Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/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 .. contents::
11 :depth: 3
12 :local:
13
14 Constants
15 ---------
16
17 pytest.__version__
18 ~~~~~~~~~~~~~~~~~~
19
20 The current pytest version, as a string::
21
22 >>> import pytest
23 >>> pytest.__version__
24 '7.0.0'
25
26
27 .. _`version-tuple`:
28
29 pytest.version_tuple
30 ~~~~~~~~~~~~~~~~~~~~
31
32 .. versionadded:: 7.0
33
34 The current pytest version, as a tuple::
35
36 >>> import pytest
37 >>> pytest.version_tuple
38 (7, 0, 0)
39
40 For pre-releases, the last component will be a string with the prerelease version::
41
42 >>> import pytest
43 >>> pytest.version_tuple
44 (7, 0, '0rc1')
45
46
47 Functions
48 ---------
49
50 pytest.approx
51 ~~~~~~~~~~~~~
52
53 .. autofunction:: pytest.approx
54
55 pytest.fail
56 ~~~~~~~~~~~
57
58 **Tutorial**: :ref:`skipping`
59
60 .. autofunction:: pytest.fail(reason, [pytrace=True, msg=None])
61
62 .. class:: pytest.fail.Exception
63
64 The exception raised by :func:`pytest.fail`.
65
66 pytest.skip
67 ~~~~~~~~~~~
68
69 .. autofunction:: pytest.skip(reason, [allow_module_level=False, msg=None])
70
71 .. class:: pytest.skip.Exception
72
73 The exception raised by :func:`pytest.skip`.
74
75 .. _`pytest.importorskip ref`:
76
77 pytest.importorskip
78 ~~~~~~~~~~~~~~~~~~~
79
80 .. autofunction:: pytest.importorskip
81
82 pytest.xfail
83 ~~~~~~~~~~~~
84
85 .. autofunction:: pytest.xfail
86
87 .. class:: pytest.xfail.Exception
88
89 The exception raised by :func:`pytest.xfail`.
90
91 pytest.exit
92 ~~~~~~~~~~~
93
94 .. autofunction:: pytest.exit(reason, [returncode=None, msg=None])
95
96 .. class:: pytest.exit.Exception
97
98 The exception raised by :func:`pytest.exit`.
99
100 pytest.main
101 ~~~~~~~~~~~
102
103 **Tutorial**: :ref:`pytest.main-usage`
104
105 .. autofunction:: pytest.main
106
107 pytest.param
108 ~~~~~~~~~~~~
109
110 .. autofunction:: pytest.param(*values, [id], [marks])
111
112 pytest.raises
113 ~~~~~~~~~~~~~
114
115 **Tutorial**: :ref:`assertraises`
116
117 .. autofunction:: pytest.raises(expected_exception: Exception [, *, match])
118 :with: excinfo
119
120 pytest.deprecated_call
121 ~~~~~~~~~~~~~~~~~~~~~~
122
123 **Tutorial**: :ref:`ensuring_function_triggers`
124
125 .. autofunction:: pytest.deprecated_call([match])
126 :with:
127
128 pytest.register_assert_rewrite
129 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
130
131 **Tutorial**: :ref:`assertion-rewriting`
132
133 .. autofunction:: pytest.register_assert_rewrite
134
135 pytest.warns
136 ~~~~~~~~~~~~
137
138 **Tutorial**: :ref:`assertwarnings`
139
140 .. autofunction:: pytest.warns(expected_warning: Exception, [match])
141 :with:
142
143 pytest.freeze_includes
144 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
145
146 **Tutorial**: :ref:`freezing-pytest`
147
148 .. autofunction:: pytest.freeze_includes
149
150 .. _`marks ref`:
151
152 Marks
153 -----
154
155 Marks can be used to apply metadata to *test functions* (but not fixtures), which can then be accessed by
156 fixtures or plugins.
157
158
159
160
161 .. _`pytest.mark.filterwarnings ref`:
162
163 pytest.mark.filterwarnings
164 ~~~~~~~~~~~~~~~~~~~~~~~~~~
165
166 **Tutorial**: :ref:`filterwarnings`
167
168 Add warning filters to marked test items.
169
170 .. py:function:: pytest.mark.filterwarnings(filter)
171
172 :keyword str filter:
173 A *warning specification string*, which is composed of contents of the tuple ``(action, message, category, module, lineno)``
174 as specified in :ref:`python:warning-filter` section of
175 the Python documentation, separated by ``":"``. Optional fields can be omitted.
176 Module names passed for filtering are not regex-escaped.
177
178 For example:
179
180 .. code-block:: python
181
182 @pytest.mark.filterwarnings("ignore:.*usage will be deprecated.*:DeprecationWarning")
183 def test_foo(): ...
184
185
186 .. _`pytest.mark.parametrize ref`:
187
188 pytest.mark.parametrize
189 ~~~~~~~~~~~~~~~~~~~~~~~
190
191 **Tutorial**: :ref:`parametrize`
192
193 This mark has the same signature as :py:meth:`pytest.Metafunc.parametrize`; see there.
194
195
196 .. _`pytest.mark.skip ref`:
197
198 pytest.mark.skip
199 ~~~~~~~~~~~~~~~~
200
201 **Tutorial**: :ref:`skip`
202
203 Unconditionally skip a test function.
204
205 .. py:function:: pytest.mark.skip(reason=None)
206
207 :keyword str reason: Reason why the test function is being skipped.
208
209
210 .. _`pytest.mark.skipif ref`:
211
212 pytest.mark.skipif
213 ~~~~~~~~~~~~~~~~~~
214
215 **Tutorial**: :ref:`skipif`
216
217 Skip a test function if a condition is ``True``.
218
219 .. py:function:: pytest.mark.skipif(condition, *, reason=None)
220
221 :type condition: bool or str
222 :param condition: ``True/False`` if the condition should be skipped or a :ref:`condition string <string conditions>`.
223 :keyword str reason: Reason why the test function is being skipped.
224
225
226 .. _`pytest.mark.usefixtures ref`:
227
228 pytest.mark.usefixtures
229 ~~~~~~~~~~~~~~~~~~~~~~~
230
231 **Tutorial**: :ref:`usefixtures`
232
233 Mark a test function as using the given fixture names.
234
235 .. py:function:: pytest.mark.usefixtures(*names)
236
237 :param args: The names of the fixture to use, as strings.
238
239 .. note::
240
241 When using `usefixtures` in hooks, it can only load fixtures when applied to a test function before test setup
242 (for example in the `pytest_collection_modifyitems` hook).
243
244 Also note that this mark has no effect when applied to **fixtures**.
245
246
247
248 .. _`pytest.mark.xfail ref`:
249
250 pytest.mark.xfail
251 ~~~~~~~~~~~~~~~~~~
252
253 **Tutorial**: :ref:`xfail`
254
255 Marks a test function as *expected to fail*.
256
257 .. py:function:: pytest.mark.xfail(condition=False, *, reason=None, raises=None, run=True, strict=xfail_strict)
258
259 :keyword Union[bool, str] condition:
260 Condition for marking the test function as xfail (``True/False`` or a
261 :ref:`condition string <string conditions>`). If a ``bool``, you also have
262 to specify ``reason`` (see :ref:`condition string <string conditions>`).
263 :keyword str reason:
264 Reason why the test function is marked as xfail.
265 :keyword raises:
266 Exception class (or tuple of classes) expected to be raised by the test function; other exceptions will fail the test.
267 Note that subclasses of the classes passed will also result in a match (similar to how the ``except`` statement works).
268 :type raises: Type[:py:exc:`Exception`]
269
270 :keyword bool run:
271 Whether the test function should actually be executed. If ``False``, the function will always xfail and will
272 not be executed (useful if a function is segfaulting).
273 :keyword bool strict:
274 * If ``False`` the function will be shown in the terminal output as ``xfailed`` if it fails
275 and as ``xpass`` if it passes. In both cases this will not cause the test suite to fail as a whole. This
276 is particularly useful to mark *flaky* tests (tests that fail at random) to be tackled later.
277 * If ``True``, the function will be shown in the terminal output as ``xfailed`` if it fails, but if it
278 unexpectedly passes then it will **fail** the test suite. This is particularly useful to mark functions
279 that are always failing and there should be a clear indication if they unexpectedly start to pass (for example
280 a new release of a library fixes a known bug).
281
282 Defaults to :confval:`xfail_strict`, which is ``False`` by default.
283
284
285 Custom marks
286 ~~~~~~~~~~~~
287
288 Marks are created dynamically using the factory object ``pytest.mark`` and applied as a decorator.
289
290 For example:
291
292 .. code-block:: python
293
294 @pytest.mark.timeout(10, "slow", method="thread")
295 def test_function(): ...
296
297 Will create and attach a :class:`Mark <pytest.Mark>` object to the collected
298 :class:`Item <pytest.Item>`, which can then be accessed by fixtures or hooks with
299 :meth:`Node.iter_markers <_pytest.nodes.Node.iter_markers>`. The ``mark`` object will have the following attributes:
300
301 .. code-block:: python
302
303 mark.args == (10, "slow")
304 mark.kwargs == {"method": "thread"}
305
306 Example for using multiple custom markers:
307
308 .. code-block:: python
309
310 @pytest.mark.timeout(10, "slow", method="thread")
311 @pytest.mark.slow
312 def test_function(): ...
313
314 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(...)``.
315
316 .. _`fixtures-api`:
317
318 Fixtures
319 --------
320
321 **Tutorial**: :ref:`fixture`
322
323 Fixtures are requested by test functions or other fixtures by declaring them as argument names.
324
325
326 Example of a test requiring a fixture:
327
328 .. code-block:: python
329
330 def test_output(capsys):
331 print("hello")
332 out, err = capsys.readouterr()
333 assert out == "hello\n"
334
335
336 Example of a fixture requiring another fixture:
337
338 .. code-block:: python
339
340 @pytest.fixture
341 def db_session(tmp_path):
342 fn = tmp_path / "db.file"
343 return connect(fn)
344
345 For more details, consult the full :ref:`fixtures docs <fixture>`.
346
347
348 .. _`pytest.fixture-api`:
349
350 @pytest.fixture
351 ~~~~~~~~~~~~~~~
352
353 .. autofunction:: pytest.fixture
354 :decorator:
355
356
357 .. fixture:: capfd
358
359 capfd
360 ~~~~~~
361
362 **Tutorial**: :ref:`captures`
363
364 .. autofunction:: _pytest.capture.capfd()
365 :no-auto-options:
366
367
368 .. fixture:: capfdbinary
369
370 capfdbinary
371 ~~~~~~~~~~~~
372
373 **Tutorial**: :ref:`captures`
374
375 .. autofunction:: _pytest.capture.capfdbinary()
376 :no-auto-options:
377
378
379 .. fixture:: caplog
380
381 caplog
382 ~~~~~~
383
384 **Tutorial**: :ref:`logging`
385
386 .. autofunction:: _pytest.logging.caplog()
387 :no-auto-options:
388
389 Returns a :class:`pytest.LogCaptureFixture` instance.
390
391 .. autoclass:: pytest.LogCaptureFixture()
392 :members:
393
394
395 .. fixture:: capsys
396
397 capsys
398 ~~~~~~
399
400 **Tutorial**: :ref:`captures`
401
402 .. autofunction:: _pytest.capture.capsys()
403 :no-auto-options:
404
405 .. autoclass:: pytest.CaptureFixture()
406 :members:
407
408 .. fixture:: capsysbinary
409
410 capsysbinary
411 ~~~~~~~~~~~~
412
413 **Tutorial**: :ref:`captures`
414
415 .. autofunction:: _pytest.capture.capsysbinary()
416 :no-auto-options:
417
418
419 .. fixture:: cache
420
421 config.cache
422 ~~~~~~~~~~~~
423
424 **Tutorial**: :ref:`cache`
425
426 The ``config.cache`` object allows other plugins and fixtures
427 to store and retrieve values across test runs. To access it from fixtures
428 request ``pytestconfig`` into your fixture and get it with ``pytestconfig.cache``.
429
430 Under the hood, the cache plugin uses the simple
431 ``dumps``/``loads`` API of the :py:mod:`json` stdlib module.
432
433 ``config.cache`` is an instance of :class:`pytest.Cache`:
434
435 .. autoclass:: pytest.Cache()
436 :members:
437
438
439 .. fixture:: doctest_namespace
440
441 doctest_namespace
442 ~~~~~~~~~~~~~~~~~
443
444 **Tutorial**: :ref:`doctest`
445
446 .. autofunction:: _pytest.doctest.doctest_namespace()
447
448
449 .. fixture:: monkeypatch
450
451 monkeypatch
452 ~~~~~~~~~~~
453
454 **Tutorial**: :ref:`monkeypatching`
455
456 .. autofunction:: _pytest.monkeypatch.monkeypatch()
457 :no-auto-options:
458
459 Returns a :class:`~pytest.MonkeyPatch` instance.
460
461 .. autoclass:: pytest.MonkeyPatch
462 :members:
463
464
465 .. fixture:: pytestconfig
466
467 pytestconfig
468 ~~~~~~~~~~~~
469
470 .. autofunction:: _pytest.fixtures.pytestconfig()
471
472
473 .. fixture:: pytester
474
475 pytester
476 ~~~~~~~~
477
478 .. versionadded:: 6.2
479
480 Provides a :class:`~pytest.Pytester` instance that can be used to run and test pytest itself.
481
482 It provides an empty directory where pytest can be executed in isolation, and contains facilities
483 to write tests, configuration files, and match against expected output.
484
485 To use it, include in your topmost ``conftest.py`` file:
486
487 .. code-block:: python
488
489 pytest_plugins = "pytester"
490
491
492
493 .. autoclass:: pytest.Pytester()
494 :members:
495
496 .. autoclass:: pytest.RunResult()
497 :members:
498
499 .. autoclass:: pytest.LineMatcher()
500 :members:
501 :special-members: __str__
502
503 .. autoclass:: pytest.HookRecorder()
504 :members:
505
506 .. autoclass:: pytest.RecordedHookCall()
507 :members:
508
509
510 .. fixture:: record_property
511
512 record_property
513 ~~~~~~~~~~~~~~~~~~~
514
515 **Tutorial**: :ref:`record_property example`
516
517 .. autofunction:: _pytest.junitxml.record_property()
518
519
520 .. fixture:: record_testsuite_property
521
522 record_testsuite_property
523 ~~~~~~~~~~~~~~~~~~~~~~~~~
524
525 **Tutorial**: :ref:`record_testsuite_property example`
526
527 .. autofunction:: _pytest.junitxml.record_testsuite_property()
528
529
530 .. fixture:: recwarn
531
532 recwarn
533 ~~~~~~~
534
535 **Tutorial**: :ref:`assertwarnings`
536
537 .. autofunction:: _pytest.recwarn.recwarn()
538 :no-auto-options:
539
540 .. autoclass:: pytest.WarningsRecorder()
541 :members:
542
543
544 .. fixture:: request
545
546 request
547 ~~~~~~~
548
549 **Example**: :ref:`request example`
550
551 The ``request`` fixture is a special fixture providing information of the requesting test function.
552
553 .. autoclass:: pytest.FixtureRequest()
554 :members:
555
556
557 .. fixture:: testdir
558
559 testdir
560 ~~~~~~~
561
562 Identical to :fixture:`pytester`, but provides an instance whose methods return
563 legacy ``py.path.local`` objects instead when applicable.
564
565 New code should avoid using :fixture:`testdir` in favor of :fixture:`pytester`.
566
567 .. autoclass:: pytest.Testdir()
568 :members:
569 :noindex: TimeoutExpired
570
571
572 .. fixture:: tmp_path
573
574 tmp_path
575 ~~~~~~~~
576
577 **Tutorial**: :ref:`tmp_path`
578
579 .. autofunction:: _pytest.tmpdir.tmp_path()
580 :no-auto-options:
581
582
583 .. fixture:: tmp_path_factory
584
585 tmp_path_factory
586 ~~~~~~~~~~~~~~~~
587
588 **Tutorial**: :ref:`tmp_path_factory example`
589
590 .. _`tmp_path_factory factory api`:
591
592 ``tmp_path_factory`` is an instance of :class:`~pytest.TempPathFactory`:
593
594 .. autoclass:: pytest.TempPathFactory()
595 :members:
596
597
598 .. fixture:: tmpdir
599
600 tmpdir
601 ~~~~~~
602
603 **Tutorial**: :ref:`tmpdir and tmpdir_factory`
604
605 .. autofunction:: _pytest.legacypath.LegacyTmpdirPlugin.tmpdir()
606 :no-auto-options:
607
608
609 .. fixture:: tmpdir_factory
610
611 tmpdir_factory
612 ~~~~~~~~~~~~~~
613
614 **Tutorial**: :ref:`tmpdir and tmpdir_factory`
615
616 ``tmpdir_factory`` is an instance of :class:`~pytest.TempdirFactory`:
617
618 .. autoclass:: pytest.TempdirFactory()
619 :members:
620
621
622 .. _`hook-reference`:
623
624 Hooks
625 -----
626
627 **Tutorial**: :ref:`writing-plugins`
628
629 Reference to all hooks which can be implemented by :ref:`conftest.py files <localplugin>` and :ref:`plugins <plugins>`.
630
631 @pytest.hookimpl
632 ~~~~~~~~~~~~~~~~
633
634 .. function:: pytest.hookimpl
635 :decorator:
636
637 pytest's decorator for marking functions as hook implementations.
638
639 See :ref:`writinghooks` and :func:`pluggy.HookimplMarker`.
640
641 @pytest.hookspec
642 ~~~~~~~~~~~~~~~~
643
644 .. function:: pytest.hookspec
645 :decorator:
646
647 pytest's decorator for marking functions as hook specifications.
648
649 See :ref:`declaringhooks` and :func:`pluggy.HookspecMarker`.
650
651 .. currentmodule:: _pytest.hookspec
652
653 Bootstrapping hooks
654 ~~~~~~~~~~~~~~~~~~~
655
656 Bootstrapping hooks called for plugins registered early enough (internal and setuptools plugins).
657
658 .. hook:: pytest_load_initial_conftests
659 .. autofunction:: pytest_load_initial_conftests
660 .. hook:: pytest_cmdline_parse
661 .. autofunction:: pytest_cmdline_parse
662 .. hook:: pytest_cmdline_main
663 .. autofunction:: pytest_cmdline_main
664
665 .. _`initialization-hooks`:
666
667 Initialization hooks
668 ~~~~~~~~~~~~~~~~~~~~
669
670 Initialization hooks called for plugins and ``conftest.py`` files.
671
672 .. hook:: pytest_addoption
673 .. autofunction:: pytest_addoption
674 .. hook:: pytest_addhooks
675 .. autofunction:: pytest_addhooks
676 .. hook:: pytest_configure
677 .. autofunction:: pytest_configure
678 .. hook:: pytest_unconfigure
679 .. autofunction:: pytest_unconfigure
680 .. hook:: pytest_sessionstart
681 .. autofunction:: pytest_sessionstart
682 .. hook:: pytest_sessionfinish
683 .. autofunction:: pytest_sessionfinish
684
685 .. hook:: pytest_plugin_registered
686 .. autofunction:: pytest_plugin_registered
687
688 Collection hooks
689 ~~~~~~~~~~~~~~~~
690
691 ``pytest`` calls the following hooks for collecting files and directories:
692
693 .. hook:: pytest_collection
694 .. autofunction:: pytest_collection
695 .. hook:: pytest_ignore_collect
696 .. autofunction:: pytest_ignore_collect
697 .. hook:: pytest_collect_directory
698 .. autofunction:: pytest_collect_directory
699 .. hook:: pytest_collect_file
700 .. autofunction:: pytest_collect_file
701 .. hook:: pytest_pycollect_makemodule
702 .. autofunction:: pytest_pycollect_makemodule
703
704 For influencing the collection of objects in Python modules
705 you can use the following hook:
706
707 .. hook:: pytest_pycollect_makeitem
708 .. autofunction:: pytest_pycollect_makeitem
709 .. hook:: pytest_generate_tests
710 .. autofunction:: pytest_generate_tests
711 .. hook:: pytest_make_parametrize_id
712 .. autofunction:: pytest_make_parametrize_id
713
714 Hooks for influencing test skipping:
715
716 .. hook:: pytest_markeval_namespace
717 .. autofunction:: pytest_markeval_namespace
718
719 After collection is complete, you can modify the order of
720 items, delete or otherwise amend the test items:
721
722 .. hook:: pytest_collection_modifyitems
723 .. autofunction:: pytest_collection_modifyitems
724
725 .. note::
726 If this hook is implemented in ``conftest.py`` files, it always receives all collected items, not only those
727 under the ``conftest.py`` where it is implemented.
728
729 .. autofunction:: pytest_collection_finish
730
731 Test running (runtest) hooks
732 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
733
734 All runtest related hooks receive a :py:class:`pytest.Item <pytest.Item>` object.
735
736 .. hook:: pytest_runtestloop
737 .. autofunction:: pytest_runtestloop
738 .. hook:: pytest_runtest_protocol
739 .. autofunction:: pytest_runtest_protocol
740 .. hook:: pytest_runtest_logstart
741 .. autofunction:: pytest_runtest_logstart
742 .. hook:: pytest_runtest_logfinish
743 .. autofunction:: pytest_runtest_logfinish
744 .. hook:: pytest_runtest_setup
745 .. autofunction:: pytest_runtest_setup
746 .. hook:: pytest_runtest_call
747 .. autofunction:: pytest_runtest_call
748 .. hook:: pytest_runtest_teardown
749 .. autofunction:: pytest_runtest_teardown
750 .. hook:: pytest_runtest_makereport
751 .. autofunction:: pytest_runtest_makereport
752
753 For deeper understanding you may look at the default implementation of
754 these hooks in ``_pytest.runner`` and maybe also
755 in ``_pytest.pdb`` which interacts with ``_pytest.capture``
756 and its input/output capturing in order to immediately drop
757 into interactive debugging when a test failure occurs.
758
759 .. hook:: pytest_pyfunc_call
760 .. autofunction:: pytest_pyfunc_call
761
762 Reporting hooks
763 ~~~~~~~~~~~~~~~
764
765 Session related reporting hooks:
766
767 .. hook:: pytest_collectstart
768 .. autofunction:: pytest_collectstart
769 .. hook:: pytest_make_collect_report
770 .. autofunction:: pytest_make_collect_report
771 .. hook:: pytest_itemcollected
772 .. autofunction:: pytest_itemcollected
773 .. hook:: pytest_collectreport
774 .. autofunction:: pytest_collectreport
775 .. hook:: pytest_deselected
776 .. autofunction:: pytest_deselected
777 .. hook:: pytest_report_header
778 .. autofunction:: pytest_report_header
779 .. hook:: pytest_report_collectionfinish
780 .. autofunction:: pytest_report_collectionfinish
781 .. hook:: pytest_report_teststatus
782 .. autofunction:: pytest_report_teststatus
783 .. hook:: pytest_report_to_serializable
784 .. autofunction:: pytest_report_to_serializable
785 .. hook:: pytest_report_from_serializable
786 .. autofunction:: pytest_report_from_serializable
787 .. hook:: pytest_terminal_summary
788 .. autofunction:: pytest_terminal_summary
789 .. hook:: pytest_fixture_setup
790 .. autofunction:: pytest_fixture_setup
791 .. hook:: pytest_fixture_post_finalizer
792 .. autofunction:: pytest_fixture_post_finalizer
793 .. hook:: pytest_warning_recorded
794 .. autofunction:: pytest_warning_recorded
795
796 Central hook for reporting about test execution:
797
798 .. hook:: pytest_runtest_logreport
799 .. autofunction:: pytest_runtest_logreport
800
801 Assertion related hooks:
802
803 .. hook:: pytest_assertrepr_compare
804 .. autofunction:: pytest_assertrepr_compare
805 .. hook:: pytest_assertion_pass
806 .. autofunction:: pytest_assertion_pass
807
808
809 Debugging/Interaction hooks
810 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
811
812 There are few hooks which can be used for special
813 reporting or interaction with exceptions:
814
815 .. hook:: pytest_internalerror
816 .. autofunction:: pytest_internalerror
817 .. hook:: pytest_keyboard_interrupt
818 .. autofunction:: pytest_keyboard_interrupt
819 .. hook:: pytest_exception_interact
820 .. autofunction:: pytest_exception_interact
821 .. hook:: pytest_enter_pdb
822 .. autofunction:: pytest_enter_pdb
823 .. hook:: pytest_leave_pdb
824 .. autofunction:: pytest_leave_pdb
825
826
827 Collection tree objects
828 -----------------------
829
830 These are the collector and item classes (collectively called "nodes") which
831 make up the collection tree.
832
833 Node
834 ~~~~
835
836 .. autoclass:: _pytest.nodes.Node()
837 :members:
838 :show-inheritance:
839
840 Collector
841 ~~~~~~~~~
842
843 .. autoclass:: pytest.Collector()
844 :members:
845 :show-inheritance:
846
847 Item
848 ~~~~
849
850 .. autoclass:: pytest.Item()
851 :members:
852 :show-inheritance:
853
854 File
855 ~~~~
856
857 .. autoclass:: pytest.File()
858 :members:
859 :show-inheritance:
860
861 FSCollector
862 ~~~~~~~~~~~
863
864 .. autoclass:: _pytest.nodes.FSCollector()
865 :members:
866 :show-inheritance:
867
868 Session
869 ~~~~~~~
870
871 .. autoclass:: pytest.Session()
872 :members:
873 :show-inheritance:
874
875 Package
876 ~~~~~~~
877
878 .. autoclass:: pytest.Package()
879 :members:
880 :show-inheritance:
881
882 Module
883 ~~~~~~
884
885 .. autoclass:: pytest.Module()
886 :members:
887 :show-inheritance:
888
889 Class
890 ~~~~~
891
892 .. autoclass:: pytest.Class()
893 :members:
894 :show-inheritance:
895
896 Function
897 ~~~~~~~~
898
899 .. autoclass:: pytest.Function()
900 :members:
901 :show-inheritance:
902
903 FunctionDefinition
904 ~~~~~~~~~~~~~~~~~~
905
906 .. autoclass:: _pytest.python.FunctionDefinition()
907 :members:
908 :show-inheritance:
909
910
911 Objects
912 -------
913
914 Objects accessible from :ref:`fixtures <fixture>` or :ref:`hooks <hook-reference>`
915 or importable from ``pytest``.
916
917
918 CallInfo
919 ~~~~~~~~
920
921 .. autoclass:: pytest.CallInfo()
922 :members:
923
924 CollectReport
925 ~~~~~~~~~~~~~
926
927 .. autoclass:: pytest.CollectReport()
928 :members:
929 :show-inheritance:
930 :inherited-members:
931
932 Config
933 ~~~~~~
934
935 .. autoclass:: pytest.Config()
936 :members:
937
938 Dir
939 ~~~
940
941 .. autoclass:: pytest.Dir()
942 :members:
943
944 Directory
945 ~~~~~~~~~
946
947 .. autoclass:: pytest.Directory()
948 :members:
949
950 ExceptionInfo
951 ~~~~~~~~~~~~~
952
953 .. autoclass:: pytest.ExceptionInfo()
954 :members:
955
956
957 ExitCode
958 ~~~~~~~~
959
960 .. autoclass:: pytest.ExitCode
961 :members:
962
963
964 FixtureDef
965 ~~~~~~~~~~
966
967 .. autoclass:: pytest.FixtureDef()
968 :members:
969 :show-inheritance:
970
971 MarkDecorator
972 ~~~~~~~~~~~~~
973
974 .. autoclass:: pytest.MarkDecorator()
975 :members:
976
977
978 MarkGenerator
979 ~~~~~~~~~~~~~
980
981 .. autoclass:: pytest.MarkGenerator()
982 :members:
983
984
985 Mark
986 ~~~~
987
988 .. autoclass:: pytest.Mark()
989 :members:
990
991
992 Metafunc
993 ~~~~~~~~
994
995 .. autoclass:: pytest.Metafunc()
996 :members:
997
998 Parser
999 ~~~~~~
1000
1001 .. autoclass:: pytest.Parser()
1002 :members:
1003
1004 OptionGroup
1005 ~~~~~~~~~~~
1006
1007 .. autoclass:: pytest.OptionGroup()
1008 :members:
1009
1010 PytestPluginManager
1011 ~~~~~~~~~~~~~~~~~~~
1012
1013 .. autoclass:: pytest.PytestPluginManager()
1014 :members:
1015 :undoc-members:
1016 :inherited-members:
1017 :show-inheritance:
1018
1019 TestReport
1020 ~~~~~~~~~~
1021
1022 .. autoclass:: pytest.TestReport()
1023 :members:
1024 :show-inheritance:
1025 :inherited-members:
1026
1027 TestShortLogReport
1028 ~~~~~~~~~~~~~~~~~~
1029
1030 .. autoclass:: pytest.TestShortLogReport()
1031 :members:
1032
1033 Result
1034 ~~~~~~~
1035
1036 Result object used within :ref:`hook wrappers <hookwrapper>`, see :py:class:`Result in the pluggy documentation <pluggy.Result>` for more information.
1037
1038 Stash
1039 ~~~~~
1040
1041 .. autoclass:: pytest.Stash
1042 :special-members: __setitem__, __getitem__, __delitem__, __contains__, __len__
1043 :members:
1044
1045 .. autoclass:: pytest.StashKey
1046 :show-inheritance:
1047 :members:
1048
1049
1050 Global Variables
1051 ----------------
1052
1053 pytest treats some global variables in a special manner when defined in a test module or
1054 ``conftest.py`` files.
1055
1056
1057 .. globalvar:: collect_ignore
1058
1059 **Tutorial**: :ref:`customizing-test-collection`
1060
1061 Can be declared in *conftest.py files* to exclude test directories or modules.
1062 Needs to be a list of paths (``str``, :class:`pathlib.Path` or any :class:`os.PathLike`).
1063
1064 .. code-block:: python
1065
1066 collect_ignore = ["setup.py"]
1067
1068
1069 .. globalvar:: collect_ignore_glob
1070
1071 **Tutorial**: :ref:`customizing-test-collection`
1072
1073 Can be declared in *conftest.py files* to exclude test directories or modules
1074 with Unix shell-style wildcards. Needs to be ``list[str]`` where ``str`` can
1075 contain glob patterns.
1076
1077 .. code-block:: python
1078
1079 collect_ignore_glob = ["*_ignore.py"]
1080
1081
1082 .. globalvar:: pytest_plugins
1083
1084 **Tutorial**: :ref:`available installable plugins`
1085
1086 Can be declared at the **global** level in *test modules* and *conftest.py files* to register additional plugins.
1087 Can be either a ``str`` or ``Sequence[str]``.
1088
1089 .. code-block:: python
1090
1091 pytest_plugins = "myapp.testsupport.myplugin"
1092
1093 .. code-block:: python
1094
1095 pytest_plugins = ("myapp.testsupport.tools", "myapp.testsupport.regression")
1096
1097
1098 .. globalvar:: pytestmark
1099
1100 **Tutorial**: :ref:`scoped-marking`
1101
1102 Can be declared at the **global** level in *test modules* to apply one or more :ref:`marks <marks ref>` to all
1103 test functions and methods. Can be either a single mark or a list of marks (applied in left-to-right order).
1104
1105 .. code-block:: python
1106
1107 import pytest
1108
1109 pytestmark = pytest.mark.webtest
1110
1111
1112 .. code-block:: python
1113
1114 import pytest
1115
1116 pytestmark = [pytest.mark.integration, pytest.mark.slow]
1117
1118
1119 Environment Variables
1120 ---------------------
1121
1122 Environment variables that can be used to change pytest's behavior.
1123
1124 .. envvar:: CI
1125
1126 When set (regardless of value), pytest acknowledges that is running in a CI process. Alternative to ``BUILD_NUMBER`` variable.
1127
1128 .. envvar:: BUILD_NUMBER
1129
1130 When set (regardless of value), pytest acknowledges that is running in a CI process. Alternative to CI variable.
1131
1132 .. envvar:: PYTEST_ADDOPTS
1133
1134 This contains a command-line (parsed by the py:mod:`shlex` module) that will be **prepended** to the command line given
1135 by the user, see :ref:`adding default options` for more information.
1136
1137 .. envvar:: PYTEST_VERSION
1138
1139 This environment variable is defined at the start of the pytest session and is undefined afterwards.
1140 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.
1141
1142 .. envvar:: PYTEST_CURRENT_TEST
1143
1144 This is not meant to be set by users, but is set by pytest internally with the name of the current test so other
1145 processes can inspect it, see :ref:`pytest current test env` for more information.
1146
1147 .. envvar:: PYTEST_DEBUG
1148
1149 When set, pytest will print tracing and debug information.
1150
1151 .. envvar:: PYTEST_DISABLE_PLUGIN_AUTOLOAD
1152
1153 When set, disables plugin auto-loading through setuptools entrypoints. Only explicitly specified plugins will be
1154 loaded.
1155
1156 .. envvar:: PYTEST_PLUGINS
1157
1158 Contains comma-separated list of modules that should be loaded as plugins:
1159
1160 .. code-block:: bash
1161
1162 export PYTEST_PLUGINS=mymodule.plugin,xdist
1163
1164 .. envvar:: PYTEST_THEME
1165
1166 Sets a `pygment style <https://pygments.org/docs/styles/>`_ to use for the code output.
1167
1168 .. envvar:: PYTEST_THEME_MODE
1169
1170 Sets the :envvar:`PYTEST_THEME` to be either *dark* or *light*.
1171
1172 .. envvar:: PY_COLORS
1173
1174 When set to ``1``, pytest will use color in terminal output.
1175 When set to ``0``, pytest will not use color.
1176 ``PY_COLORS`` takes precedence over ``NO_COLOR`` and ``FORCE_COLOR``.
1177
1178 .. envvar:: NO_COLOR
1179
1180 When set to a non-empty string (regardless of value), pytest will not use color in terminal output.
1181 ``PY_COLORS`` takes precedence over ``NO_COLOR``, which takes precedence over ``FORCE_COLOR``.
1182 See `no-color.org <https://no-color.org/>`__ for other libraries supporting this community standard.
1183
1184 .. envvar:: FORCE_COLOR
1185
1186 When set to a non-empty string (regardless of value), pytest will use color in terminal output.
1187 ``PY_COLORS`` and ``NO_COLOR`` take precedence over ``FORCE_COLOR``.
1188
1189 Exceptions
1190 ----------
1191
1192 .. autoexception:: pytest.UsageError()
1193 :show-inheritance:
1194
1195 .. autoexception:: pytest.FixtureLookupError()
1196 :show-inheritance:
1197
1198 .. _`warnings ref`:
1199
1200 Warnings
1201 --------
1202
1203 Custom warnings generated in some situations such as improper usage or deprecated features.
1204
1205 .. autoclass:: pytest.PytestWarning
1206 :show-inheritance:
1207
1208 .. autoclass:: pytest.PytestAssertRewriteWarning
1209 :show-inheritance:
1210
1211 .. autoclass:: pytest.PytestCacheWarning
1212 :show-inheritance:
1213
1214 .. autoclass:: pytest.PytestCollectionWarning
1215 :show-inheritance:
1216
1217 .. autoclass:: pytest.PytestConfigWarning
1218 :show-inheritance:
1219
1220 .. autoclass:: pytest.PytestDeprecationWarning
1221 :show-inheritance:
1222
1223 .. autoclass:: pytest.PytestExperimentalApiWarning
1224 :show-inheritance:
1225
1226 .. autoclass:: pytest.PytestReturnNotNoneWarning
1227 :show-inheritance:
1228
1229 .. autoclass:: pytest.PytestRemovedIn9Warning
1230 :show-inheritance:
1231
1232 .. autoclass:: pytest.PytestUnhandledCoroutineWarning
1233 :show-inheritance:
1234
1235 .. autoclass:: pytest.PytestUnknownMarkWarning
1236 :show-inheritance:
1237
1238 .. autoclass:: pytest.PytestUnraisableExceptionWarning
1239 :show-inheritance:
1240
1241 .. autoclass:: pytest.PytestUnhandledThreadExceptionWarning
1242 :show-inheritance:
1243
1244
1245 Consult the :ref:`internal-warnings` section in the documentation for more information.
1246
1247
1248 .. _`ini options ref`:
1249
1250 Configuration Options
1251 ---------------------
1252
1253 Here is a list of builtin configuration options that may be written in a ``pytest.ini`` (or ``.pytest.ini``),
1254 ``pyproject.toml``, ``tox.ini``, or ``setup.cfg`` file, usually located at the root of your repository.
1255
1256 To see each file format in details, see :ref:`config file formats`.
1257
1258 .. warning::
1259 Usage of ``setup.cfg`` is not recommended except for very simple use cases. ``.cfg``
1260 files use a different parser than ``pytest.ini`` and ``tox.ini`` which might cause hard to track
1261 down problems.
1262 When possible, it is recommended to use the latter files, or ``pyproject.toml``, to hold your pytest configuration.
1263
1264 Configuration options may be overwritten in the command-line by using ``-o/--override-ini``, which can also be
1265 passed multiple times. The expected format is ``name=value``. For example::
1266
1267 pytest -o console_output_style=classic -o cache_dir=/tmp/mycache
1268
1269
1270 .. confval:: addopts
1271
1272 Add the specified ``OPTS`` to the set of command line arguments as if they
1273 had been specified by the user. Example: if you have this ini file content:
1274
1275 .. code-block:: ini
1276
1277 # content of pytest.ini
1278 [pytest]
1279 addopts = --maxfail=2 -rf # exit after 2 failures, report fail info
1280
1281 issuing ``pytest test_hello.py`` actually means:
1282
1283 .. code-block:: bash
1284
1285 pytest --maxfail=2 -rf test_hello.py
1286
1287 Default is to add no options.
1288
1289
1290 .. confval:: cache_dir
1291
1292 Sets a directory where stores content of cache plugin. Default directory is
1293 ``.pytest_cache`` which is created in :ref:`rootdir <rootdir>`. Directory may be
1294 relative or absolute path. If setting relative path, then directory is created
1295 relative to :ref:`rootdir <rootdir>`. Additionally path may contain environment
1296 variables, that will be expanded. For more information about cache plugin
1297 please refer to :ref:`cache_provider`.
1298
1299 .. confval:: consider_namespace_packages
1300
1301 Controls if pytest should attempt to identify `namespace packages <https://packaging.python.org/en/latest/guides/packaging-namespace-packages>`__
1302 when collecting Python modules. Default is ``False``.
1303
1304 Set to ``True`` if the package you are testing is part of a namespace package.
1305
1306 Only `native namespace packages <https://packaging.python.org/en/latest/guides/packaging-namespace-packages/#native-namespace-packages>`__
1307 are supported, with no plans to support `legacy namespace packages <https://packaging.python.org/en/latest/guides/packaging-namespace-packages/#legacy-namespace-packages>`__.
1308
1309 .. versionadded:: 8.1
1310
1311 .. confval:: console_output_style
1312
1313 Sets the console output style while running tests:
1314
1315 * ``classic``: classic pytest output.
1316 * ``progress``: like classic pytest output, but with a progress indicator.
1317 * ``progress-even-when-capture-no``: allows the use of the progress indicator even when ``capture=no``.
1318 * ``count``: like progress, but shows progress as the number of tests completed instead of a percent.
1319
1320 The default is ``progress``, but you can fallback to ``classic`` if you prefer or
1321 the new mode is causing unexpected problems:
1322
1323 .. code-block:: ini
1324
1325 # content of pytest.ini
1326 [pytest]
1327 console_output_style = classic
1328
1329
1330 .. confval:: doctest_encoding
1331
1332
1333
1334 Default encoding to use to decode text files with docstrings.
1335 :ref:`See how pytest handles doctests <doctest>`.
1336
1337
1338 .. confval:: doctest_optionflags
1339
1340 One or more doctest flag names from the standard ``doctest`` module.
1341 :ref:`See how pytest handles doctests <doctest>`.
1342
1343
1344 .. confval:: empty_parameter_set_mark
1345
1346
1347
1348 Allows to pick the action for empty parametersets in parameterization
1349
1350 * ``skip`` skips tests with an empty parameterset (default)
1351 * ``xfail`` marks tests with an empty parameterset as xfail(run=False)
1352 * ``fail_at_collect`` raises an exception if parametrize collects an empty parameter set
1353
1354 .. code-block:: ini
1355
1356 # content of pytest.ini
1357 [pytest]
1358 empty_parameter_set_mark = xfail
1359
1360 .. note::
1361
1362 The default value of this option is planned to change to ``xfail`` in future releases
1363 as this is considered less error prone, see :issue:`3155` for more details.
1364
1365
1366 .. confval:: faulthandler_timeout
1367
1368 Dumps the tracebacks of all threads if a test takes longer than ``X`` seconds to run (including
1369 fixture setup and teardown). Implemented using the :func:`faulthandler.dump_traceback_later` function,
1370 so all caveats there apply.
1371
1372 .. code-block:: ini
1373
1374 # content of pytest.ini
1375 [pytest]
1376 faulthandler_timeout=5
1377
1378 For more information please refer to :ref:`faulthandler`.
1379
1380 .. confval:: filterwarnings
1381
1382
1383
1384 Sets a list of filters and actions that should be taken for matched
1385 warnings. By default all warnings emitted during the test session
1386 will be displayed in a summary at the end of the test session.
1387
1388 .. code-block:: ini
1389
1390 # content of pytest.ini
1391 [pytest]
1392 filterwarnings =
1393 error
1394 ignore::DeprecationWarning
1395
1396 This tells pytest to ignore deprecation warnings and turn all other warnings
1397 into errors. For more information please refer to :ref:`warnings`.
1398
1399
1400 .. confval:: junit_duration_report
1401
1402 .. versionadded:: 4.1
1403
1404 Configures how durations are recorded into the JUnit XML report:
1405
1406 * ``total`` (the default): duration times reported include setup, call, and teardown times.
1407 * ``call``: duration times reported include only call times, excluding setup and teardown.
1408
1409 .. code-block:: ini
1410
1411 [pytest]
1412 junit_duration_report = call
1413
1414
1415 .. confval:: junit_family
1416
1417 .. versionadded:: 4.2
1418 .. versionchanged:: 6.1
1419 Default changed to ``xunit2``.
1420
1421 Configures the format of the generated JUnit XML file. The possible options are:
1422
1423 * ``xunit1`` (or ``legacy``): produces old style output, compatible with the xunit 1.0 format.
1424 * ``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. **This is the default**.
1425
1426 .. code-block:: ini
1427
1428 [pytest]
1429 junit_family = xunit2
1430
1431
1432 .. confval:: junit_logging
1433
1434 .. versionadded:: 3.5
1435 .. versionchanged:: 5.4
1436 ``log``, ``all``, ``out-err`` options added.
1437
1438 Configures if captured output should be written to the JUnit XML file. Valid values are:
1439
1440 * ``log``: write only ``logging`` captured output.
1441 * ``system-out``: write captured ``stdout`` contents.
1442 * ``system-err``: write captured ``stderr`` contents.
1443 * ``out-err``: write both captured ``stdout`` and ``stderr`` contents.
1444 * ``all``: write captured ``logging``, ``stdout`` and ``stderr`` contents.
1445 * ``no`` (the default): no captured output is written.
1446
1447 .. code-block:: ini
1448
1449 [pytest]
1450 junit_logging = system-out
1451
1452
1453 .. confval:: junit_log_passing_tests
1454
1455 .. versionadded:: 4.6
1456
1457 If ``junit_logging != "no"``, configures if the captured output should be written
1458 to the JUnit XML file for **passing** tests. Default is ``True``.
1459
1460 .. code-block:: ini
1461
1462 [pytest]
1463 junit_log_passing_tests = False
1464
1465
1466 .. confval:: junit_suite_name
1467
1468 To set the name of the root test suite xml item, you can configure the ``junit_suite_name`` option in your config file:
1469
1470 .. code-block:: ini
1471
1472 [pytest]
1473 junit_suite_name = my_suite
1474
1475 .. confval:: log_auto_indent
1476
1477 Allow selective auto-indentation of multiline log messages.
1478
1479 Supports command line option ``--log-auto-indent [value]``
1480 and config option ``log_auto_indent = [value]`` to set the
1481 auto-indentation behavior for all logging.
1482
1483 ``[value]`` can be:
1484 * True or "On" - Dynamically auto-indent multiline log messages
1485 * False or "Off" or 0 - Do not auto-indent multiline log messages (the default behavior)
1486 * [positive integer] - auto-indent multiline log messages by [value] spaces
1487
1488 .. code-block:: ini
1489
1490 [pytest]
1491 log_auto_indent = False
1492
1493 Supports passing kwarg ``extra={"auto_indent": [value]}`` to
1494 calls to ``logging.log()`` to specify auto-indentation behavior for
1495 a specific entry in the log. ``extra`` kwarg overrides the value specified
1496 on the command line or in the config.
1497
1498 .. confval:: log_cli
1499
1500 Enable log display during test run (also known as :ref:`"live logging" <live_logs>`).
1501 The default is ``False``.
1502
1503 .. code-block:: ini
1504
1505 [pytest]
1506 log_cli = True
1507
1508 .. confval:: log_cli_date_format
1509
1510
1511
1512 Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for live logging.
1513
1514 .. code-block:: ini
1515
1516 [pytest]
1517 log_cli_date_format = %Y-%m-%d %H:%M:%S
1518
1519 For more information, see :ref:`live_logs`.
1520
1521 .. confval:: log_cli_format
1522
1523
1524
1525 Sets a :py:mod:`logging`-compatible string used to format live logging messages.
1526
1527 .. code-block:: ini
1528
1529 [pytest]
1530 log_cli_format = %(asctime)s %(levelname)s %(message)s
1531
1532 For more information, see :ref:`live_logs`.
1533
1534
1535 .. confval:: log_cli_level
1536
1537
1538
1539 Sets the minimum log message level that should be captured for live logging. The integer value or
1540 the names of the levels can be used.
1541
1542 .. code-block:: ini
1543
1544 [pytest]
1545 log_cli_level = INFO
1546
1547 For more information, see :ref:`live_logs`.
1548
1549
1550 .. confval:: log_date_format
1551
1552
1553
1554 Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for logging capture.
1555
1556 .. code-block:: ini
1557
1558 [pytest]
1559 log_date_format = %Y-%m-%d %H:%M:%S
1560
1561 For more information, see :ref:`logging`.
1562
1563
1564 .. confval:: log_file
1565
1566
1567
1568 Sets a file name relative to the current working directory where log messages should be written to, in addition
1569 to the other logging facilities that are active.
1570
1571 .. code-block:: ini
1572
1573 [pytest]
1574 log_file = logs/pytest-logs.txt
1575
1576 For more information, see :ref:`logging`.
1577
1578
1579 .. confval:: log_file_date_format
1580
1581
1582
1583 Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for the logging file.
1584
1585 .. code-block:: ini
1586
1587 [pytest]
1588 log_file_date_format = %Y-%m-%d %H:%M:%S
1589
1590 For more information, see :ref:`logging`.
1591
1592 .. confval:: log_file_format
1593
1594
1595
1596 Sets a :py:mod:`logging`-compatible string used to format logging messages redirected to the logging file.
1597
1598 .. code-block:: ini
1599
1600 [pytest]
1601 log_file_format = %(asctime)s %(levelname)s %(message)s
1602
1603 For more information, see :ref:`logging`.
1604
1605 .. confval:: log_file_level
1606
1607
1608
1609 Sets the minimum log message level that should be captured for the logging file. The integer value or
1610 the names of the levels can be used.
1611
1612 .. code-block:: ini
1613
1614 [pytest]
1615 log_file_level = INFO
1616
1617 For more information, see :ref:`logging`.
1618
1619
1620 .. confval:: log_format
1621
1622
1623
1624 Sets a :py:mod:`logging`-compatible string used to format captured logging messages.
1625
1626 .. code-block:: ini
1627
1628 [pytest]
1629 log_format = %(asctime)s %(levelname)s %(message)s
1630
1631 For more information, see :ref:`logging`.
1632
1633
1634 .. confval:: log_level
1635
1636
1637
1638 Sets the minimum log message level that should be captured for logging capture. The integer value or
1639 the names of the levels can be used.
1640
1641 .. code-block:: ini
1642
1643 [pytest]
1644 log_level = INFO
1645
1646 For more information, see :ref:`logging`.
1647
1648
1649 .. confval:: markers
1650
1651 When the ``--strict-markers`` or ``--strict`` command-line arguments are used,
1652 only known markers - defined in code by core pytest or some plugin - are allowed.
1653
1654 You can list additional markers in this setting to add them to the whitelist,
1655 in which case you probably want to add ``--strict-markers`` to ``addopts``
1656 to avoid future regressions:
1657
1658 .. code-block:: ini
1659
1660 [pytest]
1661 addopts = --strict-markers
1662 markers =
1663 slow
1664 serial
1665
1666 .. note::
1667 The use of ``--strict-markers`` is highly preferred. ``--strict`` was kept for
1668 backward compatibility only and may be confusing for others as it only applies to
1669 markers and not to other options.
1670
1671 .. confval:: minversion
1672
1673 Specifies a minimal pytest version required for running tests.
1674
1675 .. code-block:: ini
1676
1677 # content of pytest.ini
1678 [pytest]
1679 minversion = 3.0 # will fail if we run with pytest-2.8
1680
1681
1682 .. confval:: norecursedirs
1683
1684 Set the directory basename patterns to avoid when recursing
1685 for test discovery. The individual (fnmatch-style) patterns are
1686 applied to the basename of a directory to decide if to recurse into it.
1687 Pattern matching characters::
1688
1689 * matches everything
1690 ? matches any single character
1691 [seq] matches any character in seq
1692 [!seq] matches any char not in seq
1693
1694 Default patterns are ``'*.egg'``, ``'.*'``, ``'_darcs'``, ``'build'``,
1695 ``'CVS'``, ``'dist'``, ``'node_modules'``, ``'venv'``, ``'{arch}'``.
1696 Setting a ``norecursedirs`` replaces the default. Here is an example of
1697 how to avoid certain directories:
1698
1699 .. code-block:: ini
1700
1701 [pytest]
1702 norecursedirs = .svn _build tmp*
1703
1704 This would tell ``pytest`` to not look into typical subversion or
1705 sphinx-build directories or into any ``tmp`` prefixed directory.
1706
1707 Additionally, ``pytest`` will attempt to intelligently identify and ignore a
1708 virtualenv by the presence of an activation script. Any directory deemed to
1709 be the root of a virtual environment will not be considered during test
1710 collection unless ``--collect-in-virtualenv`` is given. Note also that
1711 ``norecursedirs`` takes precedence over ``--collect-in-virtualenv``; e.g. if
1712 you intend to run tests in a virtualenv with a base directory that matches
1713 ``'.*'`` you *must* override ``norecursedirs`` in addition to using the
1714 ``--collect-in-virtualenv`` flag.
1715
1716
1717 .. confval:: python_classes
1718
1719 One or more name prefixes or glob-style patterns determining which classes
1720 are considered for test collection. Search for multiple glob patterns by
1721 adding a space between patterns. By default, pytest will consider any
1722 class prefixed with ``Test`` as a test collection. Here is an example of how
1723 to collect tests from classes that end in ``Suite``:
1724
1725 .. code-block:: ini
1726
1727 [pytest]
1728 python_classes = *Suite
1729
1730 Note that ``unittest.TestCase`` derived classes are always collected
1731 regardless of this option, as ``unittest``'s own collection framework is used
1732 to collect those tests.
1733
1734
1735 .. confval:: python_files
1736
1737 One or more Glob-style file patterns determining which python files
1738 are considered as test modules. Search for multiple glob patterns by
1739 adding a space between patterns:
1740
1741 .. code-block:: ini
1742
1743 [pytest]
1744 python_files = test_*.py check_*.py example_*.py
1745
1746 Or one per line:
1747
1748 .. code-block:: ini
1749
1750 [pytest]
1751 python_files =
1752 test_*.py
1753 check_*.py
1754 example_*.py
1755
1756 By default, files matching ``test_*.py`` and ``*_test.py`` will be considered
1757 test modules.
1758
1759
1760 .. confval:: python_functions
1761
1762 One or more name prefixes or glob-patterns determining which test functions
1763 and methods are considered tests. Search for multiple glob patterns by
1764 adding a space between patterns. By default, pytest will consider any
1765 function prefixed with ``test`` as a test. Here is an example of how
1766 to collect test functions and methods that end in ``_test``:
1767
1768 .. code-block:: ini
1769
1770 [pytest]
1771 python_functions = *_test
1772
1773 Note that this has no effect on methods that live on a ``unittest.TestCase``
1774 derived class, as ``unittest``'s own collection framework is used
1775 to collect those tests.
1776
1777 See :ref:`change naming conventions` for more detailed examples.
1778
1779
1780 .. confval:: pythonpath
1781
1782 Sets list of directories that should be added to the python search path.
1783 Directories will be added to the head of :data:`sys.path`.
1784 Similar to the :envvar:`PYTHONPATH` environment variable, the directories will be
1785 included in where Python will look for imported modules.
1786 Paths are relative to the :ref:`rootdir <rootdir>` directory.
1787 Directories remain in path for the duration of the test session.
1788
1789 .. code-block:: ini
1790
1791 [pytest]
1792 pythonpath = src1 src2
1793
1794 .. note::
1795
1796 ``pythonpath`` does not affect some imports that happen very early,
1797 most notably plugins loaded using the ``-p`` command line option.
1798
1799
1800 .. confval:: required_plugins
1801
1802 A space separated list of plugins that must be present for pytest to run.
1803 Plugins can be listed with or without version specifiers directly following
1804 their name. Whitespace between different version specifiers is not allowed.
1805 If any one of the plugins is not found, emit an error.
1806
1807 .. code-block:: ini
1808
1809 [pytest]
1810 required_plugins = pytest-django>=3.0.0,<4.0.0 pytest-html pytest-xdist>=1.0.0
1811
1812
1813 .. confval:: testpaths
1814
1815 Sets list of directories that should be searched for tests when
1816 no specific directories, files or test ids are given in the command line when
1817 executing pytest from the :ref:`rootdir <rootdir>` directory.
1818 File system paths may use shell-style wildcards, including the recursive
1819 ``**`` pattern.
1820
1821 Useful when all project tests are in a known location to speed up
1822 test collection and to avoid picking up undesired tests by accident.
1823
1824 .. code-block:: ini
1825
1826 [pytest]
1827 testpaths = testing doc
1828
1829 This configuration means that executing:
1830
1831 .. code-block:: console
1832
1833 pytest
1834
1835 has the same practical effects as executing:
1836
1837 .. code-block:: console
1838
1839 pytest testing doc
1840
1841
1842 .. confval:: tmp_path_retention_count
1843
1844
1845
1846 How many sessions should we keep the `tmp_path` directories,
1847 according to `tmp_path_retention_policy`.
1848
1849 .. code-block:: ini
1850
1851 [pytest]
1852 tmp_path_retention_count = 3
1853
1854 Default: ``3``
1855
1856
1857 .. confval:: tmp_path_retention_policy
1858
1859
1860
1861 Controls which directories created by the `tmp_path` fixture are kept around,
1862 based on test outcome.
1863
1864 * `all`: retains directories for all tests, regardless of the outcome.
1865 * `failed`: retains directories only for tests with outcome `error` or `failed`.
1866 * `none`: directories are always removed after each test ends, regardless of the outcome.
1867
1868 .. code-block:: ini
1869
1870 [pytest]
1871 tmp_path_retention_policy = "all"
1872
1873 Default: ``all``
1874
1875
1876 .. confval:: usefixtures
1877
1878 List of fixtures that will be applied to all test functions; this is semantically the same to apply
1879 the ``@pytest.mark.usefixtures`` marker to all test functions.
1880
1881
1882 .. code-block:: ini
1883
1884 [pytest]
1885 usefixtures =
1886 clean_db
1887
1888
1889 .. confval:: verbosity_assertions
1890
1891 Set a verbosity level specifically for assertion related output, overriding the application wide level.
1892
1893 .. code-block:: ini
1894
1895 [pytest]
1896 verbosity_assertions = 2
1897
1898 Defaults to application wide verbosity level (via the ``-v`` command-line option). A special value of
1899 "auto" can be used to explicitly use the global verbosity level.
1900
1901
1902 .. confval:: verbosity_test_cases
1903
1904 Set a verbosity level specifically for test case execution related output, overriding the application wide level.
1905
1906 .. code-block:: ini
1907
1908 [pytest]
1909 verbosity_test_cases = 2
1910
1911 Defaults to application wide verbosity level (via the ``-v`` command-line option). A special value of
1912 "auto" can be used to explicitly use the global verbosity level.
1913
1914
1915 .. confval:: xfail_strict
1916
1917 If set to ``True``, tests marked with ``@pytest.mark.xfail`` that actually succeed will by default fail the
1918 test suite.
1919 For more information, see :ref:`xfail strict tutorial`.
1920
1921
1922 .. code-block:: ini
1923
1924 [pytest]
1925 xfail_strict = True
1926
1927
1928 .. _`command-line-flags`:
1929
1930 Command-line Flags
1931 ------------------
1932
1933 All the command-line flags can be obtained by running ``pytest --help``::
1934
1935 $ pytest --help
1936 usage: pytest [options] [file_or_dir] [file_or_dir] [...]
1937
1938 positional arguments:
1939 file_or_dir
1940
1941 general:
1942 -k EXPRESSION Only run tests which match the given substring
1943 expression. An expression is a Python evaluable
1944 expression where all names are substring-matched
1945 against test names and their parent classes.
1946 Example: -k 'test_method or test_other' matches all
1947 test functions and classes whose name contains
1948 'test_method' or 'test_other', while -k 'not
1949 test_method' matches those that don't contain
1950 'test_method' in their names. -k 'not test_method
1951 and not test_other' will eliminate the matches.
1952 Additionally keywords are matched to classes and
1953 functions containing extra names in their
1954 'extra_keyword_matches' set, as well as functions
1955 which have names assigned directly to them. The
1956 matching is case-insensitive.
1957 -m MARKEXPR Only run tests matching given mark expression. For
1958 example: -m 'mark1 and not mark2'.
1959 --markers show markers (builtin, plugin and per-project ones).
1960 -x, --exitfirst Exit instantly on first error or failed test
1961 --fixtures, --funcargs
1962 Show available fixtures, sorted by plugin appearance
1963 (fixtures with leading '_' are only shown with '-v')
1964 --fixtures-per-test Show fixtures per test
1965 --pdb Start the interactive Python debugger on errors or
1966 KeyboardInterrupt
1967 --pdbcls=modulename:classname
1968 Specify a custom interactive Python debugger for use
1969 with --pdb.For example:
1970 --pdbcls=IPython.terminal.debugger:TerminalPdb
1971 --trace Immediately break when running each test
1972 --capture=method Per-test capturing method: one of fd|sys|no|tee-sys
1973 -s Shortcut for --capture=no
1974 --runxfail Report the results of xfail tests as if they were
1975 not marked
1976 --lf, --last-failed Rerun only the tests that failed at the last run (or
1977 all if none failed)
1978 --ff, --failed-first Run all tests, but run the last failures first. This
1979 may re-order tests and thus lead to repeated fixture
1980 setup/teardown.
1981 --nf, --new-first Run tests from new files first, then the rest of the
1982 tests sorted by file mtime
1983 --cache-show=[CACHESHOW]
1984 Show cache contents, don't perform collection or
1985 tests. Optional argument: glob (default: '*').
1986 --cache-clear Remove all cache contents at start of test run
1987 --lfnf={all,none}, --last-failed-no-failures={all,none}
1988 With ``--lf``, determines whether to execute tests
1989 when there are no previously (known) failures or
1990 when no cached ``lastfailed`` data was found.
1991 ``all`` (the default) runs the full test suite
1992 again. ``none`` just emits a message about no known
1993 failures and exits successfully.
1994 --sw, --stepwise Exit on test failure and continue from last failing
1995 test next time
1996 --sw-skip, --stepwise-skip
1997 Ignore the first failing test but stop on the next
1998 failing test. Implicitly enables --stepwise.
1999
2000 Reporting:
2001 --durations=N Show N slowest setup/test durations (N=0 for all)
2002 --durations-min=N Minimal duration in seconds for inclusion in slowest
2003 list. Default: 0.005.
2004 -v, --verbose Increase verbosity
2005 --no-header Disable header
2006 --no-summary Disable summary
2007 -q, --quiet Decrease verbosity
2008 --verbosity=VERBOSE Set verbosity. Default: 0.
2009 -r chars Show extra test summary info as specified by chars:
2010 (f)ailed, (E)rror, (s)kipped, (x)failed, (X)passed,
2011 (p)assed, (P)assed with output, (a)ll except passed
2012 (p/P), or (A)ll. (w)arnings are enabled by default
2013 (see --disable-warnings), 'N' can be used to reset
2014 the list. (default: 'fE').
2015 --disable-warnings, --disable-pytest-warnings
2016 Disable warnings summary
2017 -l, --showlocals Show locals in tracebacks (disabled by default)
2018 --no-showlocals Hide locals in tracebacks (negate --showlocals
2019 passed through addopts)
2020 --tb=style Traceback print mode
2021 (auto/long/short/line/native/no)
2022 --show-capture={no,stdout,stderr,log,all}
2023 Controls how captured stdout/stderr/log is shown on
2024 failed tests. Default: all.
2025 --full-trace Don't cut any tracebacks (default is to cut)
2026 --color=color Color terminal output (yes/no/auto)
2027 --code-highlight={yes,no}
2028 Whether code should be highlighted (only if --color
2029 is also enabled). Default: yes.
2030 --pastebin=mode Send failed|all info to bpaste.net pastebin service
2031 --junit-xml=path Create junit-xml style report file at given path
2032 --junit-prefix=str Prepend prefix to classnames in junit-xml output
2033
2034 pytest-warnings:
2035 -W PYTHONWARNINGS, --pythonwarnings=PYTHONWARNINGS
2036 Set which warnings to report, see -W option of
2037 Python itself
2038 --maxfail=num Exit after first num failures or errors
2039 --strict-config Any warnings encountered while parsing the `pytest`
2040 section of the configuration file raise errors
2041 --strict-markers Markers not registered in the `markers` section of
2042 the configuration file raise errors
2043 --strict (Deprecated) alias to --strict-markers
2044 -c FILE, --config-file=FILE
2045 Load configuration from `FILE` instead of trying to
2046 locate one of the implicit configuration files.
2047 --continue-on-collection-errors
2048 Force test execution even if collection errors occur
2049 --rootdir=ROOTDIR Define root directory for tests. Can be relative
2050 path: 'root_dir', './root_dir',
2051 'root_dir/another_dir/'; absolute path:
2052 '/home/user/root_dir'; path with variables:
2053 '$HOME/root_dir'.
2054
2055 collection:
2056 --collect-only, --co Only collect tests, don't execute them
2057 --pyargs Try to interpret all arguments as Python packages
2058 --ignore=path Ignore path during collection (multi-allowed)
2059 --ignore-glob=path Ignore path pattern during collection (multi-
2060 allowed)
2061 --deselect=nodeid_prefix
2062 Deselect item (via node id prefix) during collection
2063 (multi-allowed)
2064 --confcutdir=dir Only load conftest.py's relative to specified dir
2065 --noconftest Don't load any conftest.py files
2066 --keep-duplicates Keep duplicate tests
2067 --collect-in-virtualenv
2068 Don't ignore tests in a local virtualenv directory
2069 --import-mode={prepend,append,importlib}
2070 Prepend/append to sys.path when importing test
2071 modules and conftest files. Default: prepend.
2072 --doctest-modules Run doctests in all .py modules
2073 --doctest-report={none,cdiff,ndiff,udiff,only_first_failure}
2074 Choose another output format for diffs on doctest
2075 failure
2076 --doctest-glob=pat Doctests file matching pattern, default: test*.txt
2077 --doctest-ignore-import-errors
2078 Ignore doctest collection errors
2079 --doctest-continue-on-failure
2080 For a given doctest, continue to run after the first
2081 failure
2082
2083 test session debugging and configuration:
2084 --basetemp=dir Base temporary directory for this test run.
2085 (Warning: this directory is removed if it exists.)
2086 -V, --version Display pytest version and information about
2087 plugins. When given twice, also display information
2088 about plugins.
2089 -h, --help Show help message and configuration info
2090 -p name Early-load given plugin module name or entry point
2091 (multi-allowed). To avoid loading of plugins, use
2092 the `no:` prefix, e.g. `no:doctest`.
2093 --trace-config Trace considerations of conftest.py files
2094 --debug=[DEBUG_FILE_NAME]
2095 Store internal tracing debug information in this log
2096 file. This file is opened with 'w' and truncated as
2097 a result, care advised. Default: pytestdebug.log.
2098 -o OVERRIDE_INI, --override-ini=OVERRIDE_INI
2099 Override ini option with "option=value" style, e.g.
2100 `-o xfail_strict=True -o cache_dir=cache`.
2101 --assert=MODE Control assertion debugging tools.
2102 'plain' performs no assertion debugging.
2103 'rewrite' (the default) rewrites assert statements
2104 in test modules on import to provide assert
2105 expression information.
2106 --setup-only Only setup fixtures, do not execute tests
2107 --setup-show Show setup of fixtures while executing tests
2108 --setup-plan Show what fixtures and tests would be executed but
2109 don't execute anything
2110
2111 logging:
2112 --log-level=LEVEL Level of messages to catch/display. Not set by
2113 default, so it depends on the root/parent log
2114 handler's effective level, where it is "WARNING" by
2115 default.
2116 --log-format=LOG_FORMAT
2117 Log format used by the logging module
2118 --log-date-format=LOG_DATE_FORMAT
2119 Log date format used by the logging module
2120 --log-cli-level=LOG_CLI_LEVEL
2121 CLI logging level
2122 --log-cli-format=LOG_CLI_FORMAT
2123 Log format used by the logging module
2124 --log-cli-date-format=LOG_CLI_DATE_FORMAT
2125 Log date format used by the logging module
2126 --log-file=LOG_FILE Path to a file when logging will be written to
2127 --log-file-mode={w,a}
2128 Log file open mode
2129 --log-file-level=LOG_FILE_LEVEL
2130 Log file logging level
2131 --log-file-format=LOG_FILE_FORMAT
2132 Log format used by the logging module
2133 --log-file-date-format=LOG_FILE_DATE_FORMAT
2134 Log date format used by the logging module
2135 --log-auto-indent=LOG_AUTO_INDENT
2136 Auto-indent multiline messages passed to the logging
2137 module. Accepts true|on, false|off or an integer.
2138 --log-disable=LOGGER_DISABLE
2139 Disable a logger by name. Can be passed multiple
2140 times.
2141
2142 [pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:
2143
2144 markers (linelist): Register new markers for test functions
2145 empty_parameter_set_mark (string):
2146 Default marker for empty parametersets
2147 norecursedirs (args): Directory patterns to avoid for recursion
2148 testpaths (args): Directories to search for tests when no files or
2149 directories are given on the command line
2150 filterwarnings (linelist):
2151 Each line specifies a pattern for
2152 warnings.filterwarnings. Processed after
2153 -W/--pythonwarnings.
2154 consider_namespace_packages (bool):
2155 Consider namespace packages when resolving module
2156 names during import
2157 usefixtures (args): List of default fixtures to be used with this
2158 project
2159 python_files (args): Glob-style file patterns for Python test module
2160 discovery
2161 python_classes (args):
2162 Prefixes or glob names for Python test class
2163 discovery
2164 python_functions (args):
2165 Prefixes or glob names for Python test function and
2166 method discovery
2167 disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):
2168 Disable string escape non-ASCII characters, might
2169 cause unwanted side effects(use at your own risk)
2170 console_output_style (string):
2171 Console output: "classic", or with additional
2172 progress information ("progress" (percentage) |
2173 "count" | "progress-even-when-capture-no" (forces
2174 progress even when capture=no)
2175 verbosity_test_cases (string):
2176 Specify a verbosity level for test case execution,
2177 overriding the main level. Higher levels will
2178 provide more detailed information about each test
2179 case executed.
2180 xfail_strict (bool): Default for the strict parameter of xfail markers
2181 when not given explicitly (default: False)
2182 tmp_path_retention_count (string):
2183 How many sessions should we keep the `tmp_path`
2184 directories, according to
2185 `tmp_path_retention_policy`.
2186 tmp_path_retention_policy (string):
2187 Controls which directories created by the `tmp_path`
2188 fixture are kept around, based on test outcome.
2189 (all/failed/none)
2190 enable_assertion_pass_hook (bool):
2191 Enables the pytest_assertion_pass hook. Make sure to
2192 delete any previously generated pyc cache files.
2193 verbosity_assertions (string):
2194 Specify a verbosity level for assertions, overriding
2195 the main level. Higher levels will provide more
2196 detailed explanation when an assertion fails.
2197 junit_suite_name (string):
2198 Test suite name for JUnit report
2199 junit_logging (string):
2200 Write captured log messages to JUnit report: one of
2201 no|log|system-out|system-err|out-err|all
2202 junit_log_passing_tests (bool):
2203 Capture log information for passing tests to JUnit
2204 report:
2205 junit_duration_report (string):
2206 Duration time to report: one of total|call
2207 junit_family (string):
2208 Emit XML for schema: one of legacy|xunit1|xunit2
2209 doctest_optionflags (args):
2210 Option flags for doctests
2211 doctest_encoding (string):
2212 Encoding used for doctest files
2213 cache_dir (string): Cache directory path
2214 log_level (string): Default value for --log-level
2215 log_format (string): Default value for --log-format
2216 log_date_format (string):
2217 Default value for --log-date-format
2218 log_cli (bool): Enable log display during test run (also known as
2219 "live logging")
2220 log_cli_level (string):
2221 Default value for --log-cli-level
2222 log_cli_format (string):
2223 Default value for --log-cli-format
2224 log_cli_date_format (string):
2225 Default value for --log-cli-date-format
2226 log_file (string): Default value for --log-file
2227 log_file_mode (string):
2228 Default value for --log-file-mode
2229 log_file_level (string):
2230 Default value for --log-file-level
2231 log_file_format (string):
2232 Default value for --log-file-format
2233 log_file_date_format (string):
2234 Default value for --log-file-date-format
2235 log_auto_indent (string):
2236 Default value for --log-auto-indent
2237 pythonpath (paths): Add paths to sys.path
2238 faulthandler_timeout (string):
2239 Dump the traceback of all threads if a test takes
2240 more than TIMEOUT seconds to finish
2241 addopts (args): Extra command line options
2242 minversion (string): Minimally required pytest version
2243 required_plugins (args):
2244 Plugins that must be present for pytest to run
2245
2246 Environment variables:
2247 PYTEST_ADDOPTS Extra command line options
2248 PYTEST_PLUGINS Comma-separated plugins to load during startup
2249 PYTEST_DISABLE_PLUGIN_AUTOLOAD Set to disable plugin auto-loading
2250 PYTEST_DEBUG Set to enable debug tracing of pytest's internals
2251
2252
2253 to see available markers type: pytest --markers
2254 to see available fixtures type: pytest --fixtures
2255 (shown according to specified file_or_dir or current dir if not specified; fixtures with leading '_' are only shown with the '-v' option