繁体   English   中英

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

[英]How to initialize the database with your test data for each module? Pytest-django

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

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

首先:在每个应用程序的文件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 作为工厂夹具导出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM