小编pet*_*ter的帖子

pytest-django 数据库初始化似乎没有重新加载数据库

我们将情况归纳为以下几点:

import pytest
from django.core.management import call_command
from foo import bar

@pytest.fixture(scope='session')
def django_db_setup(django_db_setup, django_db_blocker):
    LOGGER.info('ran call_command')
    with django_db_blocker.unblock():
        call_command('loaddata', 'XXX.json')

@pytest.mark.django_db(transaction=True)
def test_t1():
    assert len(bar.objects.all())

@pytest.mark.django_db(transaction=True)
def test_t2():
    assert len(bar.objects.all())
Run Code Online (Sandbox Code Playgroud)

测试夹具 XXX.json 包括一个栏。第一个测试 (test_t1) 成功。第二个测试 (test_t2) 失败。似乎 transaction=True 属性不会导致使用来自测试装置的数据重新初始化数据库。

如果改为使用来自 unittest 的 TransactionTestCase,则初始化发生在类中的每个测试用例之前,并且所有测试都成功。

from django.test import TransactionTestCase

from foo import bar

class TestOne(TransactionTestCase):

    fixtures = ['XXX.json']

    def test_tc1(self):
        assert len(bar.objects.all())

    def test_tc2(self):
        assert len(bar.objects.all())
        objs = bar.objects.all()
        for bar in objs:
            bar.delete()

    def test_tc3(self):
        assert len(bar.objects.all())
Run Code Online (Sandbox Code Playgroud)

对于为什么 pytest 示例不会为第二个测试用例重新初始化数据库的任何观点,我将不胜感激。

python pytest django-unittest pytest-django

5
推荐指数
1
解决办法
2163
查看次数

标签 统计

django-unittest ×1

pytest ×1

pytest-django ×1

python ×1