对于项目中的每个应用程序,您需要编写测试。此外,对于每个应用程序,您首先需要上传测试数据,在通过所有模块测试后,必须删除这些数据。
我找到了几种解决方案,但在我看来没有一个是最佳的
第一: 在每个应用程序中的文件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应该将_django_db_fixture_helper作为工厂固定装置导出到其官方 API 中。