首页 > 解决方案 > Pytest 使用 django_db 和 rest 框架

问题描述

我正在尝试django_db使用django rest framework.

基本测试设置:

import pytest
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient

@pytest.mark.django_db
def test_airport_list_real():
    client = APIClient()
    response = client.get(reverse('query_flight:airports-list'))
    assert response.status_code == 200
    assert len(response.json()) > 0

运行这个测试我得到:

___________________________ test_airport_list_real ____________________________

    @pytest.mark.django_db
    def test_airport_list_real():
        client = APIClient()
        response = client.get(reverse('query_flight:airports-list'))
        assert response.status_code == 200
>       assert len(response.json()) > 0
E       assert 0 > 0
E        +  where 0 = len([])
E        +    where [] = functools.partial(<bound method Client._parse_json of <rest_framework.test.APIClient object at 0x000001A0AB793908>>, <Response status_code=200, "application/json">)()
E        +      where functools.partial(<bound method Client._parse_json of <rest_framework.test.APIClient object at 0x000001A0AB793908>>, <Response status_code=200, "application/json">) = <Response status_code=200, "application/json">.json

query_flight\tests\query_flight\test_api.py:60: AssertionError

当我在 shell 中运行时,pipenv run python manage.py shell我得到了预期的结果: In [1]: from django.urls import reverse

In [2]: from rest_framework.test import APIClient

In [3]: client = APIClient()

In [4]: response = client.get(reverse('query_flight:airports-list'))

In [5]: len(response.json())
Out[5]: 100

使用以下软件包:

pytest-django==3.2.1
pytest [required: >=2.9, installed: 3.5.1]
djangorestframework==3.8.2
django [required: >=1.8, installed: 2.0.5]

反正有没有得到pytest办法以这种方式访问​​真实的数据库?

标签: djangodjango-rest-frameworkpytestpytest-django

解决方案


django_db标记仅负责为标记的测试提供与测试数据库的连接。传递给的 django 设置pytest-django仅负责选择测试运行中使用的数据库。

pytest-django您可以通过定义django_db_setup夹具来覆盖数据库使用情况。conftest.py如果您还没有,请在项目根目录中创建一个文件并覆盖 db 配置:

# conftest.py
import pytest

@pytest.fixture(scope='session')
def django_db_setup():
    settings.DATABASES['default'] = {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'path/to/dbfile.sqlite3',
    }

但是,您不应该在测试中使用真实的数据库。转储当前数据库以获取测试数据的快照 ( python manage.py dumpdata > testdata.json) 并将其加载到空的测试数据库中以在测试运行之前填充它:

# conftest.py
import pytest
from django.core.management import call_command

@pytest.fixture(scope='session')
def django_db_setup(django_db_setup, django_db_blocker):
    with django_db_blocker.unblock():
        call_command('loaddata', 'testdata.json')

现在,你不可能在运行测试时破坏你的真实数据库;真实数据库中的任何未来更改都不会导致测试失败(例如,当某些数据被删除时),并且您在每次测试运行时始终具有确定性状态。如果您需要一些额外的测试数据,请将其以 JSON 格式添加到testdata.json您的测试中。

来源:文档中的示例pytest-django


推荐阅读