【发布时间】:2019-10-10 18:17:49
【问题描述】:
我在 pytest-django 中有一个测试套件,我想在测试开始时创建一个数据库,然后在测试完成后立即删除它,以便在不保留大量数据的情况下模拟场景。 任何帮助,将不胜感激。提前致谢!
【问题讨论】:
-
查看
tearDownClass。您可以在那里重置数据库。或者在你的 pytest 配置中。
标签: django pytest pytest-django
我在 pytest-django 中有一个测试套件,我想在测试开始时创建一个数据库,然后在测试完成后立即删除它,以便在不保留大量数据的情况下模拟场景。 任何帮助,将不胜感激。提前致谢!
【问题讨论】:
tearDownClass。您可以在那里重置数据库。或者在你的 pytest 配置中。
标签: django pytest pytest-django
使用yield 语句而不是return 来利用fixture teardown。这允许您设置数据库,根据需要返回任何数据,然后执行任何清理。如果您希望无论是否声明使用夹具的测试函数都对每个测试执行此操作,请将autouse 设置为True。
@pytest.fixture(autouse=False)
def db():
# Setup DB here
# Yield some data, database connection or nothing at all
yield None
# Delete DB here when the test ends
def test_something(db):
# Database will be ready here and db will contain whatever
# db() function yields. With autouse=True you don't need to
# set the db fixture as the function param.
pass
【讨论】:
db 夹具产生的对象,那么您需要将其设置为测试函数参数。如果夹具需要在每次测试之前/之后设置/拆卸数据库,但您不需要它产生的结果,那么最好设置 @pytest.fixture(autouse=True) 并且您不需要声明它。 如果测试失败或错误会发生什么? 夹具的yield 之后的拆卸部分应该继续进行。