有一个
conftest.py
文件允许我使用我的自定义事务固定装置 fake_user
@pytest.mark.django_db(transaction=True)
@pytest.fixture
def fake_user():
user = getattr(fake_user, 'user', None)
if user is None:
user_data = dict(
id=1,
is_superuser=False,
is_staff=False,
email='[email protected]',
username='foobaruser',
password='passwordmaster',
date_joined=timezone.now()
)
user = User.objects.create(
**user_data
)
user.save()
# pdb.set_trace()
fake_user.user = user
yield user
不知何故,如果我使用 pdb.set_trace() 调试上面的代码,我会得到
User.objects.all()
等于 <QuerySet [<User: foobaruser>]>
。然而没有任何真正的测试数据库记录。因此,当在另一个高级函数中查询“用户”对象时,例如“GraphQL”或 REST 调用,我得到的“Users”表绝对是空的。
如何启用真正的测试数据库事务?
为什么 pytest 不允许任何物理记录或者是什么阻止它们被插入?
Pytest 在运行之间刷新测试数据库;将
--reuse-db
添加到您的选项中以保留数据。
真正帮助我的是:
django_db_blocker
的用法:https://pytest-django.readthedocs.io/en/latest/database.html#randomize-database-sequences@pytest.fixture(scope='session')
def fake_user(django_db_setup, django_db_blocker):
user = getattr(fake_user, 'user', None)
if user is None:
user_data = dict(
id=1,
is_superuser=False,
is_staff=False,
email='[email protected]',
username='foobaruser',
password='passwordmaster',
date_joined=timezone.now()
)
with django_db_blocker.unblock():
user = User.objects.create(
**user_data
)
fake_user.user = user
yield user
数据出现在 Postgres 中。 谢谢!