gpt4 book ai didi

django - Pytest 在测试后删除数据库

转载 作者:行者123 更新时间:2023-12-05 06:23:26 26 4
gpt4 key购买 nike

我在 pytest-django 中有一个测试套件,我想在测试开始时创建一个数据库,然后在测试完成后立即删除它,以便在不保留大量数据的情况下模拟场景。任何帮助,将不胜感激。提前致谢!

最佳答案

利用 fixture teardown使用 yield 语句代替 return。这使您可以设置数据库,根据需要返回任何数据,然后执行任何清理。如果您希望对每个测试都执行此操作,而不管测试函数是否声明使用 fixture ,请将 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

关于django - Pytest 在测试后删除数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58328899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com