database - 如何在 Flask 应用程序中使用 pytest 清除/拆卸数据库

标签 database flask pytest

我知道这可能看起来像是重复,我在这个主题上找到了类似的问题,但没有一个真正对我有用。我只需要在每次测试后清除(或拆卸)数据库,这样每个测试都可以使用一个新的空数据库。

我正在使用固定装置,我的代码如下所示:

@pytest.fixture(scope="module", autouse=True)
def test_client_db():

    # set up
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///"
    with app.app_context():
        db.init_app(app)
        db.create_all()
    testing_client = app.test_client() 
    ctx = app.app_context()
    ctx.push()

    # do the testing
    yield testing_client

    # tear down
    with app.app_context():
        db.session.remove()
        db.drop_all()

    ctx.pop()

我是 pytest 的新手,根据我所学到的知识,无论 Yield 之前发生的事情都作为“设置”,之后发生的事情都作为“拆卸”。然而,当我运行多个测试时,每个测试的数据库并不清楚,它保存着它们之间的数据。

为什么会这样呢?这个装置有什么问题吗?我错过了什么?

最佳答案

您已将范围设置为模块 - 这意味着只有在模块中的所有测试运行完毕后, fixture 才会重置。

将范围设置为 function 或完全保留它,因为 function 是默认值。

参见https://docs.pytest.org/en/stable/fixture.html#fixture-scopes

关于database - 如何在 Flask 应用程序中使用 pytest 清除/拆卸数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63688489/

相关文章:

python - Flask 可插入 View 错误 : "Not Implemented Error"

python - Flask-Babel 的 Flask 测试设置

python - 在 Spark 本地模式下包含包

python - 使用 py.test 运行测试套件(任意测试集合)

php - 如何在数据库中找到实际的联系表格 7 结构?

mysql - 从查询中获取并回显 mysql 数组

MySQL 特殊排序

MySQL:日期字段的 CURRENT_TIMESTAMP 在本地有效但在服务器上无效

python - 两个 flask 蓝图的 url_prefix 相同

python - 返回方法的 pytests 固定装置的类型提示