django_db_setup是会话作用域,因此只在测试会话开始时运行一次。当使用transaction=True时,测试后会刷新数据库,因此{}中添加的任何数据都将被删除。在
TransactionTestCase显然知道它正在使用事务,因此知道它需要为每个测试重新添加fixture。在
您有以下选项:使用范围较低的fixture,可能是注释中建议的function范围。但这很可能是opt-in,并且它将在事务中运行,因此在测试完成后将被删除。在
编写一个智能的fixture,通过检测测试何时使用事务来知道何时需要重新填充数据。但您需要确保事务中使用的数据库连接是而不是。我已经在django1.11上做过这个,它工作得很好,尽管它可能需要在升级后进行修复。看起来像这样:from unittest.mock import patch
from django.core.management import call_command
from django.db import DEFAULT_DB_ALIAS, ConnectionHandler
import pytest
_need_data_load = True
@pytest.fixture(autouse=True)
def auto_loaddata(django_db_blocker, request):
global _need_data_load
if _need_data_load:
# Use a separate DB connection to ensure we're not in a transaction.
con_h = ConnectionHandler()