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 之前发生的任何事情都是一种“设置”,之后发生的任何事情都是“拆卸”。然而,当我运行几个测试时,每个测试的数据库都不清楚,它保存了它们之间的数据。
为什么会这样?这个夹具有什么问题?我错过了什么?
解决方案
您已将范围设置为module
- 这意味着只有在模块中的所有测试都运行后才会重置夹具。
将范围设置为function
或完全保留,这function
是默认设置。
见https://docs.pytest.org/en/stable/fixture.html#fixture-scopes
推荐阅读
- java - JSSE 和 JCE 有什么区别?
- java - 在预编译项目上使用 Maven 运行测试
- c++ - 在 C++ 中使用#include 宏来实现 mixin 模式好吗
- c# - “int”不包含“Select”的定义,并且找不到接受“int”类型的第一个参数的扩展方法“Select”
- amazon-web-services - Cloudformation Yaml 内部函数完整函数名称
- java - java Rest API中的登录身份验证获取不支持的媒体类型
- css - 为什么div周围有空格
- javascript - 禁止 setInterval 进行 REST 调用
- spring - 如何使用@SpringBootApplication 获取类注解
- sql-server - 在 SQL Server 中使用 CTE 生成自定义序列号