如何在TestCase方法中使用pytest夹具?对类似问题的几个回答似乎意味着我的例子应该有效:
import pytest
from django.test import TestCase
from myapp.models import Category
pytestmark = pytest.mark.django_db
@pytest.fixture
def category():
return Category.objects.create()
class MyappTests(TestCase):
def test1(self, category):
assert isinstance(category, Category)但这总是导致一个错误:
TypeError: test1() missing 1 required positional argument: 'category'我意识到我可以把这个简单的例子转换成一个函数,它就能工作了。我更喜欢使用django的TestCase,因为它包括了对导入传统的"django治具“文件的支持,这是我的一些测试所需要的。将我的测试转换为函数需要重新实现这个逻辑,因为没有一种用pytest (或pytest)导入"django固定装置“的记录方法。
包版本
Django==3.1.2
pytest==6.1.1
pytest-django==4.1.0发布于 2020-10-26 02:55:44
我发现使用“use”方法更容易。它没有向函数显示一个神奇的第二个参数,它显式地标记了类是否有固定装置。
@pytest.mark.usefixtures("category")
class CategoryTest(TestCase):
def test1(self):
assert Category.objects.count() == 1发布于 2020-10-27 17:04:39
我选择使用应用于session作用域的"pytest治具“重写django的夹具逻辑。您所需要的只是测试目录根目录下的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):
fixtures = [
'myapp/channel',
'myapp/country',
...
]
with django_db_blocker.unblock():
call_command('loaddata', *fixtures)这使我可以完全放弃基于类的测试,而只使用基于功能的测试。
发布于 2021-12-16 10:54:16
你为什么需要TestCase?我通常使用Python类并在那里创建测试。
示例
import pytest
from django.urls import reverse
from rest_framework import status
from store.models import Book
from store.serializers import BooksSerializer
@pytest.fixture
def test_data():
"""Поднимает временные данные."""
Book.objects.create(name='Book1', price=4000)
@pytest.fixture
def api_client():
"""Возвращает APIClient для создания запросов."""
from rest_framework.test import APIClient
return APIClient()
@pytest.mark.django_db
class TestBooks:
@pytest.mark.usefixtures("test_data")
def test_get_books_list(self, api_client):
"""GET запрос к списку книг."""
url = reverse('book-list')
excepted_data = BooksSerializer(Book.objects.all(), many=True).data
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
assert response.data == excepted_data
assert response.data[0]['name'] == Book.objects.first().namehttps://stackoverflow.com/questions/64528957
复制相似问题