[英]How to use pytest fixtures with django TestCase
如何在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 fixture”文件,這是我的幾個測試所需要的。 將我的測試轉換為函數需要重新實現這個邏輯,因為沒有記錄的方式使用 pytest(或 pytest-django)導入“django 固定裝置” 。
包版本:
Django==3.1.2
pytest==6.1.1
pytest-django==4.1.0
我發現使用“usefixtures”方法更容易。 它沒有向函數顯示神奇的第二個參數,並且它明確地標記了具有固定裝置的類。
@pytest.mark.usefixtures("category")
class CategoryTest(TestCase):
def test1(self):
assert Category.objects.count() == 1
我選擇使用在session
范圍內應用的“pytest fixture”來重寫 django 的 fixture 邏輯。 您所需要的只是測試目錄根目錄下的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)
這讓我可以完全拋棄基於類的測試,而只使用基於函數的測試。
為什么需要測試用例? 我通常使用 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().name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.