[Django]-Pytest.mark.parametrize with django.test.SimpleTestCase

19πŸ‘

βœ…

The Django test class is a unittest.TestCase subclass.
Parametrization is unsupported and this is documented under the section pytest features in unittest.TestCase subclasses:


The following pytest features do not work, and probably never will due to different design philosophies:

  • Fixtures (except for autouse fixtures)
  • Parametrization
  • Custom hooks

If you need parametrized tests and pytest runner, your best bet is to abandon the unittest style – this means move the setup/teardown into fixtures (pytest-django plugin has already implemented the hard parts for you), and use module level functions for your tests.

17πŸ‘

Use @pytest.mark.django_db

Thanks, wim, for that helpful answer. RTFM, once again.

For clarity, here is the formulation that will work (equivalent to a test inheriting from TestCase, not just SimpleTestCase).
Make sure you have pytest-django installed and then do:

import pytest

@pytest.mark.django_db
class ParametrizeTest:
    @pytest.mark.parametrize("param", ["a", "b"])
    def test_pytest(self, param):
        print(param)
        assert False

(BTW: Funnily, one reason why I originally decided to use pytest was that
the idea of using plain test functions instead of test methods appealed to me;
I like lightweight approaches.
But now I almost exclusively use test classes and methods anyway,
because I prefer the explicit grouping of tests they provide.)

Leave a comment