Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/doc/en/how-to/unittest.rst

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