| 1 |
|
| 2 |
.. _`unittest.TestCase`: |
| 3 |
.. _`unittest`: |
| 4 |
|
| 5 |
How to use ``unittest``-based tests with pytest |
| 6 |
=============================================== |
| 7 |
|
| 8 |
``pytest`` supports running Python ``unittest``-based tests out of the box. |
| 9 |
It's meant for leveraging existing ``unittest``-based test suites |
| 10 |
to use pytest as a test runner and also allow to incrementally adapt |
| 11 |
the test suite to take full advantage of pytest's features. |
| 12 |
|
| 13 |
To run an existing ``unittest``-style test suite using ``pytest``, type: |
| 14 |
|
| 15 |
.. code-block:: bash |
| 16 |
|
| 17 |
pytest tests |
| 18 |
|
| 19 |
|
| 20 |
pytest will automatically collect ``unittest.TestCase`` subclasses and |
| 21 |
their ``test`` methods in ``test_*.py`` or ``*_test.py`` files. |
| 22 |
|
| 23 |
Almost all ``unittest`` features are supported: |
| 24 |
|
| 25 |
* :func:`unittest.skip`/:func:`unittest.skipIf` style decorators |
| 26 |
* :meth:`unittest.TestCase.setUp`/:meth:`unittest.TestCase.tearDown` |
| 27 |
* :meth:`unittest.TestCase.setUpClass`/:meth:`unittest.TestCase.tearDownClass` |
| 28 |
* :func:`unittest.setUpModule`/:func:`unittest.tearDownModule` |
| 29 |
* :meth:`unittest.TestCase.subTest` (since version ``9.0``) |
| 30 |
|
| 31 |
.. _`load_tests protocol`: https://docs.python.org/3/library/unittest.html#load-tests-protocol |
| 32 |
|
| 33 |
Up to this point pytest does not have support for the following features: |
| 34 |
|
| 35 |
* `load_tests protocol`_; |
| 36 |
|
| 37 |
Benefits out of the box |
| 38 |
----------------------- |
| 39 |
|
| 40 |
By running your test suite with pytest you can make use of several features, |
| 41 |
in most cases without having to modify existing code: |
| 42 |
|
| 43 |
* Obtain :ref:`more informative tracebacks <tbreportdemo>`; |
| 44 |
* :ref:`stdout and stderr <captures>` capturing; |
| 45 |
* :ref:`Test selection options <select-tests>` using :option:`-k` and :option:`-m` flags; |
| 46 |
* :ref:`maxfail`; |
| 47 |
* :ref:`--pdb <pdb-option>` command-line option for debugging on test failures |
| 48 |
(see :ref:`note <pdb-unittest-note>` below); |
| 49 |
* Distribute tests to multiple CPUs using the :pypi:`pytest-xdist` plugin; |
| 50 |
* Use :ref:`plain assert-statements <assert>` instead of ``self.assert*`` functions |
| 51 |
(:pypi:`unittest2pytest` is immensely helpful in this); |
| 52 |
|
| 53 |
|
| 54 |
pytest features in ``unittest.TestCase`` subclasses |
| 55 |
--------------------------------------------------- |
| 56 |
|
| 57 |
The following pytest features work in ``unittest.TestCase`` subclasses: |
| 58 |
|
| 59 |
* :ref:`Marks <mark>`: :ref:`skip <skip>`, :ref:`skipif <skipif>`, :ref:`xfail <xfail>`; |
| 60 |
* :ref:`Auto-use fixtures <mixing-fixtures>`; |
| 61 |
|
| 62 |
The following pytest features **do not** work, and probably |
| 63 |
never will due to different design philosophies: |
| 64 |
|
| 65 |
* :ref:`Fixtures <fixture>` (except for ``autouse`` fixtures, see :ref:`below <mixing-fixtures>`); |
| 66 |
* :ref:`Parametrization <parametrize>`; |
| 67 |
* :ref:`Custom hooks <writing-plugins>`; |
| 68 |
|
| 69 |
|
| 70 |
Third party plugins may or may not work well, depending on the plugin and the test suite. |
| 71 |
|
| 72 |
.. _mixing-fixtures: |
| 73 |
|
| 74 |
Mixing pytest fixtures into ``unittest.TestCase`` subclasses using marks |
| 75 |
------------------------------------------------------------------------ |
| 76 |
|
| 77 |
Running your unittest with ``pytest`` allows you to use its |
| 78 |
:ref:`fixture mechanism <fixture>` with ``unittest.TestCase`` style |
| 79 |
tests. Assuming you have at least skimmed the pytest fixture features, |
| 80 |
let's jump-start into an example that integrates a pytest ``db_class`` |
| 81 |
fixture, setting up a class-cached database object, and then reference |
| 82 |
it from a unittest-style test: |
| 83 |
|
| 84 |
.. code-block:: python |
| 85 |
|
| 86 |
# content of conftest.py |
| 87 |
|
| 88 |
# we define a fixture function below and it will be "used" by |
| 89 |
# referencing its name from tests |
| 90 |
|
| 91 |
import pytest |
| 92 |
|
| 93 |
|
| 94 |
@pytest.fixture(scope="class") |
| 95 |
def db_class(request): |
| 96 |
class DummyDB: |
| 97 |
pass |
| 98 |
|
| 99 |
# set a class attribute on the invoking test context |
| 100 |
request.cls.db = DummyDB() |
| 101 |
|
| 102 |
This defines a fixture function ``db_class`` which - if used - is |
| 103 |
called once for each test class and which sets the class-level |
| 104 |
``db`` attribute to a ``DummyDB`` instance. The fixture function |
| 105 |
achieves this by receiving a special ``request`` object which gives |
| 106 |
access to :ref:`the requesting test context <request-context>` such |
| 107 |
as the ``cls`` attribute, denoting the class from which the fixture |
| 108 |
is used. This architecture de-couples fixture writing from actual test |
| 109 |
code and allows reuse of the fixture by a minimal reference, the fixture |
| 110 |
name. So let's write an actual ``unittest.TestCase`` class using our |
| 111 |
fixture definition: |
| 112 |
|
| 113 |
.. code-block:: python |
| 114 |
|
| 115 |
# content of test_unittest_db.py |
| 116 |
|
| 117 |
import unittest |
| 118 |
|
| 119 |
import pytest |
| 120 |
|
| 121 |
|
| 122 |
@pytest.mark.usefixtures("db_class") |
| 123 |
class MyTest(unittest.TestCase): |
| 124 |
def test_method1(self): |
| 125 |
assert hasattr(self, "db") |
| 126 |
assert 0, self.db # fail for demo purposes |
| 127 |
|
| 128 |
def test_method2(self): |
| 129 |
assert 0, self.db # fail for demo purposes |
| 130 |
|
| 131 |
The ``@pytest.mark.usefixtures("db_class")`` class-decorator makes sure that |
| 132 |
the pytest fixture function ``db_class`` is called once per class. |
| 133 |
Due to the deliberately failing assert statements, we can take a look at |
| 134 |
the ``self.db`` values in the traceback: |
| 135 |
|
| 136 |
.. code-block:: pytest |
| 137 |
|
| 138 |
$ pytest test_unittest_db.py |
| 139 |
=========================== test session starts ============================ |
| 140 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 141 |
rootdir: /home/sweet/project |
| 142 |
collected 2 items |
| 143 |
|
| 144 |
test_unittest_db.py FF [100%] |
| 145 |
|
| 146 |
================================= FAILURES ================================= |
| 147 |
___________________________ MyTest.test_method1 ____________________________ |
| 148 |
|
| 149 |
self = <test_unittest_db.MyTest testMethod=test_method1> |
| 150 |
|
| 151 |
def test_method1(self): |
| 152 |
assert hasattr(self, "db") |
| 153 |
> assert 0, self.db # fail for demo purposes |
| 154 |
^^^^^^^^^^^^^^^^^ |
| 155 |
E AssertionError: <conftest.db_class.<locals>.DummyDB object at 0xdeadbeef0001> |
| 156 |
E assert 0 |
| 157 |
|
| 158 |
test_unittest_db.py:11: AssertionError |
| 159 |
___________________________ MyTest.test_method2 ____________________________ |
| 160 |
|
| 161 |
self = <test_unittest_db.MyTest testMethod=test_method2> |
| 162 |
|
| 163 |
def test_method2(self): |
| 164 |
> assert 0, self.db # fail for demo purposes |
| 165 |
^^^^^^^^^^^^^^^^^ |
| 166 |
E AssertionError: <conftest.db_class.<locals>.DummyDB object at 0xdeadbeef0001> |
| 167 |
E assert 0 |
| 168 |
|
| 169 |
test_unittest_db.py:14: AssertionError |
| 170 |
========================= short test summary info ========================== |
| 171 |
FAILED test_unittest_db.py::MyTest::test_method1 - AssertionError: <conft... |
| 172 |
FAILED test_unittest_db.py::MyTest::test_method2 - AssertionError: <conft... |
| 173 |
============================ 2 failed in 0.12s ============================= |
| 174 |
|
| 175 |
This default pytest traceback shows that the two test methods |
| 176 |
share the same ``self.db`` instance which was our intention |
| 177 |
when writing the class-scoped fixture function above. |
| 178 |
|
| 179 |
|
| 180 |
Using autouse fixtures and accessing other fixtures |
| 181 |
--------------------------------------------------- |
| 182 |
|
| 183 |
Although it's usually better to explicitly declare use of fixtures you need |
| 184 |
for a given test, you may sometimes want to have fixtures that are |
| 185 |
automatically used in a given context. After all, the traditional |
| 186 |
style of unittest-setup mandates the use of this implicit fixture writing |
| 187 |
and chances are, you are used to it or like it. |
| 188 |
|
| 189 |
You can flag fixture functions with ``@pytest.fixture(autouse=True)`` |
| 190 |
and define the fixture function in the context where you want it used. |
| 191 |
Let's look at an ``initdir`` fixture which makes all test methods of a |
| 192 |
``TestCase`` class execute in a temporary directory with a |
| 193 |
pre-initialized ``samplefile.ini``. Our ``initdir`` fixture itself uses |
| 194 |
the pytest builtin :fixture:`tmp_path` fixture to delegate the |
| 195 |
creation of a per-test temporary directory: |
| 196 |
|
| 197 |
.. code-block:: python |
| 198 |
|
| 199 |
# content of test_unittest_cleandir.py |
| 200 |
import unittest |
| 201 |
|
| 202 |
import pytest |
| 203 |
|
| 204 |
|
| 205 |
class MyTest(unittest.TestCase): |
| 206 |
@pytest.fixture(autouse=True) |
| 207 |
def initdir(self, tmp_path, monkeypatch): |
| 208 |
monkeypatch.chdir(tmp_path) # change to pytest-provided temporary directory |
| 209 |
tmp_path.joinpath("samplefile.ini").write_text("# testdata", encoding="utf-8") |
| 210 |
|
| 211 |
def test_method(self): |
| 212 |
with open("samplefile.ini", encoding="utf-8") as f: |
| 213 |
s = f.read() |
| 214 |
assert "testdata" in s |
| 215 |
|
| 216 |
Due to the ``autouse`` flag the ``initdir`` fixture function will be |
| 217 |
used for all methods of the class where it is defined. This is a |
| 218 |
shortcut for using a ``@pytest.mark.usefixtures("initdir")`` marker |
| 219 |
on the class like in the previous example. |
| 220 |
|
| 221 |
Running this test module ...: |
| 222 |
|
| 223 |
.. code-block:: pytest |
| 224 |
|
| 225 |
$ pytest -q test_unittest_cleandir.py |
| 226 |
. [100%] |
| 227 |
1 passed in 0.12s |
| 228 |
|
| 229 |
... gives us one passed test because the ``initdir`` fixture function |
| 230 |
was executed ahead of the ``test_method``. |
| 231 |
|
| 232 |
.. note:: |
| 233 |
|
| 234 |
``unittest.TestCase`` methods cannot directly receive fixture |
| 235 |
arguments as implementing that is likely to inflict |
| 236 |
on the ability to run general unittest.TestCase test suites. |
| 237 |
|
| 238 |
The above ``usefixtures`` and ``autouse`` examples should help to mix in |
| 239 |
pytest fixtures into unittest suites. |
| 240 |
|
| 241 |
You can also gradually move away from subclassing from ``unittest.TestCase`` to *plain asserts* |
| 242 |
and then start to benefit from the full pytest feature set step by step. |
| 243 |
|
| 244 |
.. _pdb-unittest-note: |
| 245 |
|
| 246 |
.. note:: |
| 247 |
|
| 248 |
Due to architectural differences between the two frameworks, setup and |
| 249 |
teardown for ``unittest``-based tests is performed during the ``call`` phase |
| 250 |
of testing instead of in ``pytest``'s standard ``setup`` and ``teardown`` |
| 251 |
stages. This can be important to understand in some situations, particularly |
| 252 |
when reasoning about errors. For example, if a ``unittest``-based suite |
| 253 |
exhibits errors during setup, ``pytest`` will report no errors during its |
| 254 |
``setup`` phase and will instead raise the error during ``call``. |