Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use pytest fixtures with django TestCase

Tags:

People also ask

Can I use pytest with Django?

pytest-django Documentation. pytest-django is a plugin for pytest that provides a set of useful tools for testing Django applications and projects.

Can a pytest fixture be a test?

Those are the things that need to test a certain action. In pytest the fixtures are functions that we define to serve these purpose, we can pass these fixtures to our test functions (test cases) so that they can run and set up the desired state for you to perform the test.

How do Django fixtures work?

fixtures . A fixture is a collection of data that Django knows how to import into a database. The most straightforward way of creating a fixture if you've already got some data is to use the manage.py dumpdata command.


How can I use a pytest fixture within a TestCase method? Several answers to similar questions seem to imply that my example should work:

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)

But this always results in an error:

TypeError: test1() missing 1 required positional argument: 'category'

I realize I could just convert this trivial example into a function, and it would work. I would prefer to use django's TestCase because it includes support for importing traditional "django fixture" files, which several of my tests require. Converting my tests to functions would require re-implementing this logic, since there isn't a documented way of importing "django fixtures" with pytest (or pytest-django).

package versions:

Django==3.1.2
pytest==6.1.1
pytest-django==4.1.0