在Django应用程序的测试运行中使用pytest/pytest-django时,如何将数据保存到数据库?如何使用pytest-django将测试数据保存到数据库?
我运行pytest py.test --nomigrations --reuse-db -s
和Postgres DB test_<configued_db_name>
是按预期创建的,但是在测试之间似乎没有任何东西会持久存在数据库中,并且在测试运行结束时数据库为空。
import pytest
from django.contrib.auth.models import User
@pytest.mark.django_db(transaction=False)
def test_insert_user():
user = User.objects.create_user(username="test_user", email="[email protected]", password="test")
users = User.objects.all()
assert len(users) > 0
@pytest.mark.django_db(transaction=False)
def test_check_user():
users = User.objects.all()
assert len(users) > 0
第一个测试通过,二不使我想知道如果有什么是持久化到数据库的。根据pystest-django文档@pytest.mark.django_db(transaction=False)
不会回滚受到装饰测试影响的任何内容。
谢谢
/大卫
这是测试跑步者的工作原理。如果你想在几次测试中使用相同的数据,你应该看看pytest文档中的fixtures。 –
您既可以使用灯具,也可以使用factory_boy之类的软件在测试之间提供数据。 – jvc26
谢谢。我结束了使用factory_boy和pytest的装置。 –