如何使用pytest-django在测试之间将数据保存到DB?

时间:2015-11-25 23:34:32

标签: django pytest pytest-django

在Django应用程序的测试运行中使用pytest / pytest-django时如何将数据保存到DB?

我使用py.test --nomigrations --reuse-db -s运行pytest,并按预期创建Postgres DB test_<configued_db_name>,但是在测试之间似乎没有任何东西持续存在,并且在测试运行结束时,DB为空。< / p>

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="test_user@test.com", 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

第一次测试通过,第二次测试没有让我怀疑是否有任何东西持续存在于DB中。根据pystest-django文档@pytest.mark.django_db(transaction=False)将不会回滚受装饰测试影响的任何内容。

谢谢,

/大卫

2 个答案:

答案 0 :(得分:4)

使用每个函数的数据预填充数据库的另一种方法是:

import pytest

from django.contrib.auth.models import User

@pytest.fixture(scope='module')
def django_db_setup(django_db_setup, django_db_blocker):
    print('setup')
    with django_db_blocker.unblock():
        User.objects.create(username='a')
        assert set(u.username for u in User.objects.all()) == {'a'}

@pytest.mark.django_db
def test1():
    print('test1')
    User.objects.create(username='b')
    assert set(u.username for u in User.objects.all()) == {'a', 'b'}

@pytest.mark.django_db
def test2():
    print('test2')
    User.objects.create(username='c')
    assert set(u.username for u in User.objects.all()) == {'a', 'c'}

这种方法的好处是只能调用一次setup函数:

plugins: django-3.1.2
collected 2 items

mytest.py setup
test1
.test2
.
=================== 2 passed in 1.38 seconds ====================

糟糕的是1.38秒对于这么简单的测试来说有点太多了。 --reuse-db是一种更快捷的方式。

答案 1 :(得分:1)

我已经解决了这个问题 - 为每个函数预填充DB - 通过定义范围为function的灯具(即modelsession将不起作用)。

以下是在Django中测试视图的代码。

# This is used to fill the database more easily
from mixer.backend.django import mixer

import pytest

from django.test import RequestFactory

from inventory import views
from inventory import services

pytestmark = pytest.mark.django_db

@pytest.fixture(scope="function")
def fill_db():
    """ Just filling the DB with my data """
    for elem in services.Search().get_lookup_data():
        mixer.blend('inventory.Enumeration', **elem)

def test_grid_anonymous(fill_db):
    request = RequestFactory().get('/grid/')
    response = views.items_grid(request)
    assert response.status_code == 200, \
        "Should be callable by anyone"

def test_list_anonymous(fill_db):
    request = RequestFactory().get('/')
    response = views.items_list(request)
    assert response.status_code == 200, \
        "Should be callable by anyone"