如何在 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固定装置” 的书面方法。
软件包版本:
Django==3.1.2
pytest==6.1.1
pytest-django==4.1.0
答案 0 :(得分:3)
我发现使用“ usefixtures”方法更容易。它没有显示该函数的神奇的第二个参数,它明确标记了具有固定装置的类。
@pytest.mark.usefixtures("category")
class CategoryTest(TestCase):
def test1(self):
assert Category.objects.count() == 1
答案 1 :(得分:0)
我选择使用 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)
这使我完全放弃了基于类的测试,而只使用了基于函数的测试。