Debian Codegraph @

doc/en/example/parametrize.rst

raw
1
2 .. _paramexamples:
3
4 Parametrizing tests
5 =================================================
6
7 ``pytest`` allows you to easily parametrize test functions.
8 For basic docs, see :ref:`parametrize-basics`.
9
10 In the following we provide some examples using
11 the builtin mechanisms.
12
13 Generating parameters combinations, depending on command line
14 ----------------------------------------------------------------------------
15
16 .. regendoc:wipe
17
18 Let's say we want to execute a test with different computation
19 parameters and the parameter range shall be determined by a command
20 line argument. Let's first write a simple (do-nothing) computation test:
21
22 .. code-block:: python
23
24 # content of test_compute.py
25
26
27 def test_compute(param1):
28 assert param1 < 4
29
30 Now we add a test configuration like this:
31
32 .. code-block:: python
33
34 # content of conftest.py
35
36
37 def pytest_addoption(parser):
38 parser.addoption("--all", action="store_true", help="run all combinations")
39
40
41 def pytest_generate_tests(metafunc):
42 if "param1" in metafunc.fixturenames:
43 if metafunc.config.getoption("all"):
44 end = 5
45 else:
46 end = 2
47 metafunc.parametrize("param1", range(end))
48
49 This means that we only run 2 tests if we do not pass ``--all``:
50
51 .. code-block:: pytest
52
53 $ pytest -q test_compute.py
54 .. [100%]
55 2 passed in 0.12s
56
57 We run only two computations, so we see two dots.
58 let's run the full monty:
59
60 .. code-block:: pytest
61
62 $ pytest -q --all
63 ....F [100%]
64 ================================= FAILURES =================================
65 _____________________________ test_compute[4] ______________________________
66
67 param1 = 4
68
69 def test_compute(param1):
70 > assert param1 < 4
71 E assert 4 < 4
72
73 test_compute.py:4: AssertionError
74 ========================= short test summary info ==========================
75 FAILED test_compute.py::test_compute[4] - assert 4 < 4
76 1 failed, 4 passed in 0.12s
77
78 As expected when running the full range of ``param1`` values
79 we'll get an error on the last one.
80
81
82 Different options for test IDs
83 ------------------------------------
84
85 pytest will build a string that is the test ID for each set of values in a
86 parametrized test. These IDs can be used with :option:`-k` to select specific cases
87 to run, and they will also identify the specific case when one is failing.
88 Running pytest with :option:`--collect-only` will show the generated IDs.
89
90 Numbers, strings, booleans and None will have their usual string representation
91 used in the test ID. For other objects, pytest will make a string based on
92 the argument name:
93
94 .. code-block:: python
95
96 # content of test_time.py
97
98 from datetime import datetime, timedelta
99
100 import pytest
101
102 testdata = [
103 (datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1)),
104 (datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1)),
105 ]
106
107
108 @pytest.mark.parametrize("a,b,expected", testdata)
109 def test_timedistance_v0(a, b, expected):
110 diff = a - b
111 assert diff == expected
112
113
114 @pytest.mark.parametrize("a,b,expected", testdata, ids=["forward", "backward"])
115 def test_timedistance_v1(a, b, expected):
116 diff = a - b
117 assert diff == expected
118
119
120 def idfn(val):
121 if isinstance(val, (datetime,)):
122 # note this wouldn't show any hours/minutes/seconds
123 return val.strftime("%Y%m%d")
124
125
126 @pytest.mark.parametrize("a,b,expected", testdata, ids=idfn)
127 def test_timedistance_v2(a, b, expected):
128 diff = a - b
129 assert diff == expected
130
131
132 @pytest.mark.parametrize(
133 "a,b,expected",
134 [
135 pytest.param(
136 datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1), id="forward"
137 ),
138 pytest.param(
139 datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1), id="backward"
140 ),
141 ],
142 )
143 def test_timedistance_v3(a, b, expected):
144 diff = a - b
145 assert diff == expected
146
147 In ``test_timedistance_v0``, we let pytest generate the test IDs.
148
149 In ``test_timedistance_v1``, we specified ``ids`` as a list of strings which were
150 used as the test IDs. These are succinct, but can be a pain to maintain.
151
152 In ``test_timedistance_v2``, we specified ``ids`` as a function that can generate a
153 string representation to make part of the test ID. So our ``datetime`` values use the
154 label generated by ``idfn``, but because we didn't generate a label for ``timedelta``
155 objects, they are still using the default pytest representation:
156
157 .. code-block:: pytest
158
159 $ pytest test_time.py --collect-only
160 =========================== test session starts ============================
161 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
162 rootdir: /home/sweet/project
163 collected 8 items
164
165 <Dir parametrize.rst-215>
166 <Module test_time.py>
167 <Function test_timedistance_v0[a0-b0-expected0]>
168 <Function test_timedistance_v0[a1-b1-expected1]>
169 <Function test_timedistance_v1[forward]>
170 <Function test_timedistance_v1[backward]>
171 <Function test_timedistance_v2[20011212-20011211-expected0]>
172 <Function test_timedistance_v2[20011211-20011212-expected1]>
173 <Function test_timedistance_v3[forward]>
174 <Function test_timedistance_v3[backward]>
175
176 ======================== 8 tests collected in 0.12s ========================
177
178 In ``test_timedistance_v3``, we used ``pytest.param`` to specify the test IDs
179 together with the actual data, instead of listing them separately.
180
181 A quick port of "testscenarios"
182 ------------------------------------
183
184 Here is a quick port to run tests configured with :pypi:`testscenarios`,
185 an add-on from Robert Collins for the standard unittest framework. We
186 only have to work a bit to construct the correct arguments for pytest's
187 :py:func:`Metafunc.parametrize <pytest.Metafunc.parametrize>`:
188
189 .. code-block:: python
190
191 # content of test_scenarios.py
192
193
194 def pytest_generate_tests(metafunc):
195 idlist = []
196 argvalues = []
197 for scenario in metafunc.cls.scenarios:
198 idlist.append(scenario[0])
199 items = scenario[1].items()
200 argnames = [x[0] for x in items]
201 argvalues.append([x[1] for x in items])
202 metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")
203
204
205 scenario1 = ("basic", {"attribute": "value"})
206 scenario2 = ("advanced", {"attribute": "value2"})
207
208
209 class TestSampleWithScenarios:
210 scenarios = [scenario1, scenario2]
211
212 def test_demo1(self, attribute):
213 assert isinstance(attribute, str)
214
215 def test_demo2(self, attribute):
216 assert isinstance(attribute, str)
217
218 this is a fully self-contained example which you can run with:
219
220 .. code-block:: pytest
221
222 $ pytest test_scenarios.py
223 =========================== test session starts ============================
224 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
225 rootdir: /home/sweet/project
226 collected 4 items
227
228 test_scenarios.py .... [100%]
229
230 ============================ 4 passed in 0.12s =============================
231
232 If you just collect tests you'll also nicely see 'advanced' and 'basic' as variants for the test function:
233
234 .. code-block:: pytest
235
236 $ pytest --collect-only test_scenarios.py
237 =========================== test session starts ============================
238 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
239 rootdir: /home/sweet/project
240 collected 4 items
241
242 <Dir parametrize.rst-215>
243 <Module test_scenarios.py>
244 <Class TestSampleWithScenarios>
245 <Function test_demo1[basic]>
246 <Function test_demo2[basic]>
247 <Function test_demo1[advanced]>
248 <Function test_demo2[advanced]>
249
250 ======================== 4 tests collected in 0.12s ========================
251
252 Note that we told ``metafunc.parametrize()`` that your scenario values
253 should be considered class-scoped. With pytest-2.3 this leads to a
254 resource-based ordering.
255
256 Deferring the setup of parametrized resources
257 ---------------------------------------------------
258
259 .. regendoc:wipe
260
261 The parametrization of test functions happens at collection
262 time. It is a good idea to setup expensive resources like DB
263 connections or subprocess only when the actual test is run.
264 Here is a simple example how you can achieve that. This test
265 requires a ``db`` object fixture:
266
267 .. code-block:: python
268
269 # content of test_backends.py
270
271 import pytest
272
273
274 def test_db_initialized(db):
275 # a dummy test
276 if db.__class__.__name__ == "DB2":
277 pytest.fail("deliberately failing for demo purposes")
278
279 We can now add a test configuration that generates two invocations of
280 the ``test_db_initialized`` function and also implements a factory that
281 creates a database object for the actual test invocations:
282
283 .. code-block:: python
284
285 # content of conftest.py
286 import pytest
287
288
289 def pytest_generate_tests(metafunc):
290 if "db" in metafunc.fixturenames:
291 metafunc.parametrize("db", ["d1", "d2"], indirect=True)
292
293
294 class DB1:
295 "one database object"
296
297
298 class DB2:
299 "alternative database object"
300
301
302 @pytest.fixture
303 def db(request):
304 if request.param == "d1":
305 return DB1()
306 elif request.param == "d2":
307 return DB2()
308 else:
309 raise ValueError("invalid internal test config")
310
311 Let's first see how it looks like at collection time:
312
313 .. code-block:: pytest
314
315 $ pytest test_backends.py --collect-only
316 =========================== test session starts ============================
317 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
318 rootdir: /home/sweet/project
319 collected 2 items
320
321 <Dir parametrize.rst-215>
322 <Module test_backends.py>
323 <Function test_db_initialized[d1]>
324 <Function test_db_initialized[d2]>
325
326 ======================== 2 tests collected in 0.12s ========================
327
328 And then when we run the test:
329
330 .. code-block:: pytest
331
332 $ pytest -q test_backends.py
333 .F [100%]
334 ================================= FAILURES =================================
335 _________________________ test_db_initialized[d2] __________________________
336
337 db = <conftest.DB2 object at 0xdeadbeef0001>
338
339 def test_db_initialized(db):
340 # a dummy test
341 if db.__class__.__name__ == "DB2":
342 > pytest.fail("deliberately failing for demo purposes")
343 E Failed: deliberately failing for demo purposes
344
345 test_backends.py:8: Failed
346 ========================= short test summary info ==========================
347 FAILED test_backends.py::test_db_initialized[d2] - Failed: deliberately f...
348 1 failed, 1 passed in 0.12s
349
350 The first invocation with ``db == "DB1"`` passed while the second with ``db == "DB2"`` failed. Our ``db`` fixture function has instantiated each of the DB values during the setup phase while the ``pytest_generate_tests`` generated two according calls to the ``test_db_initialized`` during the collection phase.
351
352 Indirect parametrization
353 ---------------------------------------------------
354
355 Using the ``indirect=True`` parameter when parametrizing a test allows one to
356 parametrize a test with a fixture receiving the values before passing them to a
357 test:
358
359 .. code-block:: python
360
361 import pytest
362
363
364 @pytest.fixture
365 def fixt(request):
366 return request.param * 3
367
368
369 @pytest.mark.parametrize("fixt", ["a", "b"], indirect=True)
370 def test_indirect(fixt):
371 assert len(fixt) == 3
372
373
374 This can be used, for example, to do more expensive setup at test run time in
375 the fixture, rather than having to run those setup steps at collection time.
376
377 .. note::
378
379 The ``request`` argument used by the fixture is pytest's built-in
380 :py:class:`FixtureRequest <pytest.FixtureRequest>` fixture. For indirect
381 parametrization, the value supplied to the test parameter is passed to the
382 fixture and made available as ``request.param``.
383
384 For more information, see :ref:`fixture-parametrize`.
385
386 .. regendoc:wipe
387
388 Apply indirect on particular arguments
389 ---------------------------------------------------
390
391 Very often parametrization uses more than one argument name. There is opportunity to apply ``indirect``
392 parameter on particular arguments. It can be done by passing list or tuple of
393 arguments' names to ``indirect``. In the example below there is a function ``test_indirect`` which uses
394 two fixtures: ``x`` and ``y``. Here we give to indirect the list, which contains the name of the
395 fixture ``x``. The indirect parameter will be applied to this argument only, and the value ``a``
396 will be passed to respective fixture function:
397
398 .. code-block:: python
399
400 # content of test_indirect_list.py
401
402 import pytest
403
404
405 @pytest.fixture(scope="function")
406 def x(request):
407 return request.param * 3
408
409
410 @pytest.fixture(scope="function")
411 def y(request):
412 return request.param * 2
413
414
415 @pytest.mark.parametrize("x, y", [("a", "b")], indirect=["x"])
416 def test_indirect(x, y):
417 assert x == "aaa"
418 assert y == "b"
419
420 The result of this test will be successful:
421
422 .. code-block:: pytest
423
424 $ pytest -v test_indirect_list.py
425 =========================== test session starts ============================
426 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
427 cachedir: .pytest_cache
428 rootdir: /home/sweet/project
429 collecting ... collected 1 item
430
431 test_indirect_list.py::test_indirect[a-b] PASSED [100%]
432
433 ============================ 1 passed in 0.12s =============================
434
435 .. regendoc:wipe
436
437 Parametrizing test methods through per-class configuration
438 --------------------------------------------------------------
439
440 .. _`unittest parametrizer`: https://github.com/testing-cabal/unittest-ext/blob/master/params.py
441
442
443 Here is an example ``pytest_generate_tests`` function implementing a
444 parametrization scheme similar to Michael Foord's `unittest
445 parametrizer`_ but in a lot less code:
446
447 .. code-block:: python
448
449 # content of ./test_parametrize.py
450 import pytest
451
452
453 def pytest_generate_tests(metafunc):
454 # called once per each test function
455 funcarglist = metafunc.cls.params[metafunc.function.__name__]
456 argnames = sorted(funcarglist[0])
457 metafunc.parametrize(
458 argnames, [[funcargs[name] for name in argnames] for funcargs in funcarglist]
459 )
460
461
462 class TestClass:
463 # a map specifying multiple argument sets for a test method
464 params = {
465 "test_equals": [dict(a=1, b=2), dict(a=3, b=3)],
466 "test_zerodivision": [dict(a=1, b=0)],
467 }
468
469 def test_equals(self, a, b):
470 assert a == b
471
472 def test_zerodivision(self, a, b):
473 with pytest.raises(ZeroDivisionError):
474 a / b
475
476 Our test generator looks up a class-level definition which specifies which
477 argument sets to use for each test function. Let's run it:
478
479 .. code-block:: pytest
480
481 $ pytest -q
482 F.. [100%]
483 ================================= FAILURES =================================
484 ________________________ TestClass.test_equals[1-2] ________________________
485
486 self = <test_parametrize.TestClass object at 0xdeadbeef0002>, a = 1, b = 2
487
488 def test_equals(self, a, b):
489 > assert a == b
490 E assert 1 == 2
491
492 test_parametrize.py:21: AssertionError
493 ========================= short test summary info ==========================
494 FAILED test_parametrize.py::TestClass::test_equals[1-2] - assert 1 == 2
495 1 failed, 2 passed in 0.12s
496
497 Parametrization with multiple fixtures
498 --------------------------------------
499
500 Here is a stripped down real-life example of using parametrized
501 testing for testing serialization of objects between different python
502 interpreters. We define a ``test_basic_objects`` function which
503 is to be run with different sets of arguments for its three arguments:
504
505 * ``python1``: first python interpreter, run to pickle-dump an object to a file
506 * ``python2``: second interpreter, run to pickle-load an object from a file
507 * ``obj``: object to be dumped/loaded
508
509 .. literalinclude:: multipython.py
510
511 Running it results in some skips if we don't have all the python interpreters installed and otherwise runs all combinations (3 interpreters times 3 interpreters times 3 objects to serialize/deserialize):
512
513 .. code-block:: pytest
514
515 . $ pytest -rs -q multipython.py
516 ssssssssssss......sss...... [100%]
517 ========================= short test summary info ==========================
518 SKIPPED [15] multipython.py:67: 'python3.11' not found
519 12 passed, 15 skipped in 0.12s
520
521 Parametrization of optional implementations/imports
522 ---------------------------------------------------
523
524 If you want to compare the outcomes of several implementations of a given
525 API, you can write test functions that receive the already imported implementations
526 and get skipped in case the implementation is not importable/available. Let's
527 say we have a "base" implementation and the other (possibly optimized ones)
528 need to provide similar results:
529
530 .. code-block:: python
531
532 # content of conftest.py
533
534 import pytest
535
536
537 @pytest.fixture(scope="session")
538 def basemod(request):
539 return pytest.importorskip("base")
540
541
542 @pytest.fixture(scope="session", params=["opt1", "opt2"])
543 def optmod(request):
544 return pytest.importorskip(request.param)
545
546 And then a base implementation of a simple function:
547
548 .. code-block:: python
549
550 # content of base.py
551 def func1():
552 return 1
553
554 And an optimized version:
555
556 .. code-block:: python
557
558 # content of opt1.py
559 def func1():
560 return 1.0001
561
562 And finally a little test module:
563
564 .. code-block:: python
565
566 # content of test_module.py
567
568
569 def test_func1(basemod, optmod):
570 assert round(basemod.func1(), 3) == round(optmod.func1(), 3)
571
572
573 If you run this with reporting for skips enabled:
574
575 .. code-block:: pytest
576
577 $ pytest -rs test_module.py
578 =========================== test session starts ============================
579 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
580 rootdir: /home/sweet/project
581 collected 2 items
582
583 test_module.py .s [100%]
584
585 ========================= short test summary info ==========================
586 SKIPPED [1] test_module.py:3: could not import 'opt2': No module named 'opt2'
587 ======================= 1 passed, 1 skipped in 0.12s =======================
588
589 You'll see that we don't have an ``opt2`` module and thus the second test run
590 of our ``test_func1`` was skipped. A few notes:
591
592 - the fixture functions in the ``conftest.py`` file are "session-scoped" because we
593 don't need to import more than once
594
595 - if you have multiple test functions and a skipped import, you will see
596 the ``[1]`` count increasing in the report
597
598 - you can put :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>` style
599 parametrization on the test functions to parametrize input/output
600 values as well.
601
602
603 Set marks or test ID for individual parametrized test
604 --------------------------------------------------------------------
605
606 Use ``pytest.param`` to apply marks or set test ID to individual parametrized test.
607 For example:
608
609 .. code-block:: python
610
611 # content of test_pytest_param_example.py
612 import pytest
613
614
615 @pytest.mark.parametrize(
616 "test_input,expected",
617 [
618 ("3+5", 8),
619 pytest.param("1+7", 8, marks=pytest.mark.basic),
620 pytest.param("2+4", 6, marks=pytest.mark.basic, id="basic_2+4"),
621 pytest.param(
622 "6*9", 42, marks=[pytest.mark.basic, pytest.mark.xfail], id="basic_6*9"
623 ),
624 ],
625 )
626 def test_eval(test_input, expected):
627 assert eval(test_input) == expected
628
629 In this example, we have 4 parametrized tests. Except for the first test,
630 we mark the rest three parametrized tests with the custom marker ``basic``,
631 and for the fourth test we also use the built-in mark ``xfail`` to indicate this
632 test is expected to fail. For explicitness, we set test ids for some tests.
633
634 Then run ``pytest`` with verbose mode and with only the ``basic`` marker:
635
636 .. code-block:: pytest
637
638 $ pytest -v -m basic
639 =========================== test session starts ============================
640 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
641 cachedir: .pytest_cache
642 rootdir: /home/sweet/project
643 collecting ... collected 24 items / 21 deselected / 3 selected
644
645 test_pytest_param_example.py::test_eval[1+7-8] PASSED [ 33%]
646 test_pytest_param_example.py::test_eval[basic_2+4] PASSED [ 66%]
647 test_pytest_param_example.py::test_eval[basic_6*9] XFAIL [100%]
648
649 =============== 2 passed, 21 deselected, 1 xfailed in 0.12s ================
650
651 As the result:
652
653 - Four tests were collected
654 - One test was deselected because it doesn't have the ``basic`` mark.
655 - Three tests with the ``basic`` mark were selected.
656 - The test ``test_eval[1+7-8]`` passed, but the name is autogenerated and confusing.
657 - The test ``test_eval[basic_2+4]`` passed.
658 - The test ``test_eval[basic_6*9]`` was expected to fail and did fail.
659
660 .. _`parametrizing_conditional_raising`:
661
662 Parametrizing conditional raising
663 --------------------------------------------------------------------
664
665 Use :func:`pytest.raises` with the
666 :ref:`pytest.mark.parametrize ref` decorator to write parametrized tests
667 in which some tests raise exceptions and others do not.
668
669 ``contextlib.nullcontext`` can be used to test cases that are not expected to
670 raise exceptions but that should result in some value. The value is given as the
671 ``enter_result`` parameter, which will be available as the ``with`` statement’s
672 target (``e`` in the example below).
673
674 For example:
675
676 .. code-block:: python
677
678 from contextlib import nullcontext
679
680 import pytest
681
682
683 @pytest.mark.parametrize(
684 "example_input,expectation",
685 [
686 (3, nullcontext(2)),
687 (2, nullcontext(3)),
688 (1, nullcontext(6)),
689 (0, pytest.raises(ZeroDivisionError)),
690 ],
691 )
692 def test_division(example_input, expectation):
693 """Test how much I know division."""
694 with expectation as e:
695 assert (6 / example_input) == e
696
697 In the example above, the first three test cases should run without any
698 exceptions, while the fourth should raise a ``ZeroDivisionError`` exception,
699 which is expected by pytest.