2015-11-25 289 views
4

在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)不会回滚受到装饰测试影响的任何内容。

谢谢

/大卫

+5

这是测试跑步者的工作原理。如果你想在几次测试中使用相同的数据,你应该看看pytest文档中的fixtures。 –

+1

您既可以使用灯具,也可以使用factory_boy之类的软件在测试之间提供数据。 – jvc26

+0

谢谢。我结束了使用factory_boy和pytest的装置。 –

回答

0

我已经解决了这个问题 - 预先填入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" 
2

与每个功能的数据预先填充数据库的另一种方法是这样的:

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'} 

关于这种方法的好处是,设置功能只能调用一次:

plugins: django-3.1.2 
collected 2 items 

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

不好的一点是,1.38秒对于这样一个简单的测试来说有点太过分了。 --reuse-db是一个更快的方式来做到这一点。

+0

@dotz也许会很有趣。 –

相关问题