Debian Codegraph @

doc/en/how-to/output.rst

raw
1 .. _how-to-manage-output:
2
3 Managing pytest's output
4 =========================
5
6 .. _how-to-modifying-python-tb-printing:
7
8 Modifying Python traceback printing
9 --------------------------------------------------
10
11 Examples for modifying traceback printing:
12
13 .. code-block:: bash
14
15 pytest --showlocals # show local variables in tracebacks
16 pytest -l # show local variables (shortcut)
17 pytest --no-showlocals # hide local variables (if addopts enables them)
18
19 pytest --capture=fd # default, capture at the file descriptor level
20 pytest --capture=sys # capture at the sys level
21 pytest --capture=no # don't capture
22 pytest -s # don't capture (shortcut)
23 pytest --capture=tee-sys # capture to logs but also output to sys level streams
24
25 pytest --tb=auto # (default) 'long' tracebacks for the first and last
26 # entry, but 'short' style for the other entries
27 pytest --tb=long # exhaustive, informative traceback formatting
28 pytest --tb=short # shorter traceback format
29 pytest --tb=line # only one line per failure
30 pytest --tb=native # Python standard library formatting
31 pytest --tb=no # no traceback at all
32
33 The :option:`--full-trace` causes very long traces to be printed on error (longer
34 than :option:`--tb=long`). It also ensures that a stack trace is printed on
35 **KeyboardInterrupt** (Ctrl+C).
36 This is very useful if the tests are taking too long and you interrupt them
37 with Ctrl+C to find out where the tests are *hanging*. By default no output
38 will be shown (because KeyboardInterrupt is caught by pytest). By using this
39 option you make sure a trace is shown.
40
41
42 Verbosity
43 --------------------------------------------------
44
45 Examples for modifying printing verbosity:
46
47 .. code-block:: bash
48
49 pytest --quiet # quiet - less verbose - mode
50 pytest -q # quiet - less verbose - mode (shortcut)
51 pytest -v # increase verbosity, display individual test names
52 pytest -vv # more verbose, display more details from the test output
53 pytest -vvv # not a standard , but may be used for even more detail in certain setups
54
55 The :option:`-v` flag controls the verbosity of pytest output in various aspects: test session progress, assertion
56 details when tests fail, fixtures details with :option:`--fixtures`, etc.
57
58 .. regendoc:wipe
59
60 Consider this simple file:
61
62 .. code-block:: python
63
64 # content of test_verbosity_example.py
65 def test_ok():
66 pass
67
68
69 def test_words_fail():
70 fruits1 = ["banana", "apple", "grapes", "melon", "kiwi"]
71 fruits2 = ["banana", "apple", "orange", "melon", "kiwi"]
72 assert fruits1 == fruits2
73
74
75 def test_numbers_fail():
76 number_to_text1 = {str(x): x for x in range(5)}
77 number_to_text2 = {str(x * 10): x * 10 for x in range(5)}
78 assert number_to_text1 == number_to_text2
79
80
81 def test_long_text_fail():
82 long_text = "Lorem ipsum dolor sit amet " * 10
83 assert "hello world" in long_text
84
85 Executing pytest normally gives us this output (we are skipping the header to focus on the rest):
86
87 .. code-block:: pytest
88
89 $ pytest --no-header
90 =========================== test session starts ============================
91 collected 4 items
92
93 test_verbosity_example.py .FFF [100%]
94
95 ================================= FAILURES =================================
96 _____________________________ test_words_fail ______________________________
97
98 def test_words_fail():
99 fruits1 = ["banana", "apple", "grapes", "melon", "kiwi"]
100 fruits2 = ["banana", "apple", "orange", "melon", "kiwi"]
101 > assert fruits1 == fruits2
102 E AssertionError: assert ['banana', 'a...elon', 'kiwi'] == ['banana', 'a...elon', 'kiwi']
103 E
104 E At index 2 diff: 'grapes' != 'orange'
105 E Use -v to get more diff
106
107 test_verbosity_example.py:8: AssertionError
108 ____________________________ test_numbers_fail _____________________________
109
110 def test_numbers_fail():
111 number_to_text1 = {str(x): x for x in range(5)}
112 number_to_text2 = {str(x * 10): x * 10 for x in range(5)}
113 > assert number_to_text1 == number_to_text2
114 E AssertionError: assert {'0': 0, '1':..., '3': 3, ...} == {'0': 0, '10'...'30': 30, ...}
115 E
116 E Omitting 1 identical items, use -vv to show
117 E Left contains 4 more items:
118 E {'1': 1, '2': 2, '3': 3, '4': 4}
119 E Right contains 4 more items:
120 E {'10': 10, '20': 20, '30': 30, '40': 40}
121 E Use -v to get more diff
122
123 test_verbosity_example.py:14: AssertionError
124 ___________________________ test_long_text_fail ____________________________
125
126 def test_long_text_fail():
127 long_text = "Lorem ipsum dolor sit amet " * 10
128 > assert "hello world" in long_text
129 E AssertionError: assert 'hello world' in 'Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ips... sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet '
130
131 test_verbosity_example.py:19: AssertionError
132 ========================= short test summary info ==========================
133 FAILED test_verbosity_example.py::test_words_fail - AssertionError: asser...
134 FAILED test_verbosity_example.py::test_numbers_fail - AssertionError: ass...
135 FAILED test_verbosity_example.py::test_long_text_fail - AssertionError: a...
136 ======================= 3 failed, 1 passed in 0.12s ========================
137
138 Notice that:
139
140 * Each test inside the file is shown by a single character in the output: ``.`` for passing, ``F`` for failure.
141 * ``test_words_fail`` failed, and we are shown a short summary indicating the index 2 of the two lists differ.
142 * ``test_numbers_fail`` failed, and we are shown a summary of left/right differences on dictionary items. Identical items are omitted.
143 * ``test_long_text_fail`` failed, and the right hand side of the ``in`` statement is truncated using ``...```
144 because it is longer than an internal threshold (240 characters currently).
145
146 Now we can increase pytest's verbosity:
147
148 .. code-block:: pytest
149
150 $ pytest --no-header -v
151 =========================== test session starts ============================
152 collecting ... collected 4 items
153
154 test_verbosity_example.py::test_ok PASSED [ 25%]
155 test_verbosity_example.py::test_words_fail FAILED [ 50%]
156 test_verbosity_example.py::test_numbers_fail FAILED [ 75%]
157 test_verbosity_example.py::test_long_text_fail FAILED [100%]
158
159 ================================= FAILURES =================================
160 _____________________________ test_words_fail ______________________________
161
162 def test_words_fail():
163 fruits1 = ["banana", "apple", "grapes", "melon", "kiwi"]
164 fruits2 = ["banana", "apple", "orange", "melon", "kiwi"]
165 > assert fruits1 == fruits2
166 E AssertionError: assert ['banana', 'a...elon', 'kiwi'] == ['banana', 'a...elon', 'kiwi']
167 E
168 E At index 2 diff: 'grapes' != 'orange'
169 E
170 E Full diff:
171 E [
172 E 'banana',
173 E 'apple',...
174 E
175 E ...Full output truncated (7 lines hidden), use '-vv' to show
176
177 test_verbosity_example.py:8: AssertionError
178 ____________________________ test_numbers_fail _____________________________
179
180 def test_numbers_fail():
181 number_to_text1 = {str(x): x for x in range(5)}
182 number_to_text2 = {str(x * 10): x * 10 for x in range(5)}
183 > assert number_to_text1 == number_to_text2
184 E AssertionError: assert {'0': 0, '1':..., '3': 3, ...} == {'0': 0, '10'...'30': 30, ...}
185 E
186 E Omitting 1 identical items, use -vv to show
187 E Left contains 4 more items:
188 E {'1': 1, '2': 2, '3': 3, '4': 4}
189 E Right contains 4 more items:
190 E {'10': 10, '20': 20, '30': 30, '40': 40}
191 E ...
192 E
193 E ...Full output truncated (16 lines hidden), use '-vv' to show
194
195 test_verbosity_example.py:14: AssertionError
196 ___________________________ test_long_text_fail ____________________________
197
198 def test_long_text_fail():
199 long_text = "Lorem ipsum dolor sit amet " * 10
200 > assert "hello world" in long_text
201 E AssertionError: assert 'hello world' in 'Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet '
202
203 test_verbosity_example.py:19: AssertionError
204 ========================= short test summary info ==========================
205 FAILED test_verbosity_example.py::test_words_fail - AssertionError: asser...
206 FAILED test_verbosity_example.py::test_numbers_fail - AssertionError: ass...
207 FAILED test_verbosity_example.py::test_long_text_fail - AssertionError: a...
208 ======================= 3 failed, 1 passed in 0.12s ========================
209
210 Notice now that:
211
212 * Each test inside the file gets its own line in the output.
213 * ``test_words_fail`` now shows the two failing lists in full, in addition to which index differs.
214 * ``test_numbers_fail`` now shows a text diff of the two dictionaries, truncated.
215 * ``test_long_text_fail`` no longer truncates the right hand side of the ``in`` statement, because the internal
216 threshold for truncation is larger now (2400 characters currently).
217
218 Now if we increase verbosity even more:
219
220 .. code-block:: pytest
221
222 $ pytest --no-header -vv
223 =========================== test session starts ============================
224 collecting ... collected 4 items
225
226 test_verbosity_example.py::test_ok PASSED [ 25%]
227 test_verbosity_example.py::test_words_fail FAILED [ 50%]
228 test_verbosity_example.py::test_numbers_fail FAILED [ 75%]
229 test_verbosity_example.py::test_long_text_fail FAILED [100%]
230
231 ================================= FAILURES =================================
232 _____________________________ test_words_fail ______________________________
233
234 def test_words_fail():
235 fruits1 = ["banana", "apple", "grapes", "melon", "kiwi"]
236 fruits2 = ["banana", "apple", "orange", "melon", "kiwi"]
237 > assert fruits1 == fruits2
238 E AssertionError: assert ['banana', 'apple', 'grapes', 'melon', 'kiwi'] == ['banana', 'apple', 'orange', 'melon', 'kiwi']
239 E
240 E At index 2 diff: 'grapes' != 'orange'
241 E
242 E Full diff:
243 E [
244 E 'banana',
245 E 'apple',
246 E - 'orange',
247 E ? ^ ^^
248 E + 'grapes',
249 E ? ^ ^ +
250 E 'melon',
251 E 'kiwi',
252 E ]
253
254 test_verbosity_example.py:8: AssertionError
255 ____________________________ test_numbers_fail _____________________________
256
257 def test_numbers_fail():
258 number_to_text1 = {str(x): x for x in range(5)}
259 number_to_text2 = {str(x * 10): x * 10 for x in range(5)}
260 > assert number_to_text1 == number_to_text2
261 E AssertionError: assert {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4} == {'0': 0, '10': 10, '20': 20, '30': 30, '40': 40}
262 E
263 E Common items:
264 E {'0': 0}
265 E Left contains 4 more items:
266 E {'1': 1, '2': 2, '3': 3, '4': 4}
267 E Right contains 4 more items:
268 E {'10': 10, '20': 20, '30': 30, '40': 40}
269 E
270 E Full diff:
271 E {
272 E '0': 0,
273 E - '10': 10,
274 E ? - -
275 E + '1': 1,
276 E - '20': 20,
277 E ? - -
278 E + '2': 2,
279 E - '30': 30,
280 E ? - -
281 E + '3': 3,
282 E - '40': 40,
283 E ? - -
284 E + '4': 4,
285 E }
286
287 test_verbosity_example.py:14: AssertionError
288 ___________________________ test_long_text_fail ____________________________
289
290 def test_long_text_fail():
291 long_text = "Lorem ipsum dolor sit amet " * 10
292 > assert "hello world" in long_text
293 E AssertionError: assert 'hello world' in 'Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet '
294
295 test_verbosity_example.py:19: AssertionError
296 ========================= short test summary info ==========================
297 FAILED test_verbosity_example.py::test_words_fail - AssertionError: assert ['banana', 'apple', 'grapes', 'melon', 'kiwi'] == ['banana', 'apple', 'orange', 'melon', 'kiwi']
298
299 At index 2 diff: 'grapes' != 'orange'
300
301 Full diff:
302 [
303 'banana',
304 'apple',
305 - 'orange',
306 ? ^ ^^
307 + 'grapes',
308 ? ^ ^ +
309 'melon',
310 'kiwi',
311 ]
312 FAILED test_verbosity_example.py::test_numbers_fail - AssertionError: assert {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4} == {'0': 0, '10': 10, '20': 20, '30': 30, '40': 40}
313
314 Common items:
315 {'0': 0}
316 Left contains 4 more items:
317 {'1': 1, '2': 2, '3': 3, '4': 4}
318 Right contains 4 more items:
319 {'10': 10, '20': 20, '30': 30, '40': 40}
320
321 Full diff:
322 {
323 '0': 0,
324 - '10': 10,
325 ? - -
326 + '1': 1,
327 - '20': 20,
328 ? - -
329 + '2': 2,
330 - '30': 30,
331 ? - -
332 + '3': 3,
333 - '40': 40,
334 ? - -
335 + '4': 4,
336 }
337 FAILED test_verbosity_example.py::test_long_text_fail - AssertionError: assert 'hello world' in 'Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet '
338 ======================= 3 failed, 1 passed in 0.12s ========================
339
340 Notice now that:
341
342 * Each test inside the file gets its own line in the output.
343 * ``test_words_fail`` gives the same output as before in this case.
344 * ``test_numbers_fail`` now shows a full text diff of the two dictionaries.
345 * ``test_long_text_fail`` also doesn't truncate on the right hand side as before, but now pytest won't truncate any
346 text at all, regardless of its size.
347
348 Those were examples of how verbosity affects normal test session output, but verbosity also is used in other
349 situations, for example you are shown even fixtures that start with ``_`` if you use ``pytest --fixtures -v``.
350
351 Using higher verbosity levels (``-vvv``, ``-vvvv``, ...) is supported, but has no effect in pytest itself at the moment,
352 however some plugins might make use of higher verbosity.
353
354 .. _`pytest.fine_grained_verbosity`:
355
356 Fine-grained verbosity
357 ~~~~~~~~~~~~~~~~~~~~~~
358
359 In addition to specifying the application wide verbosity level, it is possible to control specific aspects independently.
360 This is done by setting a verbosity level in the configuration file for the specific aspect of the output.
361
362 :confval:`verbosity_assertions`: Controls how verbose the assertion output should be when pytest is executed. Running
363 ``pytest --no-header`` with a value of ``2`` would have the same output as the previous example, but each test inside
364 the file is shown by a single character in the output.
365
366 :confval:`assertion_text_diff_style`: Controls how pytest renders ``str == str`` failures.
367
368 * ``ndiff`` (the default) outputs the differences using inline diff markers.
369 * ``block`` prints string comparisons as separate ``Left:`` and ``Right:`` blocks, which can be easier to read when whitespace or indentation differences dominate.
370
371 Note that it is possible to set this option (as any other configuration option) directly in the command line using ``-o assertion_text_diff_style=block``.
372
373 :confval:`verbosity_test_cases`: Controls how verbose the test execution output should be when pytest is executed.
374 Running ``pytest --no-header`` with a value of ``2`` would have the same output as the first verbosity example, but each
375 test inside the file gets its own line in the output.
376
377 .. _`pytest.detailed_failed_tests_usage`:
378
379 Producing a detailed summary report
380 --------------------------------------------------
381
382 The :option:`-r` flag can be used to display a "short test summary info" at the end of the test session,
383 making it easy in large test suites to get a clear picture of all failures, skips, xfails, etc.
384
385 It defaults to ``fE`` to list failures and errors.
386
387 .. regendoc:wipe
388
389 Example:
390
391 .. code-block:: python
392
393 # content of test_example.py
394 import pytest
395
396
397 @pytest.fixture
398 def error_fixture():
399 assert 0
400
401
402 def test_ok():
403 print("ok")
404
405
406 def test_fail():
407 assert 0
408
409
410 def test_error(error_fixture):
411 pass
412
413
414 def test_skip():
415 pytest.skip("skipping this test")
416
417
418 def test_xfail():
419 pytest.xfail("xfailing this test")
420
421
422 @pytest.mark.xfail(reason="always xfail")
423 def test_xpass():
424 pass
425
426
427 .. code-block:: pytest
428
429 $ pytest -ra
430 =========================== test session starts ============================
431 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
432 rootdir: /home/sweet/project
433 collected 6 items
434
435 test_example.py .FEsxX [100%]
436
437 ================================== ERRORS ==================================
438 _______________________ ERROR at setup of test_error _______________________
439
440 @pytest.fixture
441 def error_fixture():
442 > assert 0
443 E assert 0
444
445 test_example.py:6: AssertionError
446 ================================= FAILURES =================================
447 ________________________________ test_fail _________________________________
448
449 def test_fail():
450 > assert 0
451 E assert 0
452
453 test_example.py:14: AssertionError
454 ================================= XPASSES ==================================
455 ========================= short test summary info ==========================
456 SKIPPED [1] test_example.py:22: skipping this test
457 XFAIL test_example.py::test_xfail - xfailing this test
458 XPASS test_example.py::test_xpass - always xfail
459 ERROR test_example.py::test_error - assert 0
460 FAILED test_example.py::test_fail - assert 0
461 == 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s ===
462
463 The :option:`-r` options accepts a number of characters after it, with ``a`` used
464 above meaning "all except passes".
465
466 Here is the full list of available characters that can be used:
467
468 - ``f`` - failed
469 - ``E`` - error
470 - ``s`` - skipped
471 - ``x`` - xfailed
472 - ``X`` - xpassed
473 - ``p`` - passed
474 - ``P`` - passed with output
475
476 Special characters for (de)selection of groups:
477
478 - ``a`` - all except ``pP``
479 - ``A`` - all
480 - ``N`` - none, this can be used to display nothing (since ``fE`` is the default)
481
482 More than one character can be used, so for example to only see failed and skipped tests, you can execute:
483
484 .. code-block:: pytest
485
486 $ pytest -rfs
487 =========================== test session starts ============================
488 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
489 rootdir: /home/sweet/project
490 collected 6 items
491
492 test_example.py .FEsxX [100%]
493
494 ================================== ERRORS ==================================
495 _______________________ ERROR at setup of test_error _______________________
496
497 @pytest.fixture
498 def error_fixture():
499 > assert 0
500 E assert 0
501
502 test_example.py:6: AssertionError
503 ================================= FAILURES =================================
504 ________________________________ test_fail _________________________________
505
506 def test_fail():
507 > assert 0
508 E assert 0
509
510 test_example.py:14: AssertionError
511 ========================= short test summary info ==========================
512 FAILED test_example.py::test_fail - assert 0
513 SKIPPED [1] test_example.py:22: skipping this test
514 == 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s ===
515
516 Using ``p`` lists the passing tests, whilst ``P`` adds an extra section "PASSES" with those tests that passed but had
517 captured output:
518
519 .. code-block:: pytest
520
521 $ pytest -rpP
522 =========================== test session starts ============================
523 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
524 rootdir: /home/sweet/project
525 collected 6 items
526
527 test_example.py .FEsxX [100%]
528
529 ================================== ERRORS ==================================
530 _______________________ ERROR at setup of test_error _______________________
531
532 @pytest.fixture
533 def error_fixture():
534 > assert 0
535 E assert 0
536
537 test_example.py:6: AssertionError
538 ================================= FAILURES =================================
539 ________________________________ test_fail _________________________________
540
541 def test_fail():
542 > assert 0
543 E assert 0
544
545 test_example.py:14: AssertionError
546 ================================== PASSES ==================================
547 _________________________________ test_ok __________________________________
548 --------------------------- Captured stdout call ---------------------------
549 ok
550 ========================= short test summary info ==========================
551 PASSED test_example.py::test_ok
552 == 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s ===
553
554 .. note::
555
556 By default, parametrized variants of skipped tests are grouped together if
557 they share the same skip reason. You can use :option:`--no-fold-skipped` to print each skipped test separately.
558
559
560 .. _truncation-params:
561
562 Modifying truncation limits
563 --------------------------------------------------
564
565 .. versionadded: 8.4
566
567 Default truncation limits are 8 lines or 640 characters, whichever comes first.
568 To set custom truncation limits you can use the following configuration file options:
569
570 .. tab:: toml
571
572 .. code-block:: toml
573
574 [pytest]
575 truncation_limit_lines = 10
576 truncation_limit_chars = 90
577
578 .. tab:: ini
579
580 .. code-block:: ini
581
582 [pytest]
583 truncation_limit_lines = 10
584 truncation_limit_chars = 90
585
586 That will cause pytest to truncate the assertions to 10 lines or 90 characters, whichever comes first.
587
588 Setting both :confval:`truncation_limit_lines` and :confval:`truncation_limit_chars` to ``0`` will disable the truncation.
589 However, setting only one of those values will disable one truncation mode, but will leave the other one intact.
590
591
592 Creating JUnitXML format files
593 ----------------------------------------------------
594
595 To create result files which can be read by Jenkins_ or other Continuous
596 integration servers, use this invocation:
597
598 .. code-block:: bash
599
600 pytest --junit-xml=path
601
602 to create an XML file at ``path``.
603
604
605
606 To set the name of the root test suite xml item, you can configure the ``junit_suite_name`` option in your config file:
607
608 .. tab:: toml
609
610 .. code-block:: toml
611
612 [pytest]
613 junit_suite_name = "my_suite"
614
615 .. tab:: ini
616
617 .. code-block:: ini
618
619 [pytest]
620 junit_suite_name = my_suite
621
622 .. versionadded:: 4.0
623
624 JUnit XML specification seems to indicate that ``"time"`` attribute
625 should report total test execution times, including setup and teardown
626 (`1 <http://windyroad.com.au/dl/Open%20Source/JUnit.xsd>`_, `2
627 <https://www.ibm.com/support/knowledgecenter/en/SSQ2R2_14.1.0/com.ibm.rsar.analysis.codereview.cobol.doc/topics/cac_useresults_junit.html>`_).
628 It is the default pytest behavior. To report just call durations
629 instead, configure the ``junit_duration_report`` option like this:
630
631 .. tab:: toml
632
633 .. code-block:: toml
634
635 [pytest]
636 junit_duration_report = "call"
637
638 .. tab:: ini
639
640 .. code-block:: ini
641
642 [pytest]
643 junit_duration_report = call
644
645 .. _record_property example:
646
647 record_property
648 ~~~~~~~~~~~~~~~~~
649
650 If you want to log additional information for a test, you can use the
651 ``record_property`` fixture:
652
653 .. code-block:: python
654
655 def test_function(record_property):
656 record_property("example_key", 1)
657 assert True
658
659 This will add an extra property ``example_key="1"`` to the generated
660 ``testcase`` tag:
661
662 .. code-block:: xml
663
664 <testcase classname="test_function" file="test_function.py" line="0" name="test_function" time="0.0009">
665 <properties>
666 <property name="example_key" value="1" />
667 </properties>
668 </testcase>
669
670 Alternatively, you can integrate this functionality with custom markers:
671
672 .. code-block:: python
673
674 # content of conftest.py
675
676
677 def pytest_collection_modifyitems(session, config, items):
678 for item in items:
679 for marker in item.iter_markers(name="test_id"):
680 test_id = marker.args[0]
681 item.user_properties.append(("test_id", test_id))
682
683 And in your tests:
684
685 .. code-block:: python
686
687 # content of test_function.py
688 import pytest
689
690
691 @pytest.mark.test_id(1501)
692 def test_function():
693 assert True
694
695 Will result in:
696
697 .. code-block:: xml
698
699 <testcase classname="test_function" file="test_function.py" line="0" name="test_function" time="0.0009">
700 <properties>
701 <property name="test_id" value="1501" />
702 </properties>
703 </testcase>
704
705 .. warning::
706
707 Please note that using this feature will break schema verifications for the latest JUnitXML schema.
708 This might be a problem when used with some CI servers.
709
710
711 record_xml_attribute
712 ~~~~~~~~~~~~~~~~~~~~~~~
713
714 To add an additional xml attribute to a testcase element, you can use
715 ``record_xml_attribute`` fixture. This can also be used to override existing values:
716
717 .. code-block:: python
718
719 def test_function(record_xml_attribute):
720 record_xml_attribute("assertions", "REQ-1234")
721 record_xml_attribute("classname", "custom_classname")
722 print("hello world")
723 assert True
724
725 Unlike ``record_property``, this will not add a new child element.
726 Instead, this will add an attribute ``assertions="REQ-1234"`` inside the generated
727 ``testcase`` tag and override the default ``classname`` with ``"classname=custom_classname"``:
728
729 .. code-block:: xml
730
731 <testcase classname="custom_classname" file="test_function.py" line="0" name="test_function" time="0.003" assertions="REQ-1234">
732 <system-out>
733 hello world
734 </system-out>
735 </testcase>
736
737 .. warning::
738
739 ``record_xml_attribute`` is an experimental feature, and its interface might be replaced
740 by something more powerful and general in future versions. The
741 functionality per-se will be kept, however.
742
743 Using this over ``record_xml_property`` can help when using ci tools to parse the xml report.
744 However, some parsers are quite strict about the elements and attributes that are allowed.
745 Many tools use an xsd schema (like the example below) to validate incoming xml.
746 Make sure you are using attribute names that are allowed by your parser.
747
748 Below is the Scheme used by Jenkins to validate the XML report:
749
750 .. code-block:: xml
751
752 <xs:element name="testcase">
753 <xs:complexType>
754 <xs:sequence>
755 <xs:element ref="skipped" minOccurs="0" maxOccurs="1"/>
756 <xs:element ref="error" minOccurs="0" maxOccurs="unbounded"/>
757 <xs:element ref="failure" minOccurs="0" maxOccurs="unbounded"/>
758 <xs:element ref="system-out" minOccurs="0" maxOccurs="unbounded"/>
759 <xs:element ref="system-err" minOccurs="0" maxOccurs="unbounded"/>
760 </xs:sequence>
761 <xs:attribute name="name" type="xs:string" use="required"/>
762 <xs:attribute name="assertions" type="xs:string" use="optional"/>
763 <xs:attribute name="time" type="xs:string" use="optional"/>
764 <xs:attribute name="classname" type="xs:string" use="optional"/>
765 <xs:attribute name="status" type="xs:string" use="optional"/>
766 </xs:complexType>
767 </xs:element>
768
769 .. warning::
770
771 Please note that using this feature will break schema verifications for the latest JUnitXML schema.
772 This might be a problem when used with some CI servers.
773
774 .. _record_testsuite_property example:
775
776 record_testsuite_property
777 ^^^^^^^^^^^^^^^^^^^^^^^^^
778
779 .. versionadded:: 4.5
780
781 If you want to add a properties node at the test-suite level, which may contain properties
782 that are relevant to all tests, you can use the ``record_testsuite_property`` session-scoped fixture:
783
784 The ``record_testsuite_property`` session-scoped fixture can be used to add properties relevant
785 to all tests.
786
787 .. code-block:: python
788
789 import pytest
790
791
792 @pytest.fixture(scope="session", autouse=True)
793 def log_global_env_facts(record_testsuite_property):
794 record_testsuite_property("ARCH", "PPC")
795 record_testsuite_property("STORAGE_TYPE", "CEPH")
796
797
798 class TestMe:
799 def test_foo(self):
800 assert True
801
802 The fixture is a callable which receives ``name`` and ``value`` of a ``<property>`` tag
803 added at the test-suite level of the generated xml:
804
805 .. code-block:: xml
806
807 <testsuite errors="0" failures="0" name="pytest" skipped="0" tests="1" time="0.006">
808 <properties>
809 <property name="ARCH" value="PPC"/>
810 <property name="STORAGE_TYPE" value="CEPH"/>
811 </properties>
812 <testcase classname="test_me.TestMe" file="test_me.py" line="16" name="test_foo" time="0.000243663787842"/>
813 </testsuite>
814
815 ``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.
816
817 The generated XML is compatible with the latest ``xunit`` standard, contrary to `record_property`_
818 and `record_xml_attribute`_.
819
820
821 Sending test report to an online pastebin service
822 --------------------------------------------------
823
824 **Creating a URL for each test failure**:
825
826 .. code-block:: bash
827
828 pytest --pastebin=failed
829
830 This will submit test run information to a remote Paste service and
831 provide a URL for each failure. You may select tests as usual or add
832 for example :option:`-x` if you only want to send one particular failure.
833
834 **Creating a URL for a whole test session log**:
835
836 .. code-block:: bash
837
838 pytest --pastebin=all
839
840 Currently only pasting to the https://bpaste.net/ service is implemented.
841
842 .. versionchanged:: 5.2
843
844 If creating the URL fails for any reason, a warning is generated instead of failing the
845 entire test suite.
846
847 .. _jenkins: https://jenkins-ci.org