gpt4 book ai didi

python - 如何使用每个模块的测试数据初始化数据库? Pytest-django

转载 作者:太空宇宙 更新时间:2023-11-03 20:36:14 24 4
gpt4 key购买 nike

对于项目中的每个应用程序,您都需要编写测试。此外,对于每个应用程序,您首先需要上传测试数据,在通过所有模块测试后,必须将其删除。

我找到了几种解决方案,但在我看来,没有一个是最佳的

第一:在每个应用程序的文件 conftest.py 中,我重写方法 django_db_setup,但在这种情况下,通过模块中的测试后数据不会被删除,并且可供其他应用程序使用应用程序。理论上,通过yield的帮助,您可以在通过测试后删除所有数据。

@pytest.fixture(scope='module')
def django_db_setup(django_db_setup, django_db_blocker):
with django_db_blocker.unblock():
call_command('loaddata', './apps/accounts/fixtures/accounts.json')
call_command('loaddata', './apps/activation/fixtures/activation.json')
call_command('loaddata', './apps/questionnaire/fixtures/questionnaire.json')
yield
# delete test data

第二:在测试类中编写这样的设置

@pytest.fixture(autouse=True)
def setup(self, db):
call_command('loaddata', './apps/accounts/fixtures/accounts.json')
call_command('loaddata', './apps/activation/fixtures/activation.json')
call_command('loaddata', './apps/questionnaire/fixtures/questionnaire.json')

在这种情况下,数据的加载次数将与模块中的测试次数完全相同,这似乎也不完全正确。

最佳答案

我在自己的测试中做了类似的事情:

from pytest_django.fixtures import _django_db_fixture_helper

@pytest.fixture(autoscope='module')
def setup_db(request, django_db_setup, django_db_blocker):
_django_db_fixture_helper(request,·django_db_blocker)
call_command('loaddata', 'path/to/fixture.json')

我认为 pytest_django 应该将其官方 API 中的 _django_db_fixture_helper 导出为工厂固定装置。

关于python - 如何使用每个模块的测试数据初始化数据库? Pytest-django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57152634/

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