首页 > 解决方案 > 如何在 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 之前发生的任何事情都是一种“设置”,之后发生的任何事情都是“拆卸”。然而,当我运行几个测试时,每个测试的数据库都不清楚,它保存了它们之间的数据。

为什么会这样?这个夹具有什么问题?我错过了什么?

标签: databaseflaskpytest

解决方案


您已将范围设置为module- 这意味着只有在模块中的所有测试都运行后才会重置夹具。

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

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


推荐阅读