Debian Codegraph @

doc/en/reference/reference.rst

raw
1 :tocdepth: 3
2
3 .. _`api-reference`:
4
5 API Reference
6 =============
7
8 This page contains the full reference to pytest's API.
9
10
11 Constants
12 ---------
13
14 pytest.__version__
15 ~~~~~~~~~~~~~~~~~~
16
17 The current pytest version, as a string::
18
19 >>> import pytest
20 >>> pytest.__version__
21 '9.0.2'
22
23 .. _`hidden-param`:
24
25 pytest.HIDDEN_PARAM
26 ~~~~~~~~~~~~~~~~~~~
27
28 .. versionadded:: 8.4
29
30 Can be passed to ``ids`` of :py:func:`Metafunc.parametrize <pytest.Metafunc.parametrize>`
31 or to ``id`` of :func:`pytest.param` to hide a parameter set from the test name.
32 Can only be used at most 1 time, as test names need to be unique.
33
34 .. _`version-tuple`:
35
36 pytest.version_tuple
37 ~~~~~~~~~~~~~~~~~~~~
38
39 .. versionadded:: 7.0
40
41 The current pytest version, as a tuple::
42
43 >>> import pytest
44 >>> pytest.version_tuple
45 (7, 0, 0)
46
47 For pre-releases, the last component will be a string with the prerelease version::
48
49 >>> import pytest
50 >>> pytest.version_tuple
51 (7, 0, '0rc1')
52
53
54 Functions
55 ---------
56
57 pytest.approx
58 ~~~~~~~~~~~~~
59
60 .. autofunction:: pytest.approx
61
62 pytest.fail
63 ~~~~~~~~~~~
64
65 **Tutorial**: :ref:`skipping`
66
67 .. autofunction:: pytest.fail(reason, [pytrace=True])
68
69 .. class:: pytest.fail.Exception
70
71 The exception raised by :func:`pytest.fail`.
72
73 pytest.skip
74 ~~~~~~~~~~~
75
76 .. autofunction:: pytest.skip(reason, [allow_module_level=False])
77
78 .. class:: pytest.skip.Exception
79
80 The exception raised by :func:`pytest.skip`.
81
82 .. _`pytest.importorskip ref`:
83
84 pytest.importorskip
85 ~~~~~~~~~~~~~~~~~~~
86
87 .. autofunction:: pytest.importorskip
88
89 pytest.xfail
90 ~~~~~~~~~~~~
91
92 .. autofunction:: pytest.xfail
93
94 .. class:: pytest.xfail.Exception
95
96 The exception raised by :func:`pytest.xfail`.
97
98 pytest.exit
99 ~~~~~~~~~~~
100
101 .. autofunction:: pytest.exit(reason, [returncode=None])
102
103 .. class:: pytest.exit.Exception
104
105 The exception raised by :func:`pytest.exit`.
106
107 pytest.main
108 ~~~~~~~~~~~
109
110 **Tutorial**: :ref:`pytest.main-usage`
111
112 .. autofunction:: pytest.main
113
114 pytest.param
115 ~~~~~~~~~~~~
116
117 .. autofunction:: pytest.param(*values, [id], [marks])
118
119 pytest.raises
120 ~~~~~~~~~~~~~
121
122 **Tutorial**: :ref:`assertraises`
123
124 .. autofunction:: pytest.raises(expected_exception: Exception [, *, match])
125 :with: excinfo
126
127 pytest.deprecated_call
128 ~~~~~~~~~~~~~~~~~~~~~~
129
130 **Tutorial**: :ref:`ensuring_function_triggers`
131
132 .. autofunction:: pytest.deprecated_call([match])
133 :with:
134
135 pytest.register_assert_rewrite
136 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
137
138 **Tutorial**: :ref:`assertion-rewriting`
139
140 .. autofunction:: pytest.register_assert_rewrite
141
142 pytest.register_fixture
143 ~~~~~~~~~~~~~~~~~~~~~~~
144
145 .. autofunction:: pytest.register_fixture
146
147 pytest.warns
148 ~~~~~~~~~~~~
149
150 **Tutorial**: :ref:`assertwarnings`
151
152 .. autofunction:: pytest.warns(expected_warning: Exception, [match])
153 :with:
154
155 pytest.freeze_includes
156 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
157
158 **Tutorial**: :ref:`freezing-pytest`
159
160 .. autofunction:: pytest.freeze_includes
161
162 .. _`marks ref`:
163
164 Marks
165 -----
166
167 Marks can be used to apply metadata to *test functions* (but not fixtures), which can then be accessed by
168 fixtures or plugins.
169
170
171
172
173 .. _`pytest.mark.filterwarnings ref`:
174
175 pytest.mark.filterwarnings
176 ~~~~~~~~~~~~~~~~~~~~~~~~~~
177
178 **Tutorial**: :ref:`filterwarnings`
179
180 Add warning filters to marked test items.
181
182 .. py:function:: pytest.mark.filterwarnings(filter)
183
184 :keyword str filter:
185 A *warning specification string*, which is composed of contents of the tuple ``(action, message, category, module, lineno)``
186 as specified in :ref:`python:warning-filter` section of
187 the Python documentation, separated by ``":"``. Optional fields can be omitted.
188 Module names passed for filtering are not regex-escaped.
189
190 For example:
191
192 .. code-block:: python
193
194 @pytest.mark.filterwarnings(r"ignore:.*usage will be deprecated.*:DeprecationWarning")
195 def test_foo(): ...
196
197
198 .. _`pytest.mark.parametrize ref`:
199
200 pytest.mark.parametrize
201 ~~~~~~~~~~~~~~~~~~~~~~~
202
203 **Tutorial**: :ref:`parametrize`
204
205 This mark has the same signature as :py:meth:`pytest.Metafunc.parametrize`; see there.
206
207
208 .. _`pytest.mark.skip ref`:
209
210 pytest.mark.skip
211 ~~~~~~~~~~~~~~~~
212
213 **Tutorial**: :ref:`skip`
214
215 Unconditionally skip a test function.
216
217 .. py:function:: pytest.mark.skip(reason=None)
218
219 :keyword str reason: Reason why the test function is being skipped.
220
221
222 .. _`pytest.mark.skipif ref`:
223
224 pytest.mark.skipif
225 ~~~~~~~~~~~~~~~~~~
226
227 **Tutorial**: :ref:`skipif`
228
229 Skip a test function if a condition is ``True``.
230
231 .. py:function:: pytest.mark.skipif(condition, *, reason=None)
232
233 :type condition: bool or str
234 :param condition: ``True/False`` if the condition should be skipped or a :ref:`condition string <string conditions>`.
235 :keyword str reason: Reason why the test function is being skipped.
236
237
238 .. _`pytest.mark.usefixtures ref`:
239
240 pytest.mark.usefixtures
241 ~~~~~~~~~~~~~~~~~~~~~~~
242
243 **Tutorial**: :ref:`usefixtures`
244
245 Mark a test function as using the given fixture names.
246
247 .. py:function:: pytest.mark.usefixtures(*names)
248
249 :param args: The names of the fixture to use, as strings.
250
251 .. note::
252
253 When using `usefixtures` in hooks, it can only load fixtures when applied to a test function before test setup
254 (for example in the `pytest_collection_modifyitems` hook).
255
256 Also note that this mark has no effect when applied to **fixtures**.
257
258
259
260 .. _`pytest.mark.xfail ref`:
261
262 pytest.mark.xfail
263 ~~~~~~~~~~~~~~~~~~
264
265 **Tutorial**: :ref:`xfail`
266
267 Marks a test function as *expected to fail*.
268
269 .. py:function:: pytest.mark.xfail(condition=False, *, reason=None, raises=None, run=True, strict=strict_xfail)
270
271 :keyword Union[bool, str] condition:
272 Condition for marking the test function as xfail (``True/False`` or a
273 :ref:`condition string <string conditions>`). If a ``bool``, you also have
274 to specify ``reason`` (see :ref:`condition string <string conditions>`).
275 :keyword str reason:
276 Reason why the test function is marked as xfail.
277 :keyword raises:
278 Exception class (or tuple of classes) expected to be raised by the test function; other exceptions will fail the test.
279 Note that subclasses of the classes passed will also result in a match (similar to how the ``except`` statement works).
280 :type raises: Type[:py:exc:`Exception`]
281
282 :keyword bool run:
283 Whether the test function should actually be executed. If ``False``, the function will always xfail and will
284 not be executed (useful if a function is segfaulting).
285 :keyword bool strict:
286 * If ``False`` the function will be shown in the terminal output as ``xfailed`` if it fails
287 and as ``xpass`` if it passes. In both cases this will not cause the test suite to fail as a whole. This
288 is particularly useful to mark *flaky* tests (tests that fail at random) to be tackled later.
289 * If ``True``, the function will be shown in the terminal output as ``xfailed`` if it fails, but if it
290 unexpectedly passes then it will **fail** the test suite. This is particularly useful to mark functions
291 that are always failing and there should be a clear indication if they unexpectedly start to pass (for example
292 a new release of a library fixes a known bug).
293
294 Defaults to :confval:`strict_xfail`, which is ``False`` by default.
295
296
297 Custom marks
298 ~~~~~~~~~~~~
299
300 Marks are created dynamically using the factory object ``pytest.mark`` and applied as a decorator.
301
302 For example:
303
304 .. code-block:: python
305
306 @pytest.mark.timeout(10, "slow", method="thread")
307 def test_function(): ...
308
309 Will create and attach a :class:`Mark <pytest.Mark>` object to the collected
310 :class:`Item <pytest.Item>`, which can then be accessed by fixtures or hooks with
311 :meth:`Node.iter_markers <_pytest.nodes.Node.iter_markers>`. The ``mark`` object will have the following attributes:
312
313 .. code-block:: python
314
315 mark.args == (10, "slow")
316 mark.kwargs == {"method": "thread"}
317
318 Example for using multiple custom markers:
319
320 .. code-block:: python
321
322 @pytest.mark.timeout(10, "slow", method="thread")
323 @pytest.mark.slow
324 def test_function(): ...
325
326 When :meth:`Node.iter_markers <_pytest.nodes.Node.iter_markers>` or :meth:`Node.iter_markers_with_node <_pytest.nodes.Node.iter_markers_with_node>` is used with multiple markers, the marker closest to the function will be iterated over first. The above example will result in ``@pytest.mark.slow`` followed by ``@pytest.mark.timeout(...)``.
327
328 .. _`fixtures-api`:
329
330 Fixtures
331 --------
332
333 **Tutorial**: :ref:`fixture`
334
335 Fixtures are requested by test functions or other fixtures by declaring them as argument names.
336
337
338 Example of a test requiring a fixture:
339
340 .. code-block:: python
341
342 def test_output(capsys):
343 print("hello")
344 out, err = capsys.readouterr()
345 assert out == "hello\n"
346
347
348 Example of a fixture requiring another fixture:
349
350 .. code-block:: python
351
352 @pytest.fixture
353 def db_session(tmp_path):
354 fn = tmp_path / "db.file"
355 return connect(fn)
356
357 For more details, consult the full :ref:`fixtures docs <fixture>`.
358
359
360 .. _`pytest.fixture-api`:
361
362 @pytest.fixture
363 ~~~~~~~~~~~~~~~
364
365 .. autofunction:: pytest.fixture
366 :decorator:
367
368
369 .. fixture:: capfd
370
371 capfd
372 ~~~~~~
373
374 **Tutorial**: :ref:`captures`
375
376 .. autofunction:: _pytest.capture.capfd()
377 :no-auto-options:
378
379
380 .. fixture:: capfdbinary
381
382 capfdbinary
383 ~~~~~~~~~~~~
384
385 **Tutorial**: :ref:`captures`
386
387 .. autofunction:: _pytest.capture.capfdbinary()
388 :no-auto-options:
389
390
391 .. fixture:: caplog
392
393 caplog
394 ~~~~~~
395
396 **Tutorial**: :ref:`logging`
397
398 .. autofunction:: _pytest.logging.caplog()
399 :no-auto-options:
400
401 Returns a :class:`pytest.LogCaptureFixture` instance.
402
403 .. autoclass:: pytest.LogCaptureFixture()
404 :members:
405
406
407 .. fixture:: capsys
408
409 capsys
410 ~~~~~~
411
412 **Tutorial**: :ref:`captures`
413
414 .. autofunction:: _pytest.capture.capsys()
415 :no-auto-options:
416
417 .. autoclass:: pytest.CaptureFixture()
418 :members:
419
420 .. fixture:: capteesys
421
422 capteesys
423 ~~~~~~~~~
424
425 **Tutorial**: :ref:`captures`
426
427 .. autofunction:: _pytest.capture.capteesys()
428 :no-auto-options:
429
430 .. fixture:: capsysbinary
431
432 capsysbinary
433 ~~~~~~~~~~~~
434
435 **Tutorial**: :ref:`captures`
436
437 .. autofunction:: _pytest.capture.capsysbinary()
438 :no-auto-options:
439
440
441 .. fixture:: cache
442
443 config.cache
444 ~~~~~~~~~~~~
445
446 **Tutorial**: :ref:`cache`
447
448 The ``config.cache`` object allows other plugins and fixtures
449 to store and retrieve values across test runs. To access it from fixtures
450 request ``pytestconfig`` into your fixture and get it with ``pytestconfig.cache``.
451
452 Under the hood, the cache plugin uses the simple
453 ``dumps``/``loads`` API of the :py:mod:`json` stdlib module.
454
455 ``config.cache`` is an instance of :class:`pytest.Cache`:
456
457 .. autoclass:: pytest.Cache()
458 :members:
459
460
461 .. fixture:: doctest_namespace
462
463 doctest_namespace
464 ~~~~~~~~~~~~~~~~~
465
466 **Tutorial**: :ref:`doctest`
467
468 .. autofunction:: _pytest.doctest.doctest_namespace()
469
470
471 .. fixture:: monkeypatch
472
473 monkeypatch
474 ~~~~~~~~~~~
475
476 **Tutorial**: :ref:`monkeypatching`
477
478 .. autofunction:: _pytest.monkeypatch.monkeypatch()
479 :no-auto-options:
480
481 Returns a :class:`~pytest.MonkeyPatch` instance.
482
483 .. autoclass:: pytest.MonkeyPatch
484 :members:
485
486
487 .. fixture:: pytestconfig
488
489 pytestconfig
490 ~~~~~~~~~~~~
491
492 .. autofunction:: _pytest.fixtures.pytestconfig()
493
494
495 .. fixture:: pytester
496
497 pytester
498 ~~~~~~~~
499
500 .. versionadded:: 6.2
501
502 Provides a :class:`~pytest.Pytester` instance that can be used to run and test pytest itself.
503
504 It provides an empty directory where pytest can be executed in isolation, and contains facilities
505 to write tests, configuration files, and match against expected output.
506
507 To use it, include in your topmost ``conftest.py`` file:
508
509 .. code-block:: python
510
511 pytest_plugins = "pytester"
512
513
514
515 .. autoclass:: pytest.Pytester()
516 :members:
517
518 .. autoclass:: pytest.RunResult()
519 :members:
520
521 .. autoclass:: pytest.LineMatcher()
522 :members:
523 :special-members: __str__
524
525 .. autoclass:: pytest.HookRecorder()
526 :members:
527
528 .. autoclass:: pytest.RecordedHookCall()
529 :members:
530
531
532 .. fixture:: record_property
533
534 record_property
535 ~~~~~~~~~~~~~~~~~~~
536
537 **Tutorial**: :ref:`record_property example`
538
539 .. autofunction:: _pytest.junitxml.record_property()
540
541
542 .. fixture:: record_testsuite_property
543
544 record_testsuite_property
545 ~~~~~~~~~~~~~~~~~~~~~~~~~
546
547 **Tutorial**: :ref:`record_testsuite_property example`
548
549 .. autofunction:: _pytest.junitxml.record_testsuite_property()
550
551
552 .. fixture:: recwarn
553
554 recwarn
555 ~~~~~~~
556
557 **Tutorial**: :ref:`recwarn`
558
559 .. autofunction:: _pytest.recwarn.recwarn()
560 :no-auto-options:
561
562 .. autoclass:: pytest.WarningsRecorder()
563 :members:
564 :special-members: __getitem__, __iter__, __len__
565
566
567 .. fixture:: request
568
569 request
570 ~~~~~~~
571
572 **Example**: :ref:`request example`
573
574 The ``request`` fixture is a special fixture providing information of the requesting test function.
575
576 .. autoclass:: pytest.FixtureRequest()
577 :members:
578
579
580 .. fixture:: subtests
581
582 subtests
583 ~~~~~~~~
584
585 The ``subtests`` fixture enables declaring subtests inside test functions.
586
587 **Tutorial**: :ref:`subtests`
588
589 .. autoclass:: pytest.Subtests()
590 :members:
591
592
593 .. fixture:: testdir
594
595 testdir
596 ~~~~~~~
597
598 Identical to :fixture:`pytester`, but provides an instance whose methods return
599 legacy ``py.path.local`` objects instead when applicable.
600
601 New code should avoid using :fixture:`testdir` in favor of :fixture:`pytester`.
602
603 .. autoclass:: pytest.Testdir()
604 :members:
605 :noindex: TimeoutExpired
606
607
608 .. fixture:: tmp_path
609
610 tmp_path
611 ~~~~~~~~
612
613 **Tutorial**: :ref:`tmp_path`
614
615 .. autofunction:: _pytest.tmpdir.tmp_path()
616 :no-auto-options:
617
618
619 .. fixture:: tmp_path_factory
620
621 tmp_path_factory
622 ~~~~~~~~~~~~~~~~
623
624 **Tutorial**: :ref:`tmp_path_factory example`
625
626 .. _`tmp_path_factory factory api`:
627
628 ``tmp_path_factory`` is an instance of :class:`~pytest.TempPathFactory`:
629
630 .. autoclass:: pytest.TempPathFactory()
631 :members:
632
633
634 .. fixture:: tmpdir
635
636 tmpdir
637 ~~~~~~
638
639 **Tutorial**: :ref:`tmpdir and tmpdir_factory`
640
641 .. autofunction:: _pytest.legacypath.LegacyTmpdirPlugin.tmpdir()
642 :no-auto-options:
643
644
645 .. fixture:: tmpdir_factory
646
647 tmpdir_factory
648 ~~~~~~~~~~~~~~
649
650 **Tutorial**: :ref:`tmpdir and tmpdir_factory`
651
652 ``tmpdir_factory`` is an instance of :class:`~pytest.TempdirFactory`:
653
654 .. autoclass:: pytest.TempdirFactory()
655 :members:
656
657
658 .. _`hook-reference`:
659
660 Hooks
661 -----
662
663 **Tutorial**: :ref:`writing-plugins`
664
665 Reference to all hooks which can be implemented by :ref:`conftest.py files <localplugin>` and :ref:`plugins <plugins>`.
666
667 @pytest.hookimpl
668 ~~~~~~~~~~~~~~~~
669
670 .. function:: pytest.hookimpl
671 :decorator:
672
673 pytest's decorator for marking functions as hook implementations.
674
675 See :ref:`writinghooks` and :func:`pluggy.HookimplMarker`.
676
677 @pytest.hookspec
678 ~~~~~~~~~~~~~~~~
679
680 .. function:: pytest.hookspec
681 :decorator:
682
683 pytest's decorator for marking functions as hook specifications.
684
685 See :ref:`declaringhooks` and :func:`pluggy.HookspecMarker`.
686
687 .. currentmodule:: _pytest.hookspec
688
689 Bootstrapping hooks
690 ~~~~~~~~~~~~~~~~~~~
691
692 Bootstrapping hooks called for plugins registered early enough (internal and third-party plugins).
693
694 .. hook:: pytest_load_initial_conftests
695 .. autofunction:: pytest_load_initial_conftests
696 .. hook:: pytest_cmdline_parse
697 .. autofunction:: pytest_cmdline_parse
698 .. hook:: pytest_cmdline_main
699 .. autofunction:: pytest_cmdline_main
700
701 .. _`initialization-hooks`:
702
703 Initialization hooks
704 ~~~~~~~~~~~~~~~~~~~~
705
706 Initialization hooks called for plugins and ``conftest.py`` files.
707
708 .. hook:: pytest_addoption
709 .. autofunction:: pytest_addoption
710 .. hook:: pytest_addhooks
711 .. autofunction:: pytest_addhooks
712 .. hook:: pytest_configure
713 .. autofunction:: pytest_configure
714 .. hook:: pytest_unconfigure
715 .. autofunction:: pytest_unconfigure
716 .. hook:: pytest_sessionstart
717 .. autofunction:: pytest_sessionstart
718 .. hook:: pytest_sessionfinish
719 .. autofunction:: pytest_sessionfinish
720
721 .. hook:: pytest_plugin_registered
722 .. autofunction:: pytest_plugin_registered
723
724 Collection hooks
725 ~~~~~~~~~~~~~~~~
726
727 ``pytest`` calls the following hooks for collecting files and directories:
728
729 .. hook:: pytest_collection
730 .. autofunction:: pytest_collection
731 .. hook:: pytest_ignore_collect
732 .. autofunction:: pytest_ignore_collect
733 .. hook:: pytest_collect_directory
734 .. autofunction:: pytest_collect_directory
735 .. hook:: pytest_collect_file
736 .. autofunction:: pytest_collect_file
737 .. hook:: pytest_pycollect_makemodule
738 .. autofunction:: pytest_pycollect_makemodule
739
740 For influencing the collection of objects in Python modules
741 you can use the following hook:
742
743 .. hook:: pytest_pycollect_makeitem
744 .. autofunction:: pytest_pycollect_makeitem
745 .. hook:: pytest_generate_tests
746 .. autofunction:: pytest_generate_tests
747 .. hook:: pytest_make_parametrize_id
748 .. autofunction:: pytest_make_parametrize_id
749
750 Hooks for influencing test skipping:
751
752 .. hook:: pytest_markeval_namespace
753 .. autofunction:: pytest_markeval_namespace
754
755 After collection is complete, you can modify the order of
756 items, delete or otherwise amend the test items:
757
758 .. hook:: pytest_collection_modifyitems
759 .. autofunction:: pytest_collection_modifyitems
760
761 .. note::
762 If this hook is implemented in ``conftest.py`` files, it always receives all collected items, not only those
763 under the ``conftest.py`` where it is implemented.
764
765 .. hook:: pytest_collection_finish
766 .. autofunction:: pytest_collection_finish
767
768 Test running (runtest) hooks
769 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
770
771 All runtest related hooks receive a :py:class:`pytest.Item <pytest.Item>` object.
772
773 .. hook:: pytest_runtestloop
774 .. autofunction:: pytest_runtestloop
775 .. hook:: pytest_runtest_protocol
776 .. autofunction:: pytest_runtest_protocol
777 .. hook:: pytest_runtest_logstart
778 .. autofunction:: pytest_runtest_logstart
779 .. hook:: pytest_runtest_logfinish
780 .. autofunction:: pytest_runtest_logfinish
781 .. hook:: pytest_runtest_setup
782 .. autofunction:: pytest_runtest_setup
783 .. hook:: pytest_runtest_call
784 .. autofunction:: pytest_runtest_call
785 .. hook:: pytest_runtest_teardown
786 .. autofunction:: pytest_runtest_teardown
787 .. hook:: pytest_runtest_makereport
788 .. autofunction:: pytest_runtest_makereport
789
790 For deeper understanding you may look at the default implementation of
791 these hooks in ``_pytest.runner`` and maybe also
792 in ``_pytest.pdb`` which interacts with ``_pytest.capture``
793 and its input/output capturing in order to immediately drop
794 into interactive debugging when a test failure occurs.
795
796 .. hook:: pytest_pyfunc_call
797 .. autofunction:: pytest_pyfunc_call
798
799 Reporting hooks
800 ~~~~~~~~~~~~~~~
801
802 Session related reporting hooks:
803
804 .. hook:: pytest_collectstart
805 .. autofunction:: pytest_collectstart
806 .. hook:: pytest_make_collect_report
807 .. autofunction:: pytest_make_collect_report
808 .. hook:: pytest_itemcollected
809 .. autofunction:: pytest_itemcollected
810 .. hook:: pytest_collectreport
811 .. autofunction:: pytest_collectreport
812 .. hook:: pytest_deselected
813 .. autofunction:: pytest_deselected
814 .. hook:: pytest_report_header
815 .. autofunction:: pytest_report_header
816 .. hook:: pytest_report_collectionfinish
817 .. autofunction:: pytest_report_collectionfinish
818 .. hook:: pytest_report_teststatus
819 .. autofunction:: pytest_report_teststatus
820 .. hook:: pytest_report_to_serializable
821 .. autofunction:: pytest_report_to_serializable
822 .. hook:: pytest_report_from_serializable
823 .. autofunction:: pytest_report_from_serializable
824 .. hook:: pytest_terminal_summary
825 .. autofunction:: pytest_terminal_summary
826 .. hook:: pytest_fixture_setup
827 .. autofunction:: pytest_fixture_setup
828 .. hook:: pytest_fixture_post_finalizer
829 .. autofunction:: pytest_fixture_post_finalizer
830 .. hook:: pytest_warning_recorded
831 .. autofunction:: pytest_warning_recorded
832
833 Central hook for reporting about test execution:
834
835 .. hook:: pytest_runtest_logreport
836 .. autofunction:: pytest_runtest_logreport
837
838 Assertion related hooks:
839
840 .. hook:: pytest_assertrepr_compare
841 .. autofunction:: pytest_assertrepr_compare
842 .. hook:: pytest_assertion_pass
843 .. autofunction:: pytest_assertion_pass
844
845
846 Debugging/Interaction hooks
847 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
848
849 There are few hooks which can be used for special
850 reporting or interaction with exceptions:
851
852 .. hook:: pytest_internalerror
853 .. autofunction:: pytest_internalerror
854 .. hook:: pytest_keyboard_interrupt
855 .. autofunction:: pytest_keyboard_interrupt
856 .. hook:: pytest_exception_interact
857 .. autofunction:: pytest_exception_interact
858 .. hook:: pytest_enter_pdb
859 .. autofunction:: pytest_enter_pdb
860 .. hook:: pytest_leave_pdb
861 .. autofunction:: pytest_leave_pdb
862
863
864 Collection tree objects
865 -----------------------
866
867 These are the collector and item classes (collectively called "nodes") which
868 make up the collection tree.
869
870 Node
871 ~~~~
872
873 .. autoclass:: _pytest.nodes.Node()
874 :members:
875 :show-inheritance:
876
877 Collector
878 ~~~~~~~~~
879
880 .. autoclass:: pytest.Collector()
881 :members:
882 :show-inheritance:
883
884 Item
885 ~~~~
886
887 .. autoclass:: pytest.Item()
888 :members:
889 :show-inheritance:
890
891 File
892 ~~~~
893
894 .. autoclass:: pytest.File()
895 :members:
896 :show-inheritance:
897
898 FSCollector
899 ~~~~~~~~~~~
900
901 .. autoclass:: _pytest.nodes.FSCollector()
902 :members:
903 :show-inheritance:
904
905 Session
906 ~~~~~~~
907
908 .. autoclass:: pytest.Session()
909 :members:
910 :show-inheritance:
911
912 Package
913 ~~~~~~~
914
915 .. autoclass:: pytest.Package()
916 :members:
917 :show-inheritance:
918
919 Module
920 ~~~~~~
921
922 .. autoclass:: pytest.Module()
923 :members:
924 :show-inheritance:
925
926 Class
927 ~~~~~
928
929 .. autoclass:: pytest.Class()
930 :members:
931 :show-inheritance:
932
933 Function
934 ~~~~~~~~
935
936 .. autoclass:: pytest.Function()
937 :members:
938 :show-inheritance:
939
940 FunctionDefinition
941 ~~~~~~~~~~~~~~~~~~
942
943 .. autoclass:: _pytest.python.FunctionDefinition()
944 :members:
945 :show-inheritance:
946
947
948 Objects
949 -------
950
951 Objects accessible from :ref:`fixtures <fixture>` or :ref:`hooks <hook-reference>`
952 or importable from ``pytest``.
953
954
955 CallInfo
956 ~~~~~~~~
957
958 .. autoclass:: pytest.CallInfo()
959 :members:
960
961 CollectReport
962 ~~~~~~~~~~~~~
963
964 .. autoclass:: pytest.CollectReport()
965 :members:
966 :show-inheritance:
967 :inherited-members:
968
969 Config
970 ~~~~~~
971
972 .. autoclass:: pytest.Config()
973 :members:
974
975 Dir
976 ~~~
977
978 .. autoclass:: pytest.Dir()
979 :members:
980
981 Directory
982 ~~~~~~~~~
983
984 .. autoclass:: pytest.Directory()
985 :members:
986
987 ExceptionInfo
988 ~~~~~~~~~~~~~
989
990 .. autoclass:: pytest.ExceptionInfo()
991 :members:
992
993
994 ExitCode
995 ~~~~~~~~
996
997 .. autoclass:: pytest.ExitCode
998 :members:
999
1000
1001 FixtureDef
1002 ~~~~~~~~~~
1003
1004 .. autoclass:: pytest.FixtureDef()
1005 :members:
1006 :show-inheritance:
1007
1008 MarkDecorator
1009 ~~~~~~~~~~~~~
1010
1011 .. autoclass:: pytest.MarkDecorator()
1012 :members:
1013
1014
1015 MarkGenerator
1016 ~~~~~~~~~~~~~
1017
1018 .. autoclass:: pytest.MarkGenerator()
1019 :members:
1020
1021
1022 Mark
1023 ~~~~
1024
1025 .. autoclass:: pytest.Mark()
1026 :members:
1027
1028
1029 Metafunc
1030 ~~~~~~~~
1031
1032 .. autoclass:: pytest.Metafunc()
1033 :members:
1034
1035 Parser
1036 ~~~~~~
1037
1038 .. autoclass:: pytest.Parser()
1039 :members:
1040
1041 OptionGroup
1042 ~~~~~~~~~~~
1043
1044 .. autoclass:: pytest.OptionGroup()
1045 :members:
1046
1047 PytestPluginManager
1048 ~~~~~~~~~~~~~~~~~~~
1049
1050 .. autoclass:: pytest.PytestPluginManager()
1051 :members:
1052 :undoc-members:
1053 :inherited-members:
1054 :show-inheritance:
1055
1056 RaisesExc
1057 ~~~~~~~~~
1058
1059 .. autoclass:: pytest.RaisesExc()
1060 :members:
1061
1062 .. autoattribute:: fail_reason
1063
1064 RaisesGroup
1065 ~~~~~~~~~~~
1066 **Tutorial**: :ref:`assert-matching-exception-groups`
1067
1068 .. autoclass:: pytest.RaisesGroup()
1069 :members:
1070
1071 .. autoattribute:: fail_reason
1072
1073 TerminalReporter
1074 ~~~~~~~~~~~~~~~~
1075
1076 .. autoclass:: pytest.TerminalReporter
1077 :members:
1078 :inherited-members:
1079
1080 TestReport
1081 ~~~~~~~~~~
1082
1083 .. autoclass:: pytest.TestReport()
1084 :members:
1085 :show-inheritance:
1086 :inherited-members:
1087
1088 TestShortLogReport
1089 ~~~~~~~~~~~~~~~~~~
1090
1091 .. autoclass:: pytest.TestShortLogReport()
1092 :members:
1093
1094 Result
1095 ~~~~~~~
1096
1097 Result object used within :ref:`hook wrappers <hookwrapper>`, see :py:class:`Result in the pluggy documentation <pluggy.Result>` for more information.
1098
1099 Stash
1100 ~~~~~
1101
1102 .. autoclass:: pytest.Stash
1103 :special-members: __setitem__, __getitem__, __delitem__, __contains__, __len__
1104 :members:
1105
1106 .. autoclass:: pytest.StashKey
1107 :show-inheritance:
1108 :members:
1109
1110
1111 Global Variables
1112 ----------------
1113
1114 pytest treats some global variables in a special manner when defined in a test module or
1115 ``conftest.py`` files.
1116
1117
1118 .. globalvar:: collect_ignore
1119
1120 **Tutorial**: :ref:`customizing-test-collection`
1121
1122 Can be declared in *conftest.py files* to exclude test directories or modules.
1123 Needs to be a list of paths (``str``, :class:`pathlib.Path` or any :class:`os.PathLike`).
1124
1125 .. code-block:: python
1126
1127 collect_ignore = ["setup.py"]
1128
1129
1130 .. globalvar:: collect_ignore_glob
1131
1132 **Tutorial**: :ref:`customizing-test-collection`
1133
1134 Can be declared in *conftest.py files* to exclude test directories or modules
1135 with Unix shell-style wildcards. Needs to be ``list[str]`` where ``str`` can
1136 contain glob patterns.
1137
1138 .. code-block:: python
1139
1140 collect_ignore_glob = ["*_ignore.py"]
1141
1142
1143 .. globalvar:: pytest_plugins
1144
1145 **Tutorial**: :ref:`available installable plugins`
1146
1147 Can be declared at the **global** level in *test modules* and *conftest.py files* to register additional plugins.
1148 Can be either a ``str`` or ``Sequence[str]``.
1149
1150 .. code-block:: python
1151
1152 pytest_plugins = "myapp.testsupport.myplugin"
1153
1154 .. code-block:: python
1155
1156 pytest_plugins = ("myapp.testsupport.tools", "myapp.testsupport.regression")
1157
1158
1159 .. globalvar:: pytestmark
1160
1161 **Tutorial**: :ref:`scoped-marking`
1162
1163 Can be declared at the **global** level in *test modules* to apply one or more :ref:`marks <marks ref>` to all
1164 test functions and methods. Can be either a single mark or a list of marks (applied in left-to-right order).
1165
1166 .. code-block:: python
1167
1168 import pytest
1169
1170 pytestmark = pytest.mark.webtest
1171
1172
1173 .. code-block:: python
1174
1175 import pytest
1176
1177 pytestmark = [pytest.mark.integration, pytest.mark.slow]
1178
1179
1180 Environment Variables
1181 ---------------------
1182
1183 Environment variables that can be used to change pytest's behavior.
1184
1185 .. envvar:: CI
1186
1187 When set to a non-empty value, pytest acknowledges that it is running in a CI process. See also :ref:`ci-pipelines`.
1188
1189 .. envvar:: BUILD_NUMBER
1190
1191 When set to a non-empty value, pytest acknowledges that it is running in a CI process. Alternative to :envvar:`CI`. See also :ref:`ci-pipelines`.
1192
1193 .. envvar:: PYTEST_ADDOPTS
1194
1195 This contains a command-line (parsed by the py:mod:`shlex` module) that will be **prepended** to the command line given
1196 by the user, see :ref:`adding default options` for more information.
1197
1198 .. envvar:: PYTEST_VERSION
1199
1200 This environment variable is defined at the start of the pytest session and is undefined afterwards.
1201 It contains the value of ``pytest.__version__``, and among other things can be used to easily check if a code is running from within a pytest run.
1202
1203 .. envvar:: PYTEST_CURRENT_TEST
1204
1205 This is not meant to be set by users, but is set by pytest internally with the name of the current test so other
1206 processes can inspect it, see :ref:`pytest current test env` for more information.
1207
1208 .. envvar:: PYTEST_DEBUG
1209
1210 When set, pytest will print tracing and debug information.
1211
1212 .. envvar:: PYTEST_DEBUG_TEMPROOT
1213
1214 Root for temporary directories produced by fixtures like :fixture:`tmp_path`
1215 as discussed in :ref:`temporary directory location and retention`.
1216
1217 .. envvar:: PYTEST_DISABLE_PLUGIN_AUTOLOAD
1218
1219 When set, disables plugin auto-loading through :std:doc:`entry point packaging
1220 metadata <packaging:guides/creating-and-discovering-plugins>`. Only plugins
1221 explicitly specified in :envvar:`PYTEST_PLUGINS` or with :option:`-p` will be loaded.
1222 See also :ref:`--disable-plugin-autoload <disable_plugin_autoload>`.
1223
1224 .. envvar:: PYTEST_PLUGINS
1225
1226 Contains comma-separated list of modules that should be loaded as plugins:
1227
1228 .. code-block:: bash
1229
1230 export PYTEST_PLUGINS=mymodule.plugin,xdist
1231
1232 See also :option:`-p`.
1233
1234 .. envvar:: PYTEST_THEME
1235
1236 Sets a `pygment style <https://pygments.org/docs/styles/>`_ to use for the code output.
1237
1238 .. envvar:: PYTEST_THEME_MODE
1239
1240 Sets the :envvar:`PYTEST_THEME` to be either *dark* or *light*.
1241
1242 .. envvar:: PY_COLORS
1243
1244 When set to ``1``, pytest will use color in terminal output.
1245 When set to ``0``, pytest will not use color.
1246 ``PY_COLORS`` takes precedence over ``NO_COLOR`` and ``FORCE_COLOR``.
1247
1248 .. envvar:: NO_COLOR
1249
1250 When set to a non-empty string (regardless of value), pytest will not use color in terminal output.
1251 ``PY_COLORS`` takes precedence over ``NO_COLOR``, which takes precedence over ``FORCE_COLOR``.
1252 See `no-color.org <https://no-color.org/>`__ for other libraries supporting this community standard.
1253
1254 .. envvar:: FORCE_COLOR
1255
1256 When set to a non-empty string (regardless of value), pytest will use color in terminal output.
1257 ``PY_COLORS`` and ``NO_COLOR`` take precedence over ``FORCE_COLOR``.
1258
1259 Exceptions
1260 ----------
1261
1262 .. autoexception:: pytest.UsageError()
1263 :show-inheritance:
1264
1265 .. autoexception:: pytest.FixtureLookupError()
1266 :show-inheritance:
1267
1268 .. _`warnings ref`:
1269
1270 Warnings
1271 --------
1272
1273 Custom warnings generated in some situations such as improper usage or deprecated features.
1274
1275 .. autoclass:: pytest.PytestWarning
1276 :show-inheritance:
1277
1278 .. autoclass:: pytest.PytestAssertRewriteWarning
1279 :show-inheritance:
1280
1281 .. autoclass:: pytest.PytestCacheWarning
1282 :show-inheritance:
1283
1284 .. autoclass:: pytest.PytestCollectionWarning
1285 :show-inheritance:
1286
1287 .. autoclass:: pytest.PytestConfigWarning
1288 :show-inheritance:
1289
1290 .. autoclass:: pytest.PytestDeprecationWarning
1291 :show-inheritance:
1292
1293 .. autoclass:: pytest.PytestExperimentalApiWarning
1294 :show-inheritance:
1295
1296 .. autoclass:: pytest.PytestReturnNotNoneWarning
1297 :show-inheritance:
1298
1299 .. autoclass:: pytest.PytestRemovedIn10Warning
1300 :show-inheritance:
1301
1302 .. autoclass:: pytest.PytestUnknownMarkWarning
1303 :show-inheritance:
1304
1305 .. autoclass:: pytest.PytestUnraisableExceptionWarning
1306 :show-inheritance:
1307
1308 .. autoclass:: pytest.PytestUnhandledThreadExceptionWarning
1309 :show-inheritance:
1310
1311
1312 Consult the :ref:`internal-warnings` section in the documentation for more information.
1313
1314
1315 .. _`ini options ref`:
1316
1317 Configuration Options
1318 ---------------------
1319
1320 Here is a list of builtin configuration options that may be written in a ``pytest.ini`` (or ``.pytest.ini``),
1321 ``pyproject.toml``, ``tox.ini``, or ``setup.cfg`` file, usually located at the root of your repository.
1322
1323 To see each file format in detail, see :ref:`config file formats`.
1324
1325 .. warning::
1326 Usage of ``setup.cfg`` is not recommended except for very simple use cases. ``.cfg``
1327 files use a different parser than ``pytest.ini`` and ``tox.ini`` which might cause hard to track
1328 down problems.
1329 When possible, it is recommended to use the latter files, or ``pytest.toml`` or ``pyproject.toml``, to hold your pytest configuration.
1330
1331 Configuration options may be overwritten in the command-line by using ``-o/--override-ini``, which can also be
1332 passed multiple times. The expected format is ``name=value``. For example::
1333
1334 pytest -o console_output_style=classic -o cache_dir=/tmp/mycache
1335
1336
1337 .. confval:: addopts
1338 :type: ``list[str]``
1339
1340 Add the specified ``OPTS`` to the set of command line arguments as if they
1341 had been specified by the user. Example: if you have this configuration file content:
1342
1343 .. code-block:: toml
1344
1345 # content of pytest.toml
1346 [pytest]
1347 addopts = ["--maxfail=2", "-rf"] # exit after 2 failures, report fail info
1348
1349 issuing ``pytest test_hello.py`` actually means:
1350
1351 .. code-block:: bash
1352
1353 pytest --maxfail=2 -rf test_hello.py
1354
1355
1356 .. confval:: cache_dir
1357 :type: ``str``
1358 :default: ``".pytest_cache"``
1359
1360 Sets the directory where the cache plugin's content is stored.
1361 Directory may be relative or absolute path. If setting relative path, then directory is created
1362 relative to :ref:`rootdir <rootdir>`. Additionally, a path may contain environment
1363 variables, that will be expanded. For more information about cache plugin
1364 please refer to :ref:`cache_provider`.
1365
1366 .. confval:: collect_imported_tests
1367 :type: ``bool``
1368 :default: ``true``
1369
1370 .. versionadded:: 8.4
1371
1372 Setting this to ``false`` will make pytest collect classes/functions from test
1373 files **only** if they are defined in that file (as opposed to imported there).
1374
1375 .. tab:: toml
1376
1377 .. code-block:: toml
1378
1379 [pytest]
1380 collect_imported_tests = false
1381
1382 .. tab:: ini
1383
1384 .. code-block:: ini
1385
1386 [pytest]
1387 collect_imported_tests = false
1388
1389 pytest traditionally collects classes/functions in the test module namespace even if they are imported from another file.
1390
1391 For example:
1392
1393 .. code-block:: python
1394
1395 # contents of src/domain.py
1396 class Testament: ...
1397
1398
1399 # contents of tests/test_testament.py
1400 from domain import Testament
1401
1402
1403 def test_testament(): ...
1404
1405 In this scenario, with the default options, pytest will collect the class `Testament` from `tests/test_testament.py` because it starts with `Test`, even though in this case it is a production class being imported in the test module namespace.
1406
1407 Set ``collected_imported_tests`` to ``false`` in the configuration file prevents that.
1408
1409 .. confval:: consider_namespace_packages
1410 :type: ``bool``
1411 :default: ``false``
1412
1413 Controls if pytest should attempt to identify `namespace packages <https://packaging.python.org/en/latest/guides/packaging-namespace-packages>`__
1414 when collecting Python modules.
1415
1416 Set to ``True`` if the package you are testing is part of a namespace package.
1417 Namespace packages are also supported as :option:`--pyargs` target.
1418
1419 Only `native namespace packages <https://packaging.python.org/en/latest/guides/packaging-namespace-packages/#native-namespace-packages>`__
1420 are supported, with no plans to support `legacy namespace packages <https://packaging.python.org/en/latest/guides/packaging-namespace-packages/#legacy-namespace-packages>`__.
1421
1422 For best results when using `consider_namespace_packages`,
1423 pytest needs to be able to import your namespace packages.
1424 This is best achieved by installing the packages in your environment,
1425 most commonly in `"editable" mode <https://packaging.python.org/en/latest/guides/distributing-packages-using-setuptools/#working-in-development-mode>`_.
1426 If you can't install the packages, consider adding the namespace root paths to :confval:`pythonpath`.
1427
1428 .. versionadded:: 8.1
1429
1430 .. confval:: console_output_style
1431 :type: ``str``
1432 :default: ``"progress"``
1433
1434 Sets the console output style while running tests:
1435
1436 * ``classic``: classic pytest output.
1437 * ``progress``: like classic pytest output, but with a progress indicator.
1438 * ``progress-even-when-capture-no``: allows the use of the progress indicator even when ``capture=no``.
1439 * ``count``: like progress, but shows progress as the number of tests completed instead of a percent.
1440 * ``times``: show tests duration.
1441
1442 You can fallback to ``classic`` if you prefer or
1443 the new mode is causing unexpected problems:
1444
1445 .. tab:: toml
1446
1447 .. code-block:: toml
1448
1449 [pytest]
1450 console_output_style = "classic"
1451
1452 .. tab:: ini
1453
1454 .. code-block:: ini
1455
1456 [pytest]
1457 console_output_style = classic
1458
1459
1460 .. confval:: disable_test_id_escaping_and_forfeit_all_rights_to_community_support
1461 :type: ``bool``
1462 :default: ``false``
1463
1464 .. versionadded:: 4.4
1465
1466 pytest by default escapes any non-ascii characters used in unicode strings
1467 for the parametrization because it has several downsides.
1468 If however you would like to use unicode strings in parametrization
1469 and see them in the terminal as is (non-escaped), use this option
1470 in your configuration file:
1471
1472 .. tab:: toml
1473
1474 .. code-block:: toml
1475
1476 [pytest]
1477 disable_test_id_escaping_and_forfeit_all_rights_to_community_support = true
1478
1479 .. tab:: ini
1480
1481 .. code-block:: ini
1482
1483 [pytest]
1484 disable_test_id_escaping_and_forfeit_all_rights_to_community_support = true
1485
1486 Keep in mind however that this might cause unwanted side effects and
1487 even bugs depending on the OS used and plugins currently installed,
1488 so use it at your own risk.
1489
1490 See :ref:`parametrizemark`.
1491
1492 .. confval:: doctest_encoding
1493 :type: ``str``
1494 :default: ``"utf-8"``
1495
1496 Default encoding to use to decode text files with docstrings.
1497 :ref:`See how pytest handles doctests <doctest>`.
1498
1499
1500 .. confval:: doctest_optionflags
1501 :type: ``list[str]``
1502
1503 One or more doctest flag names from the standard ``doctest`` module.
1504 :ref:`See how pytest handles doctests <doctest>`.
1505
1506
1507 .. confval:: empty_parameter_set_mark
1508 :type: ``str``
1509 :default: ``"skip"``
1510
1511 Allows to pick the action for empty parametersets in parameterization
1512
1513 * ``skip`` skips tests with an empty parameterset
1514 * ``xfail`` marks tests with an empty parameterset as xfail(run=False)
1515 * ``fail_at_collect`` raises an exception if parametrize collects an empty parameter set
1516
1517 .. tab:: toml
1518
1519 .. code-block:: toml
1520
1521 [pytest]
1522 empty_parameter_set_mark = "xfail"
1523
1524 .. tab:: ini
1525
1526 .. code-block:: ini
1527
1528 [pytest]
1529 empty_parameter_set_mark = xfail
1530
1531 .. note::
1532
1533 The default value of this option is planned to change to ``xfail`` in future releases
1534 as this is considered less error prone, see :issue:`3155` for more details.
1535
1536
1537 .. confval:: enable_assertion_pass_hook
1538 :type: ``bool``
1539 :default: ``false``
1540
1541 Enables the :hook:`pytest_assertion_pass` hook.
1542 Make sure to delete any previously generated ``.pyc`` cache files.
1543
1544 .. tab:: toml
1545
1546 .. code-block:: toml
1547
1548 [pytest]
1549 enable_assertion_pass_hook = true
1550
1551 .. tab:: ini
1552
1553 .. code-block:: ini
1554
1555 [pytest]
1556 enable_assertion_pass_hook = true
1557
1558
1559 .. confval:: faulthandler_exit_on_timeout
1560 :type: ``bool``
1561 :default: ``false``
1562
1563 Exit the pytest process after the per-test timeout is reached by passing
1564 `exit=True` to the :func:`faulthandler.dump_traceback_later` function. This
1565 is particularly useful to avoid wasting CI resources for test suites that
1566 are prone to putting the main Python interpreter into a deadlock state.
1567
1568 .. tab:: toml
1569
1570 .. code-block:: toml
1571
1572 [pytest]
1573 faulthandler_timeout = 5
1574 faulthandler_exit_on_timeout = true
1575
1576 .. tab:: ini
1577
1578 .. code-block:: ini
1579
1580 [pytest]
1581 faulthandler_timeout = 5
1582 faulthandler_exit_on_timeout = true
1583
1584
1585
1586 .. confval:: faulthandler_timeout
1587 :type: ``float``
1588 :default: ``0`` (disabled)
1589
1590 Dumps the tracebacks of all threads if a test takes longer than ``X`` seconds to run (including
1591 fixture setup and teardown). Implemented using the :func:`faulthandler.dump_traceback_later` function,
1592 so all caveats there apply.
1593
1594 .. tab:: toml
1595
1596 .. code-block:: toml
1597
1598 [pytest]
1599 faulthandler_timeout = 5
1600
1601 .. tab:: ini
1602
1603 .. code-block:: ini
1604
1605 [pytest]
1606 faulthandler_timeout = 5
1607
1608 For more information please refer to :ref:`faulthandler`.
1609
1610
1611 .. confval:: filterwarnings
1612 :type: ``list[str]``
1613
1614 Sets a list of filters and actions that should be taken for matched
1615 warnings. By default all warnings emitted during the test session
1616 will be displayed in a summary at the end of the test session.
1617
1618 .. tab:: toml
1619
1620 .. code-block:: toml
1621
1622 [pytest]
1623 filterwarnings = [
1624 'error',
1625 'ignore::DeprecationWarning',
1626 # Note the use of single quote below to denote "raw" strings in TOML.
1627 'ignore:function ham\(\) should not be used:UserWarning',
1628 ]
1629
1630 .. tab:: ini
1631
1632 .. code-block:: ini
1633
1634 [pytest]
1635 filterwarnings =
1636 error
1637 ignore::DeprecationWarning
1638 ignore:function ham\(\) should not be used:UserWarning
1639
1640 This tells pytest to ignore deprecation warnings and turn all other warnings
1641 into errors. For more information please refer to :ref:`warnings`.
1642
1643
1644 .. confval:: max_warnings
1645 :type: ``int``
1646
1647 .. versionadded:: 9.1
1648
1649 Maximum number of warnings allowed before the test run is considered a failure.
1650 When all tests pass, but the total number of warnings exceeds this value, pytest exits with
1651 :class:`pytest.ExitCode` ``MAX_WARNINGS_ERROR`` (code ``6``).
1652
1653 .. tab:: toml
1654
1655 .. code-block:: toml
1656
1657 [pytest]
1658 max_warnings = 10
1659
1660 .. tab:: ini
1661
1662 .. code-block:: ini
1663
1664 [pytest]
1665 max_warnings = 10
1666
1667 Note that :confval:`filtered warnings <filterwarnings>` do not count toward this maximum total.
1668
1669 Can also be set via the :option:`--max-warnings` command-line option.
1670
1671
1672 .. confval:: junit_duration_report
1673 :type: ``str``
1674 :default: ``"total"``
1675
1676 .. versionadded:: 4.1
1677
1678 Configures how durations are recorded into the JUnit XML report:
1679
1680 * ``total``: duration times reported include setup, call, and teardown times.
1681 * ``call``: duration times reported include only call times, excluding setup and teardown.
1682
1683 .. tab:: toml
1684
1685 .. code-block:: toml
1686
1687 [pytest]
1688 junit_duration_report = "call"
1689
1690 .. tab:: ini
1691
1692 .. code-block:: ini
1693
1694 [pytest]
1695 junit_duration_report = call
1696
1697
1698 .. confval:: junit_family
1699 :type: ``str``
1700 :default: ``"xunit2"``
1701
1702 .. versionadded:: 4.2
1703 .. versionchanged:: 6.1
1704 Default changed to ``xunit2``.
1705
1706 Configures the format of the generated JUnit XML file. The possible options are:
1707
1708 * ``xunit1`` (or ``legacy``): produces old style output, compatible with the xunit 1.0 format.
1709 * ``xunit2``: produces `xunit 2.0 style output <https://github.com/jenkinsci/xunit-plugin/blob/xunit-2.3.2/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd>`__, which should be more compatible with latest Jenkins versions.
1710
1711 .. tab:: toml
1712
1713 .. code-block:: toml
1714
1715 [pytest]
1716 junit_family = "xunit2"
1717
1718 .. tab:: ini
1719
1720 .. code-block:: ini
1721
1722 [pytest]
1723 junit_family = xunit2
1724
1725
1726 .. confval:: junit_log_passing_tests
1727 :type: ``bool``
1728 :default: ``true``
1729
1730 .. versionadded:: 4.6
1731
1732 If ``junit_logging != "no"``, configures if the captured output should be written
1733 to the JUnit XML file for **passing** tests.
1734
1735 .. tab:: toml
1736
1737 .. code-block:: toml
1738
1739 [pytest]
1740 junit_log_passing_tests = false
1741
1742 .. tab:: ini
1743
1744 .. code-block:: ini
1745
1746 [pytest]
1747 junit_log_passing_tests = False
1748
1749
1750 .. confval:: junit_logging
1751 :type: ``str``
1752 :default: ``"no"``
1753
1754 .. versionadded:: 3.5
1755 .. versionchanged:: 5.4
1756 ``log``, ``all``, ``out-err`` options added.
1757
1758 Configures if captured output should be written to the JUnit XML file. Valid values are:
1759
1760 * ``log``: write only ``logging`` captured output.
1761 * ``system-out``: write captured ``stdout`` contents.
1762 * ``system-err``: write captured ``stderr`` contents.
1763 * ``out-err``: write both captured ``stdout`` and ``stderr`` contents.
1764 * ``all``: write captured ``logging``, ``stdout`` and ``stderr`` contents.
1765 * ``no``: no captured output is written.
1766
1767 .. tab:: toml
1768
1769 .. code-block:: toml
1770
1771 [pytest]
1772 junit_logging = "system-out"
1773
1774 .. tab:: ini
1775
1776 .. code-block:: ini
1777
1778 [pytest]
1779 junit_logging = system-out
1780
1781
1782 .. confval:: junit_suite_name
1783 :type: ``str``
1784 :default: ``"pytest"``
1785
1786 To set the name of the root test suite xml item, you can configure the ``junit_suite_name`` option in your config file:
1787
1788 .. tab:: toml
1789
1790 .. code-block:: toml
1791
1792 [pytest]
1793 junit_suite_name = "my_suite"
1794
1795 .. tab:: ini
1796
1797 .. code-block:: ini
1798
1799 [pytest]
1800 junit_suite_name = my_suite
1801
1802 .. confval:: log_auto_indent
1803 :type: ``str``
1804 :default: ``"false"``
1805
1806 Allow selective auto-indentation of multiline log messages.
1807
1808 Supports command line option :option:`--log-auto-indent=[value]`
1809 and config option ``log_auto_indent = [value]`` to set the
1810 auto-indentation behavior for all logging.
1811
1812 ``[value]`` can be:
1813 * "True" or "On" - Dynamically auto-indent multiline log messages
1814 * "False" or "Off" or "0" - Do not auto-indent multiline log messages
1815 * "[positive integer]" - auto-indent multiline log messages by [value] spaces
1816
1817 .. tab:: toml
1818
1819 .. code-block:: toml
1820
1821 [pytest]
1822 log_auto_indent = "false"
1823
1824 .. tab:: ini
1825
1826 .. code-block:: ini
1827
1828 [pytest]
1829 log_auto_indent = false
1830
1831 Supports passing kwarg ``extra={"auto_indent": [value]}`` to
1832 calls to ``logging.log()`` to specify auto-indentation behavior for
1833 a specific entry in the log. ``extra`` kwarg overrides the value specified
1834 on the command line or in the config.
1835
1836 .. confval:: log_cli
1837 :type: ``bool``
1838 :default: ``false``
1839
1840 Enable log display during test run (also known as :ref:`"live logging" <live_logs>`).
1841
1842 .. tab:: toml
1843
1844 .. code-block:: toml
1845
1846 [pytest]
1847 log_cli = true
1848
1849 .. tab:: ini
1850
1851 .. code-block:: ini
1852
1853 [pytest]
1854 log_cli = true
1855
1856 .. confval:: log_cli_date_format
1857 :type: ``str``
1858 :default: Fallback to ``log_date_format``
1859
1860 Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for live logging.
1861
1862 .. tab:: toml
1863
1864 .. code-block:: toml
1865
1866 [pytest]
1867 log_cli_date_format = "%Y-%m-%d %H:%M:%S"
1868
1869 .. tab:: ini
1870
1871 .. code-block:: ini
1872
1873 [pytest]
1874 log_cli_date_format = %Y-%m-%d %H:%M:%S
1875
1876 For more information, see :ref:`live_logs`.
1877
1878 .. confval:: log_cli_format
1879 :type: ``str``
1880 :default: Fallback to ``log_format``
1881
1882 Sets a :py:mod:`logging`-compatible string used to format live logging messages.
1883
1884 .. tab:: toml
1885
1886 .. code-block:: toml
1887
1888 [pytest]
1889 log_cli_format = "%(asctime)s %(levelname)s %(message)s"
1890
1891 .. tab:: ini
1892
1893 .. code-block:: ini
1894
1895 [pytest]
1896 log_cli_format = %(asctime)s %(levelname)s %(message)s
1897
1898 For more information, see :ref:`live_logs`.
1899
1900
1901 .. confval:: log_cli_level
1902 :type: ``str``
1903 :default: Fallback to ``log_level``
1904
1905 Sets the minimum log message level that should be captured for live logging. The integer value or
1906 the names of the levels can be used. Note in TOML the integer must be quoted, as there is no support
1907 for config parameters of mixed type.
1908
1909 .. tab:: toml
1910
1911 .. code-block:: toml
1912
1913 [pytest]
1914 log_cli_level = "INFO"
1915 log_cli_level = "10"
1916
1917 .. tab:: ini
1918
1919 .. code-block:: ini
1920
1921 [pytest]
1922 log_cli_level = INFO
1923 log_cli_level = 10
1924
1925 For more information, see :ref:`live_logs`.
1926
1927
1928 .. confval:: log_date_format
1929 :type: ``str``
1930 :default: ``"%H:%M:%S"``
1931
1932 Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for logging capture.
1933
1934 .. tab:: toml
1935
1936 .. code-block:: toml
1937
1938 [pytest]
1939 log_date_format = "%Y-%m-%d %H:%M:%S"
1940
1941 .. tab:: ini
1942
1943 .. code-block:: ini
1944
1945 [pytest]
1946 log_date_format = %Y-%m-%d %H:%M:%S
1947
1948 For more information, see :ref:`logging`.
1949
1950
1951 .. confval:: log_file
1952 :type: ``str``
1953
1954 Sets a file name relative to the current working directory where log messages should be written to, in addition
1955 to the other logging facilities that are active.
1956
1957 .. tab:: toml
1958
1959 .. code-block:: toml
1960
1961 [pytest]
1962 log_file = "logs/pytest-logs.txt"
1963
1964 .. tab:: ini
1965
1966 .. code-block:: ini
1967
1968 [pytest]
1969 log_file = logs/pytest-logs.txt
1970
1971 For more information, see :ref:`logging`.
1972
1973
1974 .. confval:: log_file_date_format
1975 :type: ``str``
1976 :default: Fallback to ``log_date_format``
1977
1978 Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for the logging file.
1979
1980 .. tab:: toml
1981
1982 .. code-block:: toml
1983
1984 [pytest]
1985 log_file_date_format = "%Y-%m-%d %H:%M:%S"
1986
1987 .. tab:: ini
1988
1989 .. code-block:: ini
1990
1991 [pytest]
1992 log_file_date_format = %Y-%m-%d %H:%M:%S
1993
1994 For more information, see :ref:`logging`.
1995
1996 .. confval:: log_file_format
1997 :type: ``str``
1998 :default: Fallback to ``log_format``
1999
2000 Sets a :py:mod:`logging`-compatible string used to format logging messages redirected to the logging file.
2001
2002 .. tab:: toml
2003
2004 .. code-block:: toml
2005
2006 [pytest]
2007 log_file_format = "%(asctime)s %(levelname)s %(message)s"
2008
2009 .. tab:: ini
2010
2011 .. code-block:: ini
2012
2013 [pytest]
2014 log_file_format = %(asctime)s %(levelname)s %(message)s
2015
2016 For more information, see :ref:`logging`.
2017
2018 .. confval:: log_file_level
2019 :type: ``str``
2020 :default: Fallback to ``log_level``
2021
2022 Sets the minimum log message level that should be captured for the logging file.
2023 The integer value (in TOML, as a string) or the names of the levels can be used.
2024
2025 .. tab:: toml
2026
2027 .. code-block:: toml
2028
2029 [pytest]
2030 log_file_level = "INFO"
2031 log_cli_level = "10"
2032
2033 .. tab:: ini
2034
2035 .. code-block:: ini
2036
2037 [pytest]
2038 log_file_level = INFO
2039 log_cli_level = 10
2040
2041 For more information, see :ref:`logging`.
2042
2043
2044 .. confval:: log_file_mode
2045 :type: ``str``
2046 :default: ``"w"``
2047
2048 Sets the mode that the logging file is opened with.
2049 The options are ``"w"`` to recreate the file or ``"a"`` to append to the file.
2050
2051 .. tab:: toml
2052
2053 .. code-block:: toml
2054
2055 [pytest]
2056 log_file_mode = "a"
2057
2058 .. tab:: ini
2059
2060 .. code-block:: ini
2061
2062 [pytest]
2063 log_file_mode = a
2064
2065 For more information, see :ref:`logging`.
2066
2067
2068 .. confval:: log_format
2069 :type: ``str``
2070 :default: ``%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s``
2071
2072 Sets a :py:mod:`logging`-compatible string used to format captured logging messages.
2073
2074 .. tab:: toml
2075
2076 .. code-block:: toml
2077
2078 [pytest]
2079 log_format = "%(asctime)s %(levelname)s %(message)s"
2080
2081 .. tab:: ini
2082
2083 .. code-block:: ini
2084
2085 [pytest]
2086 log_format = %(asctime)s %(levelname)s %(message)s
2087
2088 For more information, see :ref:`logging`.
2089
2090
2091 .. confval:: log_level
2092 :type: ``str``
2093
2094 Sets the minimum log message level that should be captured for logging capture.
2095 Not set by default, so it depends on the root/parent log handler's effective level,
2096 where it is ``"WARNING"`` by default.
2097 The integer value (in TOML, as a string) or the names of the levels can be used.
2098
2099 .. tab:: toml
2100
2101 .. code-block:: toml
2102
2103 [pytest]
2104 log_level = "INFO"
2105 log_cli_level = "10"
2106
2107 .. tab:: ini
2108
2109 .. code-block:: ini
2110
2111 [pytest]
2112 log_level = INFO
2113 log_cli_level = 10
2114
2115 For more information, see :ref:`logging`.
2116
2117
2118 .. confval:: markers
2119 :type: ``list[str]``
2120
2121 When the :confval:`strict_markers` configuration option is set,
2122 only known markers - defined in code by core pytest or some plugin - are allowed.
2123
2124 You can list additional markers in this setting to add them to the whitelist,
2125 in which case you probably want to set :confval:`strict_markers` to ``true``
2126 to avoid future regressions:
2127
2128 .. tab:: toml
2129
2130 .. code-block:: toml
2131
2132 [pytest]
2133 addopts = ["--strict-markers"]
2134 markers = ["slow", "serial"]
2135
2136 .. tab:: ini
2137
2138 .. code-block:: ini
2139
2140 [pytest]
2141 strict_markers = true
2142 markers =
2143 slow
2144 serial
2145
2146
2147 .. confval:: minversion
2148 :type: ``str``
2149
2150 Specifies a minimal pytest version required for running tests.
2151
2152 .. tab:: toml
2153
2154 .. code-block:: toml
2155
2156 [pytest]
2157 minversion = 3.0 # will fail if we run with pytest-2.8
2158
2159 .. tab:: ini
2160
2161 .. code-block:: ini
2162
2163 [pytest]
2164 minversion = 3.0 # will fail if we run with pytest-2.8
2165
2166
2167 .. confval:: norecursedirs
2168 :type: ``list[str]``
2169 :default: ``["*.egg", ".*", "_darcs", "build", "CVS", "dist", "node_modules", "venv", "{arch}"]``
2170
2171 Set the directory basename patterns to avoid when recursing
2172 for test discovery. The individual (fnmatch-style) patterns are
2173 applied to the basename of a directory to decide if to recurse into it.
2174 Pattern matching characters::
2175
2176 * matches everything
2177 ? matches any single character
2178 [seq] matches any character in seq
2179 [!seq] matches any char not in seq
2180
2181 Setting a ``norecursedirs`` replaces the default. Here is an example of
2182 how to avoid certain directories:
2183
2184 .. tab:: toml
2185
2186 .. code-block:: toml
2187
2188 [pytest]
2189 norecursedirs = [".svn", "_build", "tmp*"]
2190
2191 .. tab:: ini
2192
2193 .. code-block:: ini
2194
2195 [pytest]
2196 norecursedirs = .svn _build tmp*
2197
2198 This would tell ``pytest`` to not look into typical subversion or
2199 sphinx-build directories or into any ``tmp`` prefixed directory.
2200
2201 Additionally, ``pytest`` will attempt to intelligently identify and ignore
2202 a virtualenv. Any directory deemed to be the root of a virtual environment
2203 will not be considered during test collection unless
2204 :option:`--collect-in-virtualenv` is given. Note also that ``norecursedirs``
2205 takes precedence over ``--collect-in-virtualenv``; e.g. if you intend to
2206 run tests in a virtualenv with a base directory that matches ``'.*'`` you
2207 *must* override ``norecursedirs`` in addition to using the
2208 ``--collect-in-virtualenv`` flag.
2209
2210
2211 .. confval:: python_classes
2212 :type: ``list[str]``
2213 :default: ``["Test"]``
2214
2215 One or more name prefixes or glob-style patterns determining which classes
2216 are considered for test collection. Search for multiple glob patterns by
2217 adding a space between patterns. By default, pytest will consider any
2218 class prefixed with ``Test`` as a test collection. Here is an example of how
2219 to collect tests from classes that end in ``Suite``:
2220
2221 .. tab:: toml
2222
2223 .. code-block:: toml
2224
2225 [pytest]
2226 python_classes = ["*Suite"]
2227
2228 .. tab:: ini
2229
2230 .. code-block:: ini
2231
2232 [pytest]
2233 python_classes = *Suite
2234
2235 Note that ``unittest.TestCase`` derived classes are always collected
2236 regardless of this option, as ``unittest``'s own collection framework is used
2237 to collect those tests.
2238
2239
2240 .. confval:: python_files
2241 :type: ``list[str]``
2242 :default: ``["test_*.py", "*_test.py"]``
2243
2244 One or more Glob-style file patterns determining which python files
2245 are considered as test modules. Search for multiple glob patterns by
2246 adding a space between patterns:
2247
2248 .. tab:: toml
2249
2250 .. code-block:: toml
2251
2252 [pytest]
2253 python_files = ["test_*.py", "check_*.py", "example_*.py"]
2254
2255 .. tab:: ini
2256
2257 .. code-block:: ini
2258
2259 [pytest]
2260 python_files = test_*.py check_*.py example_*.py
2261
2262 Or one per line:
2263
2264 .. code-block:: ini
2265
2266 [pytest]
2267 python_files =
2268 test_*.py
2269 check_*.py
2270 example_*.py
2271
2272
2273
2274 .. confval:: python_functions
2275 :type: ``list[str]``
2276 :default: ``["test"]``
2277
2278 One or more name prefixes or glob-patterns determining which test functions
2279 and methods are considered tests. Search for multiple glob patterns by
2280 adding a space between patterns. By default, pytest will consider any
2281 function prefixed with ``test`` as a test. Here is an example of how
2282 to collect test functions and methods that end in ``_test``:
2283
2284 .. tab:: toml
2285
2286 .. code-block:: toml
2287
2288 [pytest]
2289 python_functions = ["*_test"]
2290
2291 .. tab:: ini
2292
2293 .. code-block:: ini
2294
2295 [pytest]
2296 python_functions = *_test
2297
2298 Note that this has no effect on methods that live on a ``unittest.TestCase``
2299 derived class, as ``unittest``'s own collection framework is used
2300 to collect those tests.
2301
2302 See :ref:`change naming conventions` for more detailed examples.
2303
2304
2305 .. confval:: pythonpath
2306 :type: ``list[str]``
2307
2308 Sets list of directories that should be added to the python search path.
2309 Directories will be added to the head of :data:`sys.path`.
2310 Similar to the :envvar:`PYTHONPATH` environment variable, the directories will be
2311 included in where Python will look for imported modules.
2312 Paths are relative to the :ref:`rootdir <rootdir>` directory.
2313 Directories remain in path for the duration of the test session.
2314
2315 .. tab:: toml
2316
2317 .. code-block:: toml
2318
2319 [pytest]
2320 pythonpath = ["src1", "src2"]
2321
2322 .. tab:: ini
2323
2324 .. code-block:: ini
2325
2326 [pytest]
2327 pythonpath = src1 src2
2328
2329
2330 .. confval:: required_plugins
2331 :type: ``list[str]``
2332
2333 A space separated list of plugins that must be present for pytest to run.
2334 Plugins can be listed with or without version specifiers directly following
2335 their name. Whitespace between different version specifiers is not allowed.
2336 If any one of the plugins is not found, emit an error.
2337
2338 .. tab:: toml
2339
2340 .. code-block:: toml
2341
2342 [pytest]
2343 required_plugins = ["pytest-django>=3.0.0,<4.0.0", "pytest-html", "pytest-xdist>=1.0.0"]
2344
2345 .. tab:: ini
2346
2347 .. code-block:: ini
2348
2349 [pytest]
2350 required_plugins = pytest-django>=3.0.0,<4.0.0 pytest-html pytest-xdist>=1.0.0
2351
2352
2353 .. confval:: strict
2354 :type: ``bool``
2355 :default: ``false``
2356
2357 If set to ``true``, enable "strict mode", which enables the following options:
2358
2359 * :confval:`strict_config`
2360 * :confval:`strict_markers`
2361 * :confval:`strict_parametrization_ids`
2362 * :confval:`strict_xfail`
2363
2364 Plugins may also enable their own strictness options.
2365
2366 If you explicitly set an individual strictness option, it takes precedence over ``strict``.
2367
2368 .. note::
2369 If pytest adds new strictness options in the future, they will also be enabled in strict mode.
2370 Therefore, you should only enable strict mode if you use a pinned/locked version of pytest,
2371 or if you want to proactively adopt new strictness options as they are added.
2372
2373 .. tab:: toml
2374
2375 .. code-block:: toml
2376
2377 [pytest]
2378 strict = true
2379
2380 .. tab:: ini
2381
2382 .. code-block:: ini
2383
2384 [pytest]
2385 strict = true
2386
2387 .. versionadded:: 9.0
2388
2389
2390 .. confval:: strict_config
2391 :type: ``bool``
2392 :default: ``false``
2393
2394 If set to ``true``, any warnings encountered while parsing the ``pytest`` section of the configuration file will raise errors.
2395
2396 .. tab:: toml
2397
2398 .. code-block:: toml
2399
2400 [pytest]
2401 strict_config = true
2402
2403 .. tab:: ini
2404
2405 .. code-block:: ini
2406
2407 [pytest]
2408 strict_config = true
2409
2410 You can also enable this option via the :confval:`strict` option.
2411
2412
2413 .. confval:: strict_markers
2414 :type: ``bool``
2415 :default: ``false``
2416
2417 If set to ``true``, markers not registered in the ``markers`` section of the configuration file will raise errors.
2418
2419 .. tab:: toml
2420
2421 .. code-block:: toml
2422
2423 [pytest]
2424 strict_markers = true
2425
2426 .. tab:: ini
2427
2428 .. code-block:: ini
2429
2430 [pytest]
2431 strict_markers = true
2432
2433 You can also enable this option via the :confval:`strict` option.
2434
2435
2436 .. confval:: strict_parametrization_ids
2437 :type: ``bool``
2438 :default: ``false``
2439
2440 If set to ``true``, pytest emits an error if it detects non-unique parameter set IDs.
2441
2442 If not set, pytest automatically handles this by adding `0`, `1`, ... to duplicate IDs,
2443 making them unique.
2444
2445 .. tab:: toml
2446
2447 .. code-block:: toml
2448
2449 [pytest]
2450 strict_parametrization_ids = true
2451
2452 .. tab:: ini
2453
2454 .. code-block:: ini
2455
2456 [pytest]
2457 strict_parametrization_ids = true
2458
2459 You can also enable this option via the :confval:`strict` option.
2460
2461 For example,
2462
2463 .. code-block:: python
2464
2465 import pytest
2466
2467
2468 @pytest.mark.parametrize("letter", ["a", "a"])
2469 def test_letter_is_ascii(letter):
2470 assert letter.isascii()
2471
2472 will emit an error because both cases (parameter sets) have the same auto-generated ID "a".
2473
2474 To fix the error, if you decide to keep the duplicates, explicitly assign unique IDs:
2475
2476 .. code-block:: python
2477
2478 import pytest
2479
2480
2481 @pytest.mark.parametrize("letter", ["a", "a"], ids=["a0", "a1"])
2482 def test_letter_is_ascii(letter):
2483 assert letter.isascii()
2484
2485 See :func:`parametrize <pytest.Metafunc.parametrize>` and :func:`pytest.param` for other ways to set IDs.
2486
2487
2488 .. confval:: strict_xfail
2489 :type: ``bool``
2490 :default: ``false``
2491
2492 If set to ``true``, tests marked with ``@pytest.mark.xfail`` that actually succeed will by default fail the
2493 test suite.
2494 For more information, see :ref:`xfail strict tutorial`.
2495
2496 .. tab:: toml
2497
2498 .. code-block:: toml
2499
2500 [pytest]
2501 strict_xfail = true
2502
2503 .. tab:: ini
2504
2505 .. code-block:: ini
2506
2507 [pytest]
2508 strict_xfail = true
2509
2510 You can also enable this option via the :confval:`strict` option.
2511
2512 .. versionchanged:: 9.0
2513 Renamed from ``xfail_strict`` to ``strict_xfail``.
2514 ``xfail_strict`` is accepted as an alias for ``strict_xfail``.
2515
2516
2517 .. confval:: testpaths
2518 :type: ``list[str]``
2519
2520 Sets list of directories that should be searched for tests when
2521 no specific directories, files or test ids are given in the command line when
2522 executing pytest from the :ref:`rootdir <rootdir>` directory.
2523 File system paths may use shell-style wildcards, including the recursive
2524 ``**`` pattern.
2525
2526 Useful when all project tests are in a known location to speed up
2527 test collection and to avoid picking up undesired tests by accident.
2528
2529 .. tab:: toml
2530
2531 .. code-block:: toml
2532
2533 [pytest]
2534 testpaths = ["testing", "doc"]
2535
2536 .. tab:: ini
2537
2538 .. code-block:: ini
2539
2540 [pytest]
2541 testpaths = testing doc
2542
2543 This configuration means that executing:
2544
2545 .. code-block:: console
2546
2547 pytest
2548
2549 has the same practical effects as executing:
2550
2551 .. code-block:: console
2552
2553 pytest testing doc
2554
2555 .. confval:: tmp_path_retention_count
2556 :type: ``str``
2557 :default: ``"3"``
2558
2559 How many sessions should pytest keep the `tmp_path` directories,
2560 according to :confval:`tmp_path_retention_policy`.
2561
2562 .. tab:: toml
2563
2564 .. code-block:: toml
2565
2566 [pytest]
2567 tmp_path_retention_count = "3"
2568
2569 .. tab:: ini
2570
2571 .. code-block:: ini
2572
2573 [pytest]
2574 tmp_path_retention_count = 3
2575
2576
2577 .. confval:: tmp_path_retention_policy
2578 :type: ``str``
2579 :default: ``"all"``
2580
2581 Controls which directories created by the `tmp_path` fixture are kept around,
2582 based on test outcome.
2583
2584 * `all`: retains directories for all tests, regardless of the outcome.
2585 * `failed`: retains directories only for tests with outcome `error` or `failed`.
2586 * `none`: directories are always removed after each test ends, regardless of the outcome.
2587
2588 .. tab:: toml
2589
2590 .. code-block:: toml
2591
2592 [pytest]
2593 tmp_path_retention_policy = "all"
2594
2595 .. tab:: ini
2596
2597 .. code-block:: ini
2598
2599 [pytest]
2600 tmp_path_retention_policy = all
2601
2602
2603 .. confval:: truncation_limit_chars
2604 :type: ``int``
2605 :default: ``640``
2606
2607 Controls maximum number of characters to truncate assertion message contents.
2608
2609 Setting value to ``0`` disables the character limit for truncation.
2610
2611 .. tab:: toml
2612
2613 .. code-block:: toml
2614
2615 [pytest]
2616 truncation_limit_chars = 640
2617
2618 .. tab:: ini
2619
2620 .. code-block:: ini
2621
2622 [pytest]
2623 truncation_limit_chars = 640
2624
2625 pytest truncates the assert messages to a certain limit by default to prevent comparison with large data to overload the console output.
2626
2627 .. note::
2628
2629 If pytest detects it is :ref:`running on CI <ci-pipelines>`, truncation is disabled automatically.
2630
2631
2632 .. confval:: truncation_limit_lines
2633 :type: ``int``
2634 :default: ``8``
2635
2636 Controls maximum number of lines to truncate assertion message contents.
2637
2638 Setting value to ``0`` disables the lines limit for truncation.
2639
2640 .. tab:: toml
2641
2642 .. code-block:: toml
2643
2644 [pytest]
2645 truncation_limit_lines = 8
2646
2647 .. tab:: ini
2648
2649 .. code-block:: ini
2650
2651 [pytest]
2652 truncation_limit_lines = 8
2653
2654 pytest truncates the assert messages to a certain limit by default to prevent comparison with large data to overload the console output.
2655
2656 .. note::
2657
2658 If pytest detects it is :ref:`running on CI <ci-pipelines>`, truncation is disabled automatically.
2659
2660
2661 .. confval:: usefixtures
2662 :type: ``list[str]``
2663
2664 List of fixtures that will be applied to all test functions; this is semantically the same to apply
2665 the ``@pytest.mark.usefixtures`` marker to all test functions.
2666
2667
2668 .. tab:: toml
2669
2670 .. code-block:: toml
2671
2672 [pytest]
2673 usefixtures = ["clean_db"]
2674
2675 .. tab:: ini
2676
2677 .. code-block:: ini
2678
2679 [pytest]
2680 usefixtures =
2681 clean_db
2682
2683
2684 .. confval:: verbosity_assertions
2685 :type: ``str``
2686 :default: ``"auto"``
2687
2688 Set a verbosity level specifically for assertion related output, overriding the application wide level.
2689
2690 .. tab:: toml
2691
2692 .. code-block:: toml
2693
2694 [pytest]
2695 verbosity_assertions = "2"
2696
2697 .. tab:: ini
2698
2699 .. code-block:: ini
2700
2701 [pytest]
2702 verbosity_assertions = 2
2703
2704 A special value of ``"auto"`` can be used to explicitly use the global verbosity level.
2705
2706
2707 .. confval:: assertion_text_diff_style
2708 :type: ``str``
2709 :default: ``"ndiff"``
2710
2711 Set how pytest renders diffs for string equality assertions.
2712
2713 Supported values are:
2714
2715 * ``ndiff``: use the inline diff rendering markers.
2716 * ``block``: render each string in separate ``Left:`` and ``Right:`` blocks.
2717
2718 .. tab:: toml
2719
2720 .. code-block:: toml
2721
2722 [pytest]
2723 assertion_text_diff_style = "block"
2724
2725 .. tab:: ini
2726
2727 .. code-block:: ini
2728
2729 [pytest]
2730 assertion_text_diff_style = block
2731
2732
2733 .. confval:: verbosity_subtests
2734 :type: ``str``
2735 :default: ``"auto"``
2736
2737 Set the verbosity level specifically for **passed** subtests.
2738
2739 .. tab:: toml
2740
2741 .. code-block:: toml
2742
2743 [pytest]
2744 verbosity_subtests = "1"
2745
2746 .. tab:: ini
2747
2748 .. code-block:: ini
2749
2750 [pytest]
2751 verbosity_subtests = 1
2752
2753 A value of ``1`` or higher will show output for **passed** subtests (**failed** subtests are always reported).
2754 Passed subtests output can be suppressed with the value ``0``, which overwrites the :option:`-v` command-line option.
2755
2756 A special value of ``"auto"`` can be used to explicitly use the global verbosity level.
2757
2758 See also: :ref:`subtests`.
2759
2760
2761 .. confval:: verbosity_test_cases
2762 :type: ``str``
2763 :default: ``"auto"``
2764
2765 Set a verbosity level specifically for test case execution related output, overriding the application wide level.
2766
2767 .. tab:: toml
2768
2769 .. code-block:: toml
2770
2771 [pytest]
2772 verbosity_test_cases = "2"
2773
2774 .. tab:: ini
2775
2776 .. code-block:: ini
2777
2778 [pytest]
2779 verbosity_test_cases = 2
2780
2781 A special value of ``"auto"`` can be used to explicitly use the global verbosity level.
2782
2783
2784 .. _`command-line-flags`:
2785
2786 Command-line Flags
2787 ------------------
2788
2789 This section documents all command-line options provided by pytest's core plugins.
2790
2791 .. note::
2792
2793 External plugins can add their own command-line options.
2794 This reference documents only the options from pytest's core plugins.
2795 To see all available options including those from installed plugins, run ``pytest --help``.
2796
2797 Test Selection
2798 ~~~~~~~~~~~~~~
2799
2800 .. option:: -k EXPRESSION
2801
2802 Only run tests which match the given substring expression.
2803 An expression is a Python evaluable expression where all names are substring-matched against test names and their parent classes.
2804
2805 Examples::
2806
2807 pytest -k "test_method or test_other" # matches names containing 'test_method' OR 'test_other'
2808 pytest -k "not test_method" # matches names NOT containing 'test_method'
2809 pytest -k "not test_method and not test_other" # excludes both
2810
2811 The matching is case-insensitive.
2812 Keywords are also matched to classes and functions containing extra names in their ``extra_keyword_matches`` set.
2813
2814 See :ref:`select-tests` for more information and examples.
2815
2816 .. option:: -m MARKEXPR
2817
2818 Only run tests matching given mark expression.
2819 Supports ``and``, ``or``, and ``not`` operators.
2820
2821 Examples::
2822
2823 pytest -m slow # run tests marked with @pytest.mark.slow
2824 pytest -m "not slow" # run tests NOT marked slow
2825 pytest -m "mark1 and not mark2" # run tests marked mark1 but not mark2
2826
2827 See :ref:`mark` for more information on markers.
2828
2829 .. option:: --markers
2830
2831 Show all available markers (builtin, plugin, and per-project markers defined in configuration).
2832
2833 Test Execution Control
2834 ~~~~~~~~~~~~~~~~~~~~~~~
2835
2836 .. option:: -x, --exitfirst
2837
2838 Exit instantly on first error or failed test.
2839
2840 .. option:: --maxfail=NUM
2841
2842 Exit after first ``num`` failures or errors.
2843 Useful for CI environments where you want to fail fast but see a few failures.
2844
2845 .. option:: --last-failed, --lf
2846
2847 Rerun only the tests that failed at the last run.
2848 If no tests failed (or no cached data exists), all tests are run.
2849 See also :confval:`cache_dir` and :ref:`cache`.
2850
2851 .. option:: --failed-first, --ff
2852
2853 Run all tests, but run the last failures first.
2854 This may re-order tests and thus lead to repeated fixture setup/teardown.
2855
2856 .. option:: --new-first, --nf
2857
2858 Run tests from new files first, then the rest of the tests sorted by file modification time.
2859
2860 .. option:: --stepwise, --sw
2861
2862 Exit on test failure and continue from last failing test next time.
2863 Useful for fixing multiple test failures one at a time.
2864
2865 See :ref:`cache stepwise` for more information.
2866
2867 .. option:: --stepwise-skip, --sw-skip
2868
2869 Ignore the first failing test but stop on the next failing test.
2870 Implicitly enables :option:`--stepwise`.
2871
2872 .. option:: --stepwise-reset, --sw-reset
2873
2874 Resets stepwise state, restarting the stepwise workflow.
2875 Implicitly enables :option:`--stepwise`.
2876
2877 .. option:: --last-failed-no-failures, --lfnf
2878
2879 With :option:`--last-failed`, determines whether to execute tests when there are no previously known failures or when no cached ``lastfailed`` data was found.
2880
2881 * ``all`` (default): runs the full test suite again
2882 * ``none``: just emits a message about no known failures and exits successfully
2883
2884 .. option:: --runxfail
2885
2886 Report the results of xfail tests as if they were not marked.
2887 Useful for debugging xfailed tests.
2888 See :ref:`xfail`.
2889
2890 Collection
2891 ~~~~~~~~~~
2892
2893 .. option:: --collect-only, --co
2894
2895 Only collect tests, don't execute them.
2896 Shows which tests would be collected and run.
2897
2898 .. option:: --pyargs
2899
2900 Try to interpret all arguments as Python packages.
2901 Useful for running tests of installed packages::
2902
2903 pytest --pyargs pkg.testing
2904
2905 .. option:: --ignore=PATH
2906
2907 Ignore path during collection (multi-allowed).
2908 Can be specified multiple times.
2909
2910 .. option:: --ignore-glob=PATTERN
2911
2912 Ignore path pattern during collection (multi-allowed).
2913 Supports glob patterns.
2914
2915 .. option:: --deselect=NODEID_PREFIX
2916
2917 Deselect item (via node id prefix) during collection (multi-allowed).
2918
2919 .. option:: --confcutdir=DIR
2920
2921 Only load ``conftest.py`` files relative to specified directory.
2922
2923 .. option:: --noconftest
2924
2925 Don't load any ``conftest.py`` files.
2926
2927 .. option:: --keep-duplicates
2928
2929 Keep duplicate tests. By default, pytest removes duplicate test items.
2930
2931 .. option:: --collect-in-virtualenv
2932
2933 Don't ignore tests in a local virtualenv directory.
2934 By default, pytest skips tests in virtualenv directories.
2935
2936 .. option:: --continue-on-collection-errors
2937
2938 Force test execution even if collection errors occur.
2939
2940 .. option:: --import-mode
2941
2942 Prepend/append to sys.path when importing test modules and conftest files.
2943
2944 * ``prepend`` (default): prepend to sys.path
2945 * ``append``: append to sys.path
2946 * ``importlib``: use importlib to import test modules
2947
2948 See :ref:`pythonpath` for more information.
2949
2950 Fixtures
2951 ~~~~~~~~
2952
2953 .. option:: --fixtures, --funcargs
2954
2955 Show available fixtures, sorted by plugin appearance.
2956 Fixtures with leading ``_`` are only shown with :option:`--verbose`.
2957
2958 .. option:: --fixtures-per-test
2959
2960 Show fixtures per test.
2961
2962 .. option:: --setup-only
2963
2964 Only setup fixtures, do not execute tests.
2965 See :ref:`how-to-fixtures`.
2966
2967 .. option:: --setup-show
2968
2969 Show setup of fixtures while executing tests.
2970
2971 .. option:: --setup-plan
2972
2973 Show what fixtures and tests would be executed but don't execute anything.
2974
2975 Debugging
2976 ~~~~~~~~~
2977
2978 .. option:: --pdb
2979
2980 Start the interactive Python debugger on errors or KeyboardInterrupt.
2981 See :ref:`pdb-option`.
2982
2983 .. option:: --pdbcls=MODULENAME:CLASSNAME
2984
2985 Specify a custom interactive Python debugger for use with :option:`--pdb`.
2986
2987 Example::
2988
2989 pytest --pdbcls=IPython.terminal.debugger:TerminalPdb
2990
2991 .. option:: --trace
2992
2993 Immediately break when running each test.
2994
2995 See :ref:`trace-option` for more information.
2996
2997 .. option:: --full-trace
2998
2999 Don't cut any tracebacks (default is to cut).
3000
3001 See :ref:`how-to-modifying-python-tb-printing` for more information.
3002
3003 .. option:: --debug, --debug=DEBUG_FILE_NAME
3004
3005 Store internal tracing debug information in this log file.
3006 This file is opened with ``'w'`` and truncated as a result, care advised.
3007 Default file name if not specified: ``pytestdebug.log``.
3008
3009 .. option:: --trace-config
3010
3011 Trace considerations of conftest.py files.
3012
3013 Output and Reporting
3014 ~~~~~~~~~~~~~~~~~~~~
3015
3016 .. option:: -v, --verbose
3017
3018 Increase verbosity.
3019 Can be specified multiple times (e.g., ``-vv``) for even more verbose output.
3020
3021 See :ref:`pytest.fine_grained_verbosity` for fine-grained control over verbosity.
3022
3023 .. option:: -q, --quiet
3024
3025 Decrease verbosity.
3026
3027 .. option:: --verbosity=NUM
3028
3029 Set verbosity level explicitly. Default: 0.
3030
3031 .. option:: -r CHARS, --report-chars=CHARS
3032
3033 Show extra test summary info as specified by chars:
3034
3035 * ``f``: failed
3036 * ``E``: error
3037 * ``s``: skipped
3038 * ``x``: xfailed
3039 * ``X``: xpassed
3040 * ``p``: passed
3041 * ``P``: passed with output
3042 * ``a``: all except passed (p/P)
3043 * ``A``: all
3044 * ``w``: warnings (enabled by default)
3045 * ``N``: resets the list
3046
3047 Default: ``'fE'``
3048
3049 Examples::
3050
3051 pytest -rA # show all outcomes
3052 pytest -rfE # show only failed and errors (default)
3053 pytest -rfs # show failed and skipped
3054
3055 See :ref:`pytest.detailed_failed_tests_usage` for more information.
3056
3057 .. option:: --no-header
3058
3059 Disable header.
3060
3061 .. option:: --no-summary
3062
3063 Disable summary.
3064
3065 .. option:: --no-fold-skipped
3066
3067 Do not fold skipped tests in short summary.
3068
3069 .. option:: --force-short-summary
3070
3071 Force condensed summary output regardless of verbosity level.
3072
3073 .. option:: -l, --showlocals
3074
3075 Show locals in tracebacks (disabled by default).
3076
3077 .. option:: --no-showlocals
3078
3079 Hide locals in tracebacks (negate :option:`--showlocals` passed through addopts).
3080
3081 .. option:: --tb=STYLE
3082
3083 Traceback print mode:
3084
3085 * ``auto``: intelligent traceback formatting (default)
3086 * ``long``: exhaustive, informative traceback formatting
3087 * ``short``: shorter traceback format
3088 * ``line``: only the failing line
3089 * ``native``: Python's standard traceback
3090 * ``no``: no traceback
3091
3092 See :ref:`how-to-modifying-python-tb-printing` for examples.
3093
3094 .. option:: --xfail-tb
3095
3096 Show tracebacks for xfail (as long as :option:`--tb` != ``no``).
3097
3098 .. option:: --show-capture
3099
3100 Controls how captured stdout/stderr/log is shown on failed tests.
3101
3102 * ``no``: don't show captured output
3103 * ``stdout``: show captured stdout
3104 * ``stderr``: show captured stderr
3105 * ``log``: show captured logging
3106 * ``all`` (default): show all captured output
3107
3108 .. option:: --color=WHEN
3109
3110 Color terminal output:
3111
3112 * ``yes``: always use color
3113 * ``no``: never use color
3114 * ``auto`` (default): use color if terminal supports it
3115
3116 .. option:: --code-highlight={yes,no}
3117
3118 Whether code should be highlighted (only if :option:`--color` is also enabled).
3119 Default: ``yes``.
3120
3121 .. option:: --pastebin=MODE
3122
3123 Send failed|all info to bpaste.net pastebin service.
3124
3125 .. option:: --durations=NUM
3126
3127 Show N slowest setup/test durations (N=0 for all).
3128 See :ref:`durations`.
3129
3130 .. option:: --durations-min=NUM
3131
3132 Minimal duration in seconds for inclusion in slowest list.
3133 Default: 0.005 (or 0.0 if ``-vv`` is given).
3134
3135 Output Capture
3136 ~~~~~~~~~~~~~~
3137
3138 .. option:: --capture=METHOD
3139
3140 Per-test capturing method:
3141
3142 * ``fd``: capture at file descriptor level (default)
3143 * ``sys``: capture at sys level
3144 * ``no``: don't capture output
3145 * ``tee-sys``: capture but also show output on terminal
3146
3147 See :ref:`captures`.
3148
3149 .. option:: -s
3150
3151 Shortcut for :option:`--capture=no`.
3152
3153 JUnit XML
3154 ~~~~~~~~~
3155
3156 .. option:: --junit-xml=PATH, --junitxml=PATH
3157
3158 Create junit-xml style report file at given path.
3159
3160 .. option:: --junit-prefix=STR, --junitprefix=STR
3161
3162 Prepend prefix to classnames in junit-xml output.
3163
3164 Cache
3165 ~~~~~
3166
3167 .. option:: --cache-show[=PATTERN]
3168
3169 Show cache contents, don't perform collection or tests.
3170 Default glob pattern: ``'*'``.
3171
3172 .. option:: --cache-clear
3173
3174 Remove all cache contents at start of test run.
3175 See :ref:`cache`.
3176
3177 Warnings
3178 ~~~~~~~~
3179
3180 .. option:: --disable-pytest-warnings, --disable-warnings
3181
3182 Disable warnings summary.
3183
3184 .. option:: -W WARNING, --pythonwarnings=WARNING
3185
3186 Set which warnings to report, see ``-W`` option of Python itself.
3187 Can be specified multiple times.
3188
3189 .. option:: --max-warnings=NUM
3190
3191 Exit with :class:`pytest.ExitCode` ``MAX_WARNINGS_ERROR`` (code ``6``) if all the tests pass, but the number
3192 of warnings exceeds the given threshold. By default there is no limit.
3193 Can also be set via the :confval:`max_warnings` configuration option.
3194
3195 Doctest
3196 ~~~~~~~
3197
3198 .. option:: --doctest-modules
3199
3200 Run doctests in all .py modules.
3201
3202 See :ref:`doctest` for more information on using doctests with pytest.
3203
3204 .. option:: --doctest-report
3205
3206 Choose another output format for diffs on doctest failure:
3207
3208 * ``none``
3209 * ``cdiff``
3210 * ``ndiff``
3211 * ``udiff``
3212 * ``only_first_failure``
3213
3214 .. option:: --doctest-glob=PATTERN
3215
3216 Doctests file matching pattern.
3217 Default: ``test*.txt``.
3218
3219 .. option:: --doctest-ignore-import-errors
3220
3221 Ignore doctest collection errors.
3222
3223 .. option:: --doctest-continue-on-failure
3224
3225 For a given doctest, continue to run after the first failure.
3226
3227 Configuration
3228 ~~~~~~~~~~~~~
3229
3230 .. option:: -c FILE, --config-file=FILE
3231
3232 Load configuration from ``FILE`` instead of trying to locate one of the implicit configuration files.
3233
3234 .. option:: --rootdir=ROOTDIR
3235
3236 Define root directory for tests.
3237 Can be relative path: ``'root_dir'``, ``'./root_dir'``, ``'root_dir/another_dir/'``; absolute path: ``'/home/user/root_dir'``; path with variables: ``'$HOME/root_dir'``.
3238
3239 .. option:: --basetemp=DIR
3240
3241 Base temporary directory for this test run.
3242 Warning: this directory is removed if it exists.
3243
3244 See :ref:`temporary directory location and retention` for more information.
3245
3246 .. option:: -o OPTION=VALUE, --override-ini=OPTION=VALUE
3247
3248 Override configuration option with ``option=value`` style.
3249 Can be specified multiple times.
3250
3251 Example::
3252
3253 pytest -o strict_xfail=true -o cache_dir=cache
3254
3255 .. option:: --strict-config
3256
3257 Enables the :confval:`strict_config` option.
3258
3259 .. option:: --strict-markers
3260
3261 Enables the :confval:`strict_markers` option.
3262
3263 .. option:: --strict
3264
3265 Enables the :confval:`strict` option (which enables all strictness options).
3266
3267 .. option:: --assert=MODE
3268
3269 Control assertion debugging tools:
3270
3271 * ``plain``: performs no assertion debugging
3272 * ``rewrite`` (default): rewrites assert statements in test modules on import to provide assert expression information
3273
3274 Logging
3275 ~~~~~~~
3276
3277 See :ref:`logging` for a guide on using these flags.
3278
3279 .. option:: --log-level=LEVEL
3280
3281 Level of messages to catch/display.
3282 Not set by default, so it depends on the root/parent log handler's effective level, where it is ``WARNING`` by default.
3283
3284 .. option:: --log-format=FORMAT
3285
3286 Log format used by the logging module.
3287
3288 .. option:: --log-date-format=FORMAT
3289
3290 Log date format used by the logging module.
3291
3292 .. option:: --log-cli-level=LEVEL
3293
3294 CLI logging level. See :ref:`live_logs`.
3295
3296 .. option:: --log-cli-format=FORMAT
3297
3298 Log format used by the logging module for CLI output.
3299
3300 .. option:: --log-cli-date-format=FORMAT
3301
3302 Log date format used by the logging module for CLI output.
3303
3304 .. option:: --log-file=PATH
3305
3306 Path to a file logging will be written to.
3307
3308 .. option:: --log-file-mode
3309
3310 Log file open mode:
3311
3312 * ``w`` (default): recreate the file
3313 * ``a``: append to the file
3314
3315 .. option:: --log-file-level=LEVEL
3316
3317 Log file logging level.
3318
3319 .. option:: --log-file-format=FORMAT
3320
3321 Log format used by the logging module for the log file.
3322
3323 .. option:: --log-file-date-format=FORMAT
3324
3325 Log date format used by the logging module for the log file.
3326
3327 .. option:: --log-auto-indent=VALUE
3328
3329 Auto-indent multiline messages passed to the logging module.
3330 Accepts ``true|on``, ``false|off`` or an integer.
3331
3332 .. option:: --log-disable=LOGGER
3333
3334 Disable a logger by name. Can be passed multiple times.
3335
3336 Plugin and Extension Management
3337 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3338
3339 .. option:: -p NAME
3340
3341 Early-load given plugin module name or entry point (multi-allowed).
3342 To avoid loading of plugins, use the ``no:`` prefix, e.g. ``no:doctest``.
3343 See also :option:`--disable-plugin-autoload`.
3344
3345 .. option:: --disable-plugin-autoload
3346
3347 Disable plugin auto-loading through entry point packaging metadata.
3348 Only plugins explicitly specified in :option:`-p` or env var :envvar:`PYTEST_PLUGINS` will be loaded.
3349
3350 Version and Help
3351 ~~~~~~~~~~~~~~~~
3352
3353 .. option:: -V, --version
3354
3355 Display pytest version and information about plugins. When given twice, also display information about plugins.
3356
3357 .. option:: -h, --help
3358
3359 Show help message and configuration info.
3360
3361 Complete Help Output
3362 ~~~~~~~~~~~~~~~~~~~~
3363
3364 All the command-line flags can also be obtained by running ``pytest --help``::
3365
3366 $ pytest --help
3367 usage: pytest [options] [file_or_dir] [file_or_dir] [...]
3368
3369 positional arguments:
3370 file_or_dir
3371
3372 general:
3373 -k EXPRESSION Only run tests which match the given substring
3374 expression. An expression is a Python evaluable
3375 expression where all names are substring-matched
3376 against test names and their parent classes.
3377 Example: -k 'test_method or test_other' matches all
3378 test functions and classes whose name contains
3379 'test_method' or 'test_other', while -k 'not
3380 test_method' matches those that don't contain
3381 'test_method' in their names. -k 'not test_method
3382 and not test_other' will eliminate the matches.
3383 Additionally keywords are matched to classes and
3384 functions containing extra names in their
3385 'extra_keyword_matches' set, as well as functions
3386 which have names assigned directly to them. The
3387 matching is case-insensitive.
3388 -m MARKEXPR Only run tests matching given mark expression. For
3389 example: -m 'mark1 and not mark2'.
3390 --markers show markers (builtin, plugin and per-project ones).
3391 -x, --exitfirst Exit instantly on first error or failed test
3392 --maxfail=num Exit after first num failures or errors
3393 --strict-config Enables the strict_config option
3394 --strict-markers Enables the strict_markers option
3395 --strict Enables the strict option
3396 --fixtures, --funcargs
3397 Show available fixtures, sorted by plugin appearance
3398 (fixtures with leading '_' are only shown with '-v')
3399 --fixtures-per-test Show fixtures per test
3400 --pdb Start the interactive Python debugger on errors or
3401 KeyboardInterrupt
3402 --pdbcls=modulename:classname
3403 Specify a custom interactive Python debugger for use
3404 with --pdb.For example:
3405 --pdbcls=IPython.terminal.debugger:TerminalPdb
3406 --trace Immediately break when running each test
3407 --capture=method Per-test capturing method: one of fd|sys|no|tee-sys
3408 -s Shortcut for --capture=no
3409 --runxfail Report the results of xfail tests as if they were
3410 not marked
3411 --lf, --last-failed Rerun only the tests that failed at the last run (or
3412 all if none failed)
3413 --ff, --failed-first Run all tests, but run the last failures first. This
3414 may re-order tests and thus lead to repeated fixture
3415 setup/teardown.
3416 --nf, --new-first Run tests from new files first, then the rest of the
3417 tests sorted by file mtime
3418 --cache-show=[CACHESHOW]
3419 Show cache contents, don't perform collection or
3420 tests. Optional argument: glob (default: '*').
3421 --cache-clear Remove all cache contents at start of test run
3422 --lfnf, --last-failed-no-failures={all,none}
3423 With ``--lf``, determines whether to execute tests
3424 when there are no previously (known) failures or
3425 when no cached ``lastfailed`` data was found.
3426 ``all`` (the default) runs the full test suite
3427 again. ``none`` just emits a message about no known
3428 failures and exits successfully.
3429 --sw, --stepwise Exit on test failure and continue from last failing
3430 test next time
3431 --sw-skip, --stepwise-skip
3432 Ignore the first failing test but stop on the next
3433 failing test. Implicitly enables --stepwise.
3434 --sw-reset, --stepwise-reset
3435 Resets stepwise state, restarting the stepwise
3436 workflow. Implicitly enables --stepwise.
3437
3438 Reporting:
3439 --durations=N Show N slowest setup/test durations (N=0 for all)
3440 --durations-min=N Minimal duration in seconds for inclusion in slowest
3441 list. Default: 0.005 (or 0.0 if -vv is given).
3442 -v, --verbose Increase verbosity
3443 --no-header Disable header
3444 --no-summary Disable summary
3445 --no-fold-skipped Do not fold skipped tests in short summary.
3446 --force-short-summary
3447 Force condensed summary output regardless of
3448 verbosity level.
3449 -q, --quiet Decrease verbosity
3450 --verbosity=VERBOSE Set verbosity. Default: 0.
3451 -r, --report-chars chars
3452 Show extra test summary info as specified by chars:
3453 (f)ailed, (E)rror, (s)kipped, (x)failed, (X)passed,
3454 (p)assed, (P)assed with output, (a)ll except passed
3455 (p/P), or (A)ll. (w)arnings are enabled by default
3456 (see --disable-warnings), 'N' can be used to reset
3457 the list. (default: 'fE').
3458 --disable-warnings, --disable-pytest-warnings
3459 Disable warnings summary
3460 -l, --showlocals Show locals in tracebacks (disabled by default)
3461 --no-showlocals Hide locals in tracebacks (negate --showlocals
3462 passed through addopts)
3463 --tb=style Traceback print mode
3464 (auto/long/short/line/native/no)
3465 --xfail-tb Show tracebacks for xfail (as long as --tb != no)
3466 --show-capture={no,stdout,stderr,log,all}
3467 Controls how captured stdout/stderr/log is shown on
3468 failed tests. Default: all.
3469 --full-trace Don't cut any tracebacks (default is to cut)
3470 --color=color Color terminal output (yes/no/auto)
3471 --code-highlight={yes,no}
3472 Whether code should be highlighted (only if --color
3473 is also enabled). Default: yes.
3474 --pastebin=mode Send failed|all info to bpaste.net pastebin service
3475 --junitxml, --junit-xml=path
3476 Create junit-xml style report file at given path
3477 --junitprefix, --junit-prefix=str
3478 Prepend prefix to classnames in junit-xml output
3479
3480 pytest-warnings:
3481 -W, --pythonwarnings PYTHONWARNINGS
3482 Set which warnings to report, see -W option of
3483 Python itself
3484 --max-warnings=num Exit with error if all tests pass but the number of
3485 warnings exceeds this threshold
3486
3487 collection:
3488 --collect-only, --co Only collect tests, don't execute them
3489 --pyargs Try to interpret all arguments as Python packages
3490 --ignore=path Ignore path during collection (multi-allowed)
3491 --ignore-glob=path Ignore path pattern during collection (multi-
3492 allowed)
3493 --deselect=nodeid_prefix
3494 Deselect item (via node id prefix) during collection
3495 (multi-allowed)
3496 --confcutdir=dir Only load conftest.py's relative to specified dir
3497 --noconftest Don't load any conftest.py files
3498 --keep-duplicates Keep duplicate tests
3499 --collect-in-virtualenv
3500 Don't ignore tests in a local virtualenv directory
3501 --continue-on-collection-errors
3502 Force test execution even if collection errors occur
3503 --import-mode={prepend,append,importlib}
3504 Prepend/append to sys.path when importing test
3505 modules and conftest files. Default: prepend.
3506 --doctest-modules Run doctests in all .py modules
3507 --doctest-report={none,cdiff,ndiff,udiff,only_first_failure}
3508 Choose another output format for diffs on doctest
3509 failure
3510 --doctest-glob=pat Doctests file matching pattern, default: test*.txt
3511 --doctest-ignore-import-errors
3512 Ignore doctest collection errors
3513 --doctest-continue-on-failure
3514 For a given doctest, continue to run after the first
3515 failure
3516
3517 test session debugging and configuration:
3518 -c, --config-file FILE
3519 Load configuration from `FILE` instead of trying to
3520 locate one of the implicit configuration files.
3521 --rootdir=ROOTDIR Define root directory for tests. Can be relative
3522 path: 'root_dir', './root_dir',
3523 'root_dir/another_dir/'; absolute path:
3524 '/home/user/root_dir'; path with variables:
3525 '$HOME/root_dir'.
3526 --basetemp=dir Base temporary directory for this test run.
3527 (Warning: this directory is removed if it exists.)
3528 -V, --version Display pytest version and information about
3529 plugins. When given twice, also display information
3530 about plugins.
3531 -h, --help Show help message and configuration info
3532 -p name Early-load given plugin module name or entry point
3533 (multi-allowed). To avoid loading of plugins, use
3534 the `no:` prefix, e.g. `no:doctest`. See also
3535 --disable-plugin-autoload.
3536 --disable-plugin-autoload
3537 Disable plugin auto-loading through entry point
3538 packaging metadata. Only plugins explicitly
3539 specified in -p or env var PYTEST_PLUGINS will be
3540 loaded.
3541 --trace-config Trace considerations of conftest.py files
3542 --debug=[DEBUG_FILE_NAME]
3543 Store internal tracing debug information in this log
3544 file. This file is opened with 'w' and truncated as
3545 a result, care advised. Default: pytestdebug.log.
3546 -o, --override-ini OVERRIDE_INI
3547 Override configuration option with "option=value"
3548 style, e.g. `-o strict_xfail=True -o
3549 cache_dir=cache`.
3550 --assert=MODE Control assertion debugging tools.
3551 'plain' performs no assertion debugging.
3552 'rewrite' (the default) rewrites assert statements
3553 in test modules on import to provide assert
3554 expression information.
3555 --setup-only Only setup fixtures, do not execute tests
3556 --setup-show Show setup of fixtures while executing tests
3557 --setup-plan Show what fixtures and tests would be executed but
3558 don't execute anything
3559
3560 logging:
3561 --log-level=LEVEL Level of messages to catch/display. Not set by
3562 default, so it depends on the root/parent log
3563 handler's effective level, where it is "WARNING" by
3564 default.
3565 --log-format=LOG_FORMAT
3566 Log format used by the logging module
3567 --log-date-format=LOG_DATE_FORMAT
3568 Log date format used by the logging module
3569 --log-cli-level=LOG_CLI_LEVEL
3570 CLI logging level
3571 --log-cli-format=LOG_CLI_FORMAT
3572 Log format used by the logging module
3573 --log-cli-date-format=LOG_CLI_DATE_FORMAT
3574 Log date format used by the logging module
3575 --log-file=LOG_FILE Path to a file when logging will be written to
3576 --log-file-mode={w,a}
3577 Log file open mode
3578 --log-file-level=LOG_FILE_LEVEL
3579 Log file logging level
3580 --log-file-format=LOG_FILE_FORMAT
3581 Log format used by the logging module
3582 --log-file-date-format=LOG_FILE_DATE_FORMAT
3583 Log date format used by the logging module
3584 --log-auto-indent=LOG_AUTO_INDENT
3585 Auto-indent multiline messages passed to the logging
3586 module. Accepts true|on, false|off or an integer.
3587 --log-disable=LOGGER_DISABLE
3588 Disable a logger by name. Can be passed multiple
3589 times.
3590
3591 [pytest] configuration options in the first pytest.toml|pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:
3592
3593 markers (linelist): Register new markers for test functions
3594 empty_parameter_set_mark (string):
3595 Default marker for empty parametersets
3596 strict_config (bool): Any warnings encountered while parsing the `pytest`
3597 section of the configuration file raise errors
3598 strict_markers (bool):
3599 Markers not registered in the `markers` section of
3600 the configuration file raise errors
3601 strict (bool): Enables all strictness options, currently:
3602 strict_config, strict_markers, strict_xfail,
3603 strict_parametrization_ids
3604 filterwarnings (linelist):
3605 Each line specifies a pattern for
3606 warnings.filterwarnings. Processed after
3607 -W/--pythonwarnings.
3608 max_warnings (string):
3609 Exit with error if all tests pass but the number of
3610 warnings exceeds this threshold
3611 norecursedirs (args): Directory patterns to avoid for recursion
3612 testpaths (args): Directories to search for tests when no files or
3613 directories are given on the command line
3614 collect_imported_tests (bool):
3615 Whether to collect tests in imported modules outside
3616 `testpaths`
3617 consider_namespace_packages (bool):
3618 Consider namespace packages when resolving module
3619 names during import
3620 usefixtures (args): List of default fixtures to be used with this
3621 project
3622 python_files (args): Glob-style file patterns for Python test module
3623 discovery
3624 python_classes (args):
3625 Prefixes or glob names for Python test class
3626 discovery
3627 python_functions (args):
3628 Prefixes or glob names for Python test function and
3629 method discovery
3630 disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):
3631 Disable string escape non-ASCII characters, might
3632 cause unwanted side effects(use at your own risk)
3633 strict_parametrization_ids (bool):
3634 Emit an error if non-unique parameter set IDs are
3635 detected
3636 console_output_style (string):
3637 Console output: "classic", or with additional
3638 progress information ("progress" (percentage) |
3639 "count" | "progress-even-when-capture-no" (forces
3640 progress even when capture=no)
3641 verbosity_test_cases (string):
3642 Specify a verbosity level for test case execution,
3643 overriding the main level. Higher levels will
3644 provide more detailed information about each test
3645 case executed.
3646 strict_xfail (bool): Default for the strict parameter of xfail markers
3647 when not given explicitly (default: False) (alias:
3648 xfail_strict)
3649 tmp_path_retention_count (string):
3650 How many sessions should we keep the `tmp_path`
3651 directories, according to
3652 `tmp_path_retention_policy`.
3653 tmp_path_retention_policy (string):
3654 Controls which directories created by the `tmp_path`
3655 fixture are kept around, based on test outcome.
3656 (all/failed/none)
3657 enable_assertion_pass_hook (bool):
3658 Enables the pytest_assertion_pass hook. Make sure to
3659 delete any previously generated pyc cache files.
3660 truncation_limit_lines (string):
3661 Set threshold of LINES after which truncation will
3662 take effect
3663 truncation_limit_chars (string):
3664 Set threshold of CHARS after which truncation will
3665 take effect
3666 assertion_text_diff_style (string):
3667 Choose how pytest renders diffs for string equality
3668 assertions: ndiff or block
3669 verbosity_assertions (string):
3670 Specify a verbosity level for assertions, overriding
3671 the main level. Higher levels will provide more
3672 detailed explanation when an assertion fails.
3673 junit_suite_name (string):
3674 Test suite name for JUnit report
3675 junit_logging (string):
3676 Write captured log messages to JUnit report: one of
3677 no|log|system-out|system-err|out-err|all
3678 junit_log_passing_tests (bool):
3679 Capture log information for passing tests to JUnit
3680 report:
3681 junit_duration_report (string):
3682 Duration time to report: one of total|call
3683 junit_family (string):
3684 Emit XML for schema: one of legacy|xunit1|xunit2
3685 doctest_optionflags (args):
3686 Option flags for doctests
3687 doctest_encoding (string):
3688 Encoding used for doctest files
3689 cache_dir (string): Cache directory path
3690 log_level (string): Default value for --log-level
3691 log_format (string): Default value for --log-format
3692 log_date_format (string):
3693 Default value for --log-date-format
3694 log_cli (bool): Enable log display during test run (also known as
3695 "live logging")
3696 log_cli_level (string):
3697 Default value for --log-cli-level
3698 log_cli_format (string):
3699 Default value for --log-cli-format
3700 log_cli_date_format (string):
3701 Default value for --log-cli-date-format
3702 log_file (string): Default value for --log-file
3703 log_file_mode (string):
3704 Default value for --log-file-mode
3705 log_file_level (string):
3706 Default value for --log-file-level
3707 log_file_format (string):
3708 Default value for --log-file-format
3709 log_file_date_format (string):
3710 Default value for --log-file-date-format
3711 log_auto_indent (string):
3712 Default value for --log-auto-indent
3713 faulthandler_timeout (string):
3714 Dump the traceback of all threads if a test takes
3715 more than TIMEOUT seconds to finish
3716 faulthandler_exit_on_timeout (bool):
3717 Exit the test process if a test takes more than
3718 faulthandler_timeout seconds to finish
3719 verbosity_subtests (string):
3720 Specify verbosity level for subtests. Higher levels
3721 will generate output for passed subtests. Failed
3722 subtests are always reported.
3723 addopts (args): Extra command line options
3724 minversion (string): Minimally required pytest version
3725 pythonpath (paths): Add paths to sys.path
3726 required_plugins (args):
3727 Plugins that must be present for pytest to run
3728
3729 Environment variables:
3730 CI When set to a non-empty value, pytest knows it is running in a CI process and does not truncate summary info
3731 BUILD_NUMBER Equivalent to CI
3732 PYTEST_ADDOPTS Extra command line options
3733 PYTEST_PLUGINS Comma-separated plugins to load during startup
3734 PYTEST_DISABLE_PLUGIN_AUTOLOAD Set to disable plugin auto-loading
3735 PYTEST_DEBUG Set to enable debug tracing of pytest's internals
3736 PYTEST_DEBUG_TEMPROOT Override the system temporary directory
3737 PYTEST_THEME The Pygments style to use for code output
3738 PYTEST_THEME_MODE Set the PYTEST_THEME to be either 'dark' or 'light'
3739
3740
3741 to see available markers type: pytest --markers
3742 to see available fixtures type: pytest --fixtures
3743 (shown according to specified file_or_dir or current dir if not specified; fixtures with leading '_' are only shown with the '-v' option