Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/doc/en/example/parametrize.rst

raw
1
2 .. _paramexamples:
3
4 Parametrizing tests
5 =================================================
6
7 ``pytest`` allows 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 ``-k`` to select specific cases
87 to run, and they will also identify the specific case when one is failing.
88 Running pytest with ``--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-8.x.y, pluggy-1.x.y
162 rootdir: /home/sweet/project
163 collected 8 items
164
165 <Dir parametrize.rst-199>
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-8.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-8.x.y, pluggy-1.x.y
239 rootdir: /home/sweet/project
240 collected 4 items
241
242 <Dir parametrize.rst-199>
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-8.x.y, pluggy-1.x.y
318 rootdir: /home/sweet/project
319 collected 2 items
320
321 <Dir parametrize.rst-199>
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 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 This can be used, for example, to do more expensive setup at test run time in
374 the fixture, rather than having to run those setup steps at collection time.
375
376 .. regendoc:wipe
377
378 Apply indirect on particular arguments
379 ---------------------------------------------------
380
381 Very often parametrization uses more than one argument name. There is opportunity to apply ``indirect``
382 parameter on particular arguments. It can be done by passing list or tuple of
383 arguments' names to ``indirect``. In the example below there is a function ``test_indirect`` which uses
384 two fixtures: ``x`` and ``y``. Here we give to indirect the list, which contains the name of the
385 fixture ``x``. The indirect parameter will be applied to this argument only, and the value ``a``
386 will be passed to respective fixture function:
387
388 .. code-block:: python
389
390 # content of test_indirect_list.py
391
392 import pytest
393
394
395 @pytest.fixture(scope="function")
396 def x(request):
397 return request.param * 3
398
399
400 @pytest.fixture(scope="function")
401 def y(request):
402 return request.param * 2
403
404
405 @pytest.mark.parametrize("x, y", [("a", "b")], indirect=["x"])
406 def test_indirect(x, y):
407 assert x == "aaa"
408 assert y == "b"
409
410 The result of this test will be successful:
411
412 .. code-block:: pytest
413
414 $ pytest -v test_indirect_list.py
415 =========================== test session starts ============================
416 platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
417 cachedir: .pytest_cache
418 rootdir: /home/sweet/project
419 collecting ... collected 1 item
420
421 test_indirect_list.py::test_indirect[a-b] PASSED [100%]
422
423 ============================ 1 passed in 0.12s =============================
424
425 .. regendoc:wipe
426
427 Parametrizing test methods through per-class configuration
428 --------------------------------------------------------------
429
430 .. _`unittest parametrizer`: https://github.com/testing-cabal/unittest-ext/blob/master/params.py
431
432
433 Here is an example ``pytest_generate_tests`` function implementing a
434 parametrization scheme similar to Michael Foord's `unittest
435 parametrizer`_ but in a lot less code:
436
437 .. code-block:: python
438
439 # content of ./test_parametrize.py
440 import pytest
441
442
443 def pytest_generate_tests(metafunc):
444 # called once per each test function
445 funcarglist = metafunc.cls.params[metafunc.function.__name__]
446 argnames = sorted(funcarglist[0])
447 metafunc.parametrize(
448 argnames, [[funcargs[name] for name in argnames] for funcargs in funcarglist]
449 )
450
451
452 class TestClass:
453 # a map specifying multiple argument sets for a test method
454 params = {
455 "test_equals": [dict(a=1, b=2), dict(a=3, b=3)],
456 "test_zerodivision": [dict(a=1, b=0)],
457 }
458
459 def test_equals(self, a, b):
460 assert a == b
461
462 def test_zerodivision(self, a, b):
463 with pytest.raises(ZeroDivisionError):
464 a / b
465
466 Our test generator looks up a class-level definition which specifies which
467 argument sets to use for each test function. Let's run it:
468
469 .. code-block:: pytest
470
471 $ pytest -q
472 F.. [100%]
473 ================================= FAILURES =================================
474 ________________________ TestClass.test_equals[1-2] ________________________
475
476 self = <test_parametrize.TestClass object at 0xdeadbeef0002>, a = 1, b = 2
477
478 def test_equals(self, a, b):
479 > assert a == b
480 E assert 1 == 2
481
482 test_parametrize.py:21: AssertionError
483 ========================= short test summary info ==========================
484 FAILED test_parametrize.py::TestClass::test_equals[1-2] - assert 1 == 2
485 1 failed, 2 passed in 0.12s
486
487 Parametrization with multiple fixtures
488 --------------------------------------
489
490 Here is a stripped down real-life example of using parametrized
491 testing for testing serialization of objects between different python
492 interpreters. We define a ``test_basic_objects`` function which
493 is to be run with different sets of arguments for its three arguments:
494
495 * ``python1``: first python interpreter, run to pickle-dump an object to a file
496 * ``python2``: second interpreter, run to pickle-load an object from a file
497 * ``obj``: object to be dumped/loaded
498
499 .. literalinclude:: multipython.py
500
501 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):
502
503 .. code-block:: pytest
504
505 . $ pytest -rs -q multipython.py
506 ssssssssssss...ssssssssssss [100%]
507 ========================= short test summary info ==========================
508 SKIPPED [12] multipython.py:65: 'python3.9' not found
509 SKIPPED [12] multipython.py:65: 'python3.11' not found
510 3 passed, 24 skipped in 0.12s
511
512 Parametrization of optional implementations/imports
513 ---------------------------------------------------
514
515 If you want to compare the outcomes of several implementations of a given
516 API, you can write test functions that receive the already imported implementations
517 and get skipped in case the implementation is not importable/available. Let's
518 say we have a "base" implementation and the other (possibly optimized ones)
519 need to provide similar results:
520
521 .. code-block:: python
522
523 # content of conftest.py
524
525 import pytest
526
527
528 @pytest.fixture(scope="session")
529 def basemod(request):
530 return pytest.importorskip("base")
531
532
533 @pytest.fixture(scope="session", params=["opt1", "opt2"])
534 def optmod(request):
535 return pytest.importorskip(request.param)
536
537 And then a base implementation of a simple function:
538
539 .. code-block:: python
540
541 # content of base.py
542 def func1():
543 return 1
544
545 And an optimized version:
546
547 .. code-block:: python
548
549 # content of opt1.py
550 def func1():
551 return 1.0001
552
553 And finally a little test module:
554
555 .. code-block:: python
556
557 # content of test_module.py
558
559
560 def test_func1(basemod, optmod):
561 assert round(basemod.func1(), 3) == round(optmod.func1(), 3)
562
563
564 If you run this with reporting for skips enabled:
565
566 .. code-block:: pytest
567
568 $ pytest -rs test_module.py
569 =========================== test session starts ============================
570 platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
571 rootdir: /home/sweet/project
572 collected 2 items
573
574 test_module.py .s [100%]
575
576 ========================= short test summary info ==========================
577 SKIPPED [1] test_module.py:3: could not import 'opt2': No module named 'opt2'
578 ======================= 1 passed, 1 skipped in 0.12s =======================
579
580 You'll see that we don't have an ``opt2`` module and thus the second test run
581 of our ``test_func1`` was skipped. A few notes:
582
583 - the fixture functions in the ``conftest.py`` file are "session-scoped" because we
584 don't need to import more than once
585
586 - if you have multiple test functions and a skipped import, you will see
587 the ``[1]`` count increasing in the report
588
589 - you can put :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>` style
590 parametrization on the test functions to parametrize input/output
591 values as well.
592
593
594 Set marks or test ID for individual parametrized test
595 --------------------------------------------------------------------
596
597 Use ``pytest.param`` to apply marks or set test ID to individual parametrized test.
598 For example:
599
600 .. code-block:: python
601
602 # content of test_pytest_param_example.py
603 import pytest
604
605
606 @pytest.mark.parametrize(
607 "test_input,expected",
608 [
609 ("3+5", 8),
610 pytest.param("1+7", 8, marks=pytest.mark.basic),
611 pytest.param("2+4", 6, marks=pytest.mark.basic, id="basic_2+4"),
612 pytest.param(
613 "6*9", 42, marks=[pytest.mark.basic, pytest.mark.xfail], id="basic_6*9"
614 ),
615 ],
616 )
617 def test_eval(test_input, expected):
618 assert eval(test_input) == expected
619
620 In this example, we have 4 parametrized tests. Except for the first test,
621 we mark the rest three parametrized tests with the custom marker ``basic``,
622 and for the fourth test we also use the built-in mark ``xfail`` to indicate this
623 test is expected to fail. For explicitness, we set test ids for some tests.
624
625 Then run ``pytest`` with verbose mode and with only the ``basic`` marker:
626
627 .. code-block:: pytest
628
629 $ pytest -v -m basic
630 =========================== test session starts ============================
631 platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
632 cachedir: .pytest_cache
633 rootdir: /home/sweet/project
634 collecting ... collected 24 items / 21 deselected / 3 selected
635
636 test_pytest_param_example.py::test_eval[1+7-8] PASSED [ 33%]
637 test_pytest_param_example.py::test_eval[basic_2+4] PASSED [ 66%]
638 test_pytest_param_example.py::test_eval[basic_6*9] XFAIL [100%]
639
640 =============== 2 passed, 21 deselected, 1 xfailed in 0.12s ================
641
642 As the result:
643
644 - Four tests were collected
645 - One test was deselected because it doesn't have the ``basic`` mark.
646 - Three tests with the ``basic`` mark was selected.
647 - The test ``test_eval[1+7-8]`` passed, but the name is autogenerated and confusing.
648 - The test ``test_eval[basic_2+4]`` passed.
649 - The test ``test_eval[basic_6*9]`` was expected to fail and did fail.
650
651 .. _`parametrizing_conditional_raising`:
652
653 Parametrizing conditional raising
654 --------------------------------------------------------------------
655
656 Use :func:`pytest.raises` with the
657 :ref:`pytest.mark.parametrize ref` decorator to write parametrized tests
658 in which some tests raise exceptions and others do not.
659
660 ``contextlib.nullcontext`` can be used to test cases that are not expected to
661 raise exceptions but that should result in some value. The value is given as the
662 ``enter_result`` parameter, which will be available as the ``with`` statement’s
663 target (``e`` in the example below).
664
665 For example:
666
667 .. code-block:: python
668
669 from contextlib import nullcontext
670
671 import pytest
672
673
674 @pytest.mark.parametrize(
675 "example_input,expectation",
676 [
677 (3, nullcontext(2)),
678 (2, nullcontext(3)),
679 (1, nullcontext(6)),
680 (0, pytest.raises(ZeroDivisionError)),
681 ],
682 )
683 def test_division(example_input, expectation):
684 """Test how much I know division."""
685 with expectation as e:
686 assert (6 / example_input) == e
687
688 In the example above, the first three test cases should run without any
689 exceptions, while the fourth should raise a``ZeroDivisionError`` exception,
690 which is expected by pytest.