Debian Codegraph @

doc/en/how-to/parametrize.rst

raw
1
2 .. _`test generators`:
3 .. _`parametrizing-tests`:
4 .. _`parametrized test functions`:
5 .. _`parametrize`:
6
7 .. _`parametrize-basics`:
8
9 How to parametrize fixtures and test functions
10 ==========================================================================
11
12 pytest enables test parametrization at several levels:
13
14 - :py:func:`pytest.fixture` allows one to :ref:`parametrize fixture
15 functions <fixture-parametrize>`.
16
17 * `@pytest.mark.parametrize`_ allows one to define multiple sets of
18 arguments and fixtures at the test function or class.
19
20 * `pytest_generate_tests`_ allows one to define custom parametrization
21 schemes or extensions.
22
23
24 .. note::
25
26 See :ref:`subtests` for an alternative to parametrization.
27
28 .. _parametrizemark:
29 .. _`@pytest.mark.parametrize`:
30
31
32 ``@pytest.mark.parametrize``: parametrizing test functions
33 ---------------------------------------------------------------------
34
35 .. regendoc: wipe
36
37 The builtin :ref:`pytest.mark.parametrize ref` decorator enables
38 parametrization of arguments for a test function. Here is a typical example
39 of a test function that implements checking that a certain input leads
40 to an expected output:
41
42 .. code-block:: python
43
44 # content of test_expectation.py
45 import pytest
46
47
48 @pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
49 def test_eval(test_input, expected):
50 assert eval(test_input) == expected
51
52 Here, the ``@parametrize`` decorator defines three different ``(test_input,expected)``
53 tuples so that the ``test_eval`` function will run three times using
54 them in turn:
55
56 .. code-block:: pytest
57
58 $ pytest
59 =========================== test session starts ============================
60 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
61 rootdir: /home/sweet/project
62 collected 3 items
63
64 test_expectation.py ..F [100%]
65
66 ================================= FAILURES =================================
67 ____________________________ test_eval[6*9-42] _____________________________
68
69 test_input = '6*9', expected = 42
70
71 @pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
72 def test_eval(test_input, expected):
73 > assert eval(test_input) == expected
74 E AssertionError: assert 54 == 42
75 E + where 54 = eval('6*9')
76
77 test_expectation.py:6: AssertionError
78 ========================= short test summary info ==========================
79 FAILED test_expectation.py::test_eval[6*9-42] - AssertionError: assert 54...
80 ======================= 1 failed, 2 passed in 0.12s ========================
81
82 .. note::
83
84 Parameter values are passed as-is to tests (no copy whatsoever).
85
86 For example, if you pass a list or a dict as a parameter value, and
87 the test case code mutates it, the mutations will be reflected in subsequent
88 test case calls.
89
90 .. note::
91
92 pytest by default escapes any non-ascii characters used in unicode strings
93 for the parametrization because it has several downsides.
94 If however you would like to use unicode strings in parametrization
95 and see them in the terminal as is (non-escaped), use this option
96 in your configuration file:
97
98 .. tab:: toml
99
100 .. code-block:: toml
101
102 [pytest]
103 disable_test_id_escaping_and_forfeit_all_rights_to_community_support = true
104
105 .. tab:: ini
106
107 .. code-block:: ini
108
109 [pytest]
110 disable_test_id_escaping_and_forfeit_all_rights_to_community_support = true
111
112 Keep in mind however that this might cause unwanted side effects and
113 even bugs depending on the OS used and plugins currently installed,
114 so use it at your own risk.
115
116
117 As designed in this example, only one pair of input/output values fails
118 the simple test function. And as usual with test function arguments,
119 you can see the ``input`` and ``output`` values in the traceback.
120
121 Note that you could also use the parametrize marker on a class or a module
122 (see :ref:`mark`) which would invoke several functions with the argument sets,
123 for instance:
124
125
126 .. code-block:: python
127
128 import pytest
129
130
131 @pytest.mark.parametrize("n,expected", [(1, 2), (3, 4)])
132 class TestClass:
133 def test_simple_case(self, n, expected):
134 assert n + 1 == expected
135
136 def test_weird_simple_case(self, n, expected):
137 assert (n * 1) + 1 == expected
138
139
140 To parametrize all tests in a module, you can assign to the :globalvar:`pytestmark` global variable:
141
142
143 .. code-block:: python
144
145 import pytest
146
147 pytestmark = pytest.mark.parametrize("n,expected", [(1, 2), (3, 4)])
148
149
150 class TestClass:
151 def test_simple_case(self, n, expected):
152 assert n + 1 == expected
153
154 def test_weird_simple_case(self, n, expected):
155 assert (n * 1) + 1 == expected
156
157
158 It is also possible to mark individual test instances within parametrize,
159 for example with the builtin ``mark.xfail``:
160
161 .. code-block:: python
162
163 # content of test_expectation.py
164 import pytest
165
166
167 @pytest.mark.parametrize(
168 "test_input,expected",
169 [("3+5", 8), ("2+4", 6), pytest.param("6*9", 42, marks=pytest.mark.xfail)],
170 )
171 def test_eval(test_input, expected):
172 assert eval(test_input) == expected
173
174 Let's run this:
175
176 .. code-block:: pytest
177
178 $ pytest
179 =========================== test session starts ============================
180 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
181 rootdir: /home/sweet/project
182 collected 3 items
183
184 test_expectation.py ..x [100%]
185
186 ======================= 2 passed, 1 xfailed in 0.12s =======================
187
188 The one parameter set which caused a failure previously now
189 shows up as an "xfailed" (expected to fail) test.
190
191 In case the values provided to ``parametrize`` result in an empty list - for
192 example, if they're dynamically generated by some function - the behaviour of
193 pytest is defined by the :confval:`empty_parameter_set_mark` option.
194
195 To get all combinations of multiple parametrized arguments you can stack
196 ``parametrize`` decorators:
197
198 .. code-block:: python
199
200 import pytest
201
202
203 @pytest.mark.parametrize("x", [0, 1])
204 @pytest.mark.parametrize("y", [2, 3])
205 def test_foo(x, y):
206 pass
207
208 This will run the test with the arguments set to ``x=0/y=2``, ``x=1/y=2``,
209 ``x=0/y=3``, and ``x=1/y=3`` exhausting parameters in the order of the decorators.
210
211
212 .. _`pytest_generate_tests`:
213
214 Basic ``pytest_generate_tests`` example
215 ---------------------------------------------
216
217 Sometimes you may want to implement your own parametrization scheme
218 or implement some dynamism for determining the parameters or scope
219 of a fixture. For this, you can use the ``pytest_generate_tests`` hook
220 which is called when collecting a test function. Through the passed in
221 ``metafunc`` object you can inspect the requesting test context and, most
222 importantly, you can call ``metafunc.parametrize()`` to cause
223 parametrization.
224
225 For example, let's say we want to run a test taking string inputs which
226 we want to set via a new ``pytest`` command line option. Let's first write
227 a simple test accepting a ``stringinput`` fixture function argument:
228
229 .. code-block:: python
230
231 # content of test_strings.py
232
233
234 def test_valid_string(stringinput):
235 assert stringinput.isalpha()
236
237 Now we add a ``conftest.py`` file containing the addition of a
238 command line option and the parametrization of our test function:
239
240 .. code-block:: python
241
242 # content of conftest.py
243
244
245 def pytest_addoption(parser):
246 parser.addoption(
247 "--stringinput",
248 action="append",
249 default=[],
250 help="list of stringinputs to pass to test functions",
251 )
252
253
254 def pytest_generate_tests(metafunc):
255 if "stringinput" in metafunc.fixturenames:
256 metafunc.parametrize("stringinput", metafunc.config.getoption("stringinput"))
257
258 .. note::
259
260 The :hook:`pytest_generate_tests` hook can also be implemented directly in a test
261 module or inside a test class; unlike other hooks, pytest will discover it there
262 as well. Other hooks must live in a :ref:`conftest.py <localplugin>` or a plugin.
263 See :ref:`writinghooks`.
264
265 If we now pass two stringinput values, our test will run twice:
266
267 .. code-block:: pytest
268
269 $ pytest -q --stringinput="hello" --stringinput="world" test_strings.py
270 .. [100%]
271 2 passed in 0.12s
272
273 Let's also run with a stringinput that will lead to a failing test:
274
275 .. code-block:: pytest
276
277 $ pytest -q --stringinput="!" test_strings.py
278 F [100%]
279 ================================= FAILURES =================================
280 ___________________________ test_valid_string[!] ___________________________
281
282 stringinput = '!'
283
284 def test_valid_string(stringinput):
285 > assert stringinput.isalpha()
286 E AssertionError: assert False
287 E + where False = <built-in method isalpha of str object at 0xdeadbeef0001>()
288 E + where <built-in method isalpha of str object at 0xdeadbeef0001> = '!'.isalpha
289
290 test_strings.py:4: AssertionError
291 ========================= short test summary info ==========================
292 FAILED test_strings.py::test_valid_string[!] - AssertionError: assert False
293 1 failed in 0.12s
294
295 As expected our test function fails.
296
297 If you don't specify a stringinput it will be skipped because
298 ``metafunc.parametrize()`` will be called with an empty parameter
299 list:
300
301 .. code-block:: pytest
302
303 $ pytest -q -rs test_strings.py
304 s [100%]
305 ========================= short test summary info ==========================
306 SKIPPED [1] test_strings.py: got empty parameter set for (stringinput)
307 1 skipped in 0.12s
308
309 Note that when calling ``metafunc.parametrize`` multiple times with different parameter sets, all parameter names across
310 those sets cannot be duplicated, otherwise an error will be raised.
311
312 More examples
313 -------------
314
315 For further examples, you might want to look at :ref:`more
316 parametrization examples <paramexamples>`.