3

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

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

首先:在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')

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

4

1 回答 1

1

我在自己的测试中做了这样的事情:

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 导出为工厂夹具。

于 2019-11-30T23:37:51.440 回答