【发布时间】:2020-02-21 10:05:24
【问题描述】:
我正在努力实现的目标。
我正在 Django 项目中测试 rest API。我想创建具有相关测试函数的测试类(以下每个测试函数都依赖于前一个) - 第一次失败意味着全部失败。在第一个测试函数中,我创建了一个带有“发布”请求的对象。在下一个测试用例中,我想使用“get”请求检查该对象是否确实存在。
工作原理
看起来 Django-pytest 在每次测试后都会从所有记录中清除数据库。
在 pytest 文档中提到:https://pytest-django.readthedocs.io/en/latest/helpers.html#pytest-mark-django-db-request-database-access
有什么办法可以改变吗?
我的代码:
我的conftest.py:
import pytest
@pytest.fixture(scope='session')
def django_db_setup():
from django.conf import settings
settings.DATABASES['default'] = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db_name.sqlite3',
}
@pytest.fixture
def object_data():
return {"some keys": "some values"}
@pytest.fixture
def object_name():
return "some name"
我的tests.py:
import pytest
from rest_framework.test import APIClient
from rest_framework import status
@pytest.mark.django_db
class TestAPI:
def setup(self):
self.client = APIClient()
def test_create_object(self, object_data, object_name):
post_response = self.client.post("/api/object/", data=object_data, format="json")
assert status.is_success(post_response.status_code)
# make sure that report was created
get_response = self.client.get(f"/api/object/{object_name}/")
assert status.is_success(get_response.status_code)
# object exists here (test passes)
def test_get_object(self, object_name):
get_response = self.client.get(f"/api/object/{object_name}/")
assert status.is_success(get_response.status_code)
# object does not exists here (test failes)
【问题讨论】:
标签: python django-rest-framework pytest-django