【发布时间】:2019-01-14 02:40:23
【问题描述】:
我正在尝试将一系列带有 pytest.parameterize 标记的故事放在一起:
conftest.py:
from django.conf import settings
import pytest
@pytest.fixture(scope='session')
def django_db_modify_db_settings():
pass
@pytest.fixture(scope='session')
def pytest_configure():
settings.configure(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
],
DATABASES=dict(default=dict(
ENGINE='django.db.backends.sqlite3',
NAME=':memory:',
))
)
test_db.py:
import pytest
from django.contrib.auth.models import Group
@pytest.mark.parametrize('name,count', [
('test', 1,),
('staff', 2),
])
@pytest.mark.django_db(transaction=True)
def test_group(name, count):
Group.objects.create(name=name)
assert Group.objects.count() == count
py.test 输出:
$ py.test test_db.py
============================================ test session starts =============================================
platform linux -- Python 3.7.2, pytest-3.10.1, py-1.5.4, pluggy-0.7.1
rootdir: /home/jpic/src/djcli, inifile:
plugins: mock-1.5.0, django-3.4.2, cov-2.6.0
collected 2 items
test_db.py .F [100%]
================================================== FAILURES ==================================================
____________________________________________ test_group[staff-2] _____________________________________________
name = 'staff', count = 2
@pytest.mark.parametrize('name,count', [
('test', 1,),
('staff', 2),
])
@pytest.mark.django_db(transaction=True)
def test_group(name, count):
Group.objects.create(name=name)
> assert Group.objects.count() == count
E assert 1 == 2
E + where 1 = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.GroupManager object at 0x7f351e01ef98>>()
E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.GroupManager object at 0x7f351e01ef98>> = <django.contrib.auth.models.GroupManager object at 0x7f351e01ef98>.count
E + where <django.contrib.auth.models.GroupManager object at 0x7f351e01ef98> = Group.objects
test_db.py:12: AssertionError
如您所见,第一个测试通过,这意味着创建了一个组并留下了一个组。
在第二个测试中,您可以看到测试失败,因为第一组已经消失。
此实现有效,但我们在摘要中的细节较少,因为它将测试归为一个。
import pytest
from django.contrib.auth.models import Group
story = [
('test', 1,),
('staff', 2),
]
@pytest.mark.django_db(transaction=True)
def test_group():
for name, count in story:
Group.objects.create(name=name)
assert Group.objects.count() == count
【问题讨论】:
-
我认为 pytest 在每次测试后回滚事务(刷新任何更改)
-
应该的,但如果有黑客我会接受它!
-
试试 django_db_keepdb 标记。测试运行后应该保留数据库
-
github.com/pytest-dev/pytest-django/blob/master/pytest_django/… 这里
test_database_exists_from_previous_run函数检查是否有要重用的数据库,对于内存数据库,它始终为False -
我认为如果你使用'pytest.fixture',你可以让后面的函数“依赖”它们之前的固定装置,他们会推迟拆除自己,直到他们和所有依赖者已完成:docs.pytest.org/en/latest/fixture.html
标签: python django pytest-django