How to use pytest fixtures in single Django TestCase test function
Test yields TypeError: test() missing 1 required positional argument: 'fix'
from django.test import TestCase
import pytest
@pytest.fixture
def fix():
return "x"
class QueryTestCase(TestCase):
def test(self, fix):
print(fix)
An almost similar case exists but I want the fixture to be used only in that particular test but not the class
You are trying to combine pytest fixtures with Django's unittest.TestCase. Django's TestCase is not compatible with pytest fixture injection directly into test methods rather it relies on unittest, which doesn’t support fixtures like that. If you want to use a pytest fixture only in a specific test, you can just use pytest function-based test:
import pytest
@pytest.fixture
def fix():
return "x"
def test_with_fix(fix):
print(fix)
Or use pytest with a class without without inheriting from Django's TestCase:
import pytest
@pytest.fixture
def fix():
return "x"
class TestQuery:
def test_with_fix(self, fix):
print(fix)
If you must use Django's TestCase, note that you can't use pytest fixtures directly. Instead, you can use self.setUp() or manually call the fixture.
from django.test import TestCase
def fix():
return "x"
class QueryTestCase(TestCase):
def test_something(self):
value = fix()
print(value)
Or use @pytest.mark.django_db if you're testing models without subclassing TestCase.