【发布时间】:2019-02-27 09:23:20
【问题描述】:
这个问题背后的想法很容易理解,但解决起来很复杂:我需要在测试之间共享数据。
我有一个 Django 项目,我使用 pytest-django 和 pytest-descibe 来定义和运行测试。
虽然在 pytest 中,数据库在每次测试后都会回滚,但在“描述方式”中,在同一描述中的测试之间共享“上下文”是很常见的。 这使得编写测试更具可读性和运行速度更快,并且允许运行所有断言,即使其间单个测试失败。
出于这个原因,我想在每个测试中关闭数据库回滚的默认行为,而是在整个描述运行后执行。
这是我的测试的简化版本:
pytestmark = [pytest.mark.django_db]
def describe_users():
email = 'foo@example.com'
def test_create_a_user_and_it_exists():
User.objects.create(email=email)
assert User.objects.filter(email=email).exists() # Pass
def test_the_user_keeps_to_exist():
assert User.objects.filter(email=email).exists() # Fail
我尝试使用文档中建议的夹具db_access_without_rollback_and_truncate,但没有成功,每次测试后数据库仍会重置。
有没有简单的方法来实现这一点?
提前致谢。
【问题讨论】:
-
您使用的夹具对
read only数据库有效,对于您的要求,这更合适 - pytest-django.readthedocs.io/en/latest/… 或 pytest-django.readthedocs.io/en/latest/… -
也许我不知道如何使用它,但它似乎不起作用。但是,我需要基于模块而不是基于会话的东西。
标签: django pytest pytest-django