I’m using pytest 3.2.2 and Django 1.11.5 on Python 3.6.2 on Windows.
The following code
import django.test importpytest class ParametrizeTest: @pytest.mark.parametrize("param", ["a", "b"]) def test_pytest(self, param): print(param) assert False
Works as expected:
scratch_test.py::ParametrizeTest::test_pytest[a] FAILED scratch_test.py::ParametrizeTest::test_pytest[b] failed
But once I changed it to use Django SimpleTestCase
, like this:
class ParametrizeTest(django.test.SimpleTestCase): ...
It failed
TypeError: test_pytest() is missing 1 required positional parameter: ‘param’
Can anyone explain why? How to do it?
(I actually even need to use django.test.TestCase
and access the database.)
I installed the following pytest plugins:
Plugin:random-0.2,mock-1.6.2,django-3.1.2,cov-2.5.1
But turning any (or all) of them off via -p no:random
etc. will not help.
1> wim.. :
The Django test class is a unittest.TestCase
subclass. Parameterization is not supported, this is documented in the pytest functions section of unittest.TestCase
subclasses:
The following pytest functions do not work and may never work due to different design philosophies:
Clamps (except autouse clamps)
Parameterization
Customized hook
If you need parameterized tests and a pytest runner, your best option is to abandon the unit test style – this means moving setup/teardown into fixtures (the pytest-django
plugin has Hardware components are implemented for you) and tested using module-level functionality.
2> Lutz Prechel..:
Use @pytest.mark.django_db
Thank you, thank you, for this helpful answer. RTFM, again.
For clarity, here is the preparation will (inheritance is equivalent to testing TestCase
, not just SimpleTestCase
). Make sure pytest-django
is installed, then do the following:
import pytest @pytest.mark.django_db class ParametrizeTest: @pytest.mark.parametrize("param", ["a", "b"]) def test_pytest(self, param): print(param) assert False
(As an aside, interestingly, one of the reasons I originally decided to use pytest
was that the idea of using pure test functionality rather than test methods appealed to me; I like the lightweight approach.
But now I still almost exclusively use test classes and methods because I prefer the clear grouping of tests they provide. )