Usage and Invocations — pytest documentation (2024)

Calling pytest through python -m pytest

You can invoke testing through the Python interpreter from the command line:

python -m pytest [...]

This is almost equivalent to invoking the command line script pytest [...]directly, except that calling via python will also add the current directory to sys.path.

Possible exit codes

Running pytest can result in six different exit codes:

Exit code 0

All tests were collected and passed successfully

Exit code 1

Tests were collected and run but some of the tests failed

Exit code 2

Test execution was interrupted by the user

Exit code 3

Internal error happened while executing tests

Exit code 4

pytest command line usage error

Exit code 5

No tests were collected

They are represented by the pytest.ExitCode enum. The exit codes being a part of the public API can be imported and accessed directly using:

from pytest import ExitCode

Note

If you would like to customize the exit code in some scenarios, specially whenno tests are collected, consider using thepytest-custom_exit_codeplugin.

Getting help on version, option names, environment variables

pytest --version # shows where pytest was imported frompytest --fixtures # show available builtin function argumentspytest -h | --help # show help on command line and config file options

The full command-line flags can be found in the reference.

Stopping after the first (or N) failures

To stop the testing process after the first (N) failures:

pytest -x # stop after first failurepytest --maxfail=2 # stop after two failures

Specifying tests / selecting tests

Pytest supports several ways to run and select tests from the command-line.

Run tests in a module

pytest test_mod.py

Run tests in a directory

pytest testing/

Run tests by keyword expressions

pytest -k "MyClass and not method"

This will run tests which contain names that match the given string expression (case-insensitive),which can include Python operators that use filenames, class names and function names as variables.The example above will run TestMyClass.test_something but not TestMyClass.test_method_simple.

Run tests by node ids

Each collected test is assigned a unique nodeid which consist of the module filename followedby specifiers like class names, function names and parameters from parametrization, separated by :: characters.

To run a specific test within a module:

pytest test_mod.py::test_func

Another example specifying a test method in the command line:

pytest test_mod.py::TestClass::test_method

Run tests by marker expressions

pytest -m slow

Will run all tests which are decorated with the @pytest.mark.slow decorator.

For more information see marks.

Run tests from packages

pytest --pyargs pkg.testing

This will import pkg.testing and use its filesystem location to find and run tests from.

Modifying Python traceback printing

Examples for modifying traceback printing:

pytest --showlocals # show local variables in tracebackspytest -l # show local variables (shortcut)pytest --tb=auto # (default) 'long' tracebacks for the first and last # entry, but 'short' style for the other entriespytest --tb=long # exhaustive, informative traceback formattingpytest --tb=short # shorter traceback formatpytest --tb=line # only one line per failurepytest --tb=native # Python standard library formattingpytest --tb=no # no traceback at all

The --full-trace causes very long traces to be printed on error (longerthan --tb=long). It also ensures that a stack trace is printed onKeyboardInterrupt (Ctrl+C).This is very useful if the tests are taking too long and you interrupt themwith Ctrl+C to find out where the tests are hanging. By default no outputwill be shown (because KeyboardInterrupt is caught by pytest). By using thisoption you make sure a trace is shown.

Detailed summary report

The -r flag can be used to display a “short test summary info” at the end of the test session,making it easy in large test suites to get a clear picture of all failures, skips, xfails, etc.

It defaults to fE to list failures and errors.

Example:

# content of test_example.pyimport pytest@pytest.fixturedef error_fixture(): assert 0def test_ok(): print("ok")def test_fail(): assert 0def test_error(error_fixture): passdef test_skip(): pytest.skip("skipping this test")def test_xfail(): pytest.xfail("xfailing this test")@pytest.mark.xfail(reason="always xfail")def test_xpass(): pass
$ pytest -ra=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-1.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 6 itemstest_example.py .FEsxX [100%]================================== ERRORS ==================================_______________________ ERROR at setup of test_error _______________________ @pytest.fixture def error_fixture():> assert 0E assert 0test_example.py:6: AssertionError================================= FAILURES =================================________________________________ test_fail _________________________________ def test_fail():> assert 0E assert 0test_example.py:14: AssertionError========================= short test summary info ==========================SKIPPED [1] test_example.py:22: skipping this testXFAIL test_example.py::test_xfail reason: xfailing this testXPASS test_example.py::test_xpass always xfailERROR test_example.py::test_error - assert 0FAILED test_example.py::test_fail - assert 0== 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s ===

The -r options accepts a number of characters after it, with a usedabove meaning “all except passes”.

Here is the full list of available characters that can be used:

  • f - failed

  • E - error

  • s - skipped

  • x - xfailed

  • X - xpassed

  • p - passed

  • P - passed with output

Special characters for (de)selection of groups:

  • a - all except pP

  • A - all

  • N - none, this can be used to display nothing (since fE is the default)

More than one character can be used, so for example to only see failed and skipped tests, you can execute:

$ pytest -rfs=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-1.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 6 itemstest_example.py .FEsxX [100%]================================== ERRORS ==================================_______________________ ERROR at setup of test_error _______________________ @pytest.fixture def error_fixture():> assert 0E assert 0test_example.py:6: AssertionError================================= FAILURES =================================________________________________ test_fail _________________________________ def test_fail():> assert 0E assert 0test_example.py:14: AssertionError========================= short test summary info ==========================FAILED test_example.py::test_fail - assert 0SKIPPED [1] test_example.py:22: skipping this test== 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s ===

Using p lists the passing tests, whilst P adds an extra section “PASSES” with those tests that passed but hadcaptured output:

$ pytest -rpP=========================== test session starts ============================platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-1.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_TMPDIRcollected 6 itemstest_example.py .FEsxX [100%]================================== ERRORS ==================================_______________________ ERROR at setup of test_error _______________________ @pytest.fixture def error_fixture():> assert 0E assert 0test_example.py:6: AssertionError================================= FAILURES =================================________________________________ test_fail _________________________________ def test_fail():> assert 0E assert 0test_example.py:14: AssertionError================================== PASSES ==================================_________________________________ test_ok __________________________________--------------------------- Captured stdout call ---------------------------ok========================= short test summary info ==========================PASSED test_example.py::test_ok== 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s ===

Dropping to PDB (Python Debugger) on failures

Python comes with a builtin Python debugger called PDB. pytestallows one to drop into the PDB prompt via a command line option:

pytest --pdb

This will invoke the Python debugger on every failure (or KeyboardInterrupt).Often you might only want to do this for the first failing test to understanda certain failure situation:

pytest -x --pdb # drop to PDB on first failure, then end test sessionpytest --pdb --maxfail=3 # drop to PDB for first three failures

Note that on any failure the exception information is stored onsys.last_value, sys.last_type and sys.last_traceback. Ininteractive use, this allows one to drop into postmortem debugging withany debug tool. One can also manually access the exception information,for example:

>>> import sys>>> sys.last_traceback.tb_lineno42>>> sys.last_valueAssertionError('assert result == "ok"',)

Dropping to PDB (Python Debugger) at the start of a test

pytest allows one to drop into the PDB prompt immediately at the start of each test via a command line option:

pytest --trace

This will invoke the Python debugger at the start of every test.

Setting breakpoints

To set a breakpoint in your code use the native Python import pdb;pdb.set_trace() callin your code and pytest automatically disables its output capture for that test:

  • Output capture in other tests is not affected.

  • Any prior test output that has already been captured and will be processed assuch.

  • Output capture gets resumed when ending the debugger session (via thecontinue command).

Using the builtin breakpoint function

Python 3.7 introduces a builtin breakpoint() function.Pytest supports the use of breakpoint() with the following behaviours:

  • When breakpoint() is called and PYTHONBREAKPOINT is set to the default value, pytest will use the custom internal PDB trace UI instead of the system default Pdb.

  • When tests are complete, the system will default back to the system Pdb trace UI.

  • With --pdb passed to pytest, the custom internal Pdb trace UI is used with both breakpoint() and failed tests/unhandled exceptions.

  • --pdbcls can be used to specify a custom debugger class.

Profiling test execution duration

Changed in version 6.0.

To get a list of the slowest 10 test durations over 1.0s long:

pytest --durations=10 --durations-min=1.0

By default, pytest will not show test durations that are too small (<0.005s) unless -vv is passed on the command-line.

Fault Handler

New in version 5.0.

The faulthandler standard modulecan be used to dump Python tracebacks on a segfault or after a timeout.

The module is automatically enabled for pytest runs, unless the -p no:faulthandler is givenon the command-line.

Also the faulthandler_timeout=X configuration option can be usedto dump the traceback of all threads if a test takes longer than Xseconds to finish (not available on Windows).

Note

This functionality has been integrated from the externalpytest-faulthandler plugin, with twosmall differences:

  • To disable it, use -p no:faulthandler instead of --no-faulthandler: the formercan be used with any plugin, so it saves one option.

  • The --faulthandler-timeout command-line option has become thefaulthandler_timeout configuration option. It can still be configured fromthe command-line using -o faulthandler_timeout=X.

Warning about unraisable exceptions and unhandled thread exceptions

New in version 6.2.

Note

These features only work on Python>=3.8.

Unhandled exceptions are exceptions that are raised in a situation in whichthey cannot propagate to a caller. The most common case is an exception raisedin a __del__ implementation.

Unhandled thread exceptions are exceptions raised in a Threadbut not handled, causing the thread to terminate uncleanly.

Both types of exceptions are normally considered bugs, but may go unnoticedbecause they don’t cause the program itself to crash. Pytest detects theseconditions and issues a warning that is visible in the test run summary.

The plugins are automatically enabled for pytest runs, unless the-p no:unraisableexception (for unraisable exceptions) and-p no:threadexception (for thread exceptions) options are given on thecommand-line.

The warnings may be silenced selectivly using the pytest.mark.filterwarningsmark. The warning categories are pytest.PytestUnraisableExceptionWarning andpytest.PytestUnhandledThreadExceptionWarning.

Creating JUnitXML format files

To create result files which can be read by Jenkins or other Continuousintegration servers, use this invocation:

pytest --junitxml=path

to create an XML file at path.

To set the name of the root test suite xml item, you can configure the junit_suite_name option in your config file:

[pytest]junit_suite_name = my_suite

New in version 4.0.

JUnit XML specification seems to indicate that "time" attributeshould report total test execution times, including setup and teardown(1, 2).It is the default pytest behavior. To report just call durationsinstead, configure the junit_duration_report option like this:

[pytest]junit_duration_report = call

record_property

If you want to log additional information for a test, you can use therecord_property fixture:

def test_function(record_property): record_property("example_key", 1) assert True

This will add an extra property example_key="1" to the generatedtestcase tag:

<testcase classname="test_function" file="test_function.py" line="0" name="test_function" time="0.0009"> <properties> <property name="example_key" value="1" /> </properties></testcase>

Alternatively, you can integrate this functionality with custom markers:

# content of conftest.pydef pytest_collection_modifyitems(session, config, items): for item in items: for marker in item.iter_markers(name="test_id"): test_id = marker.args[0] item.user_properties.append(("test_id", test_id))

And in your tests:

# content of test_function.pyimport pytest@pytest.mark.test_id(1501)def test_function(): assert True

Will result in:

<testcase classname="test_function" file="test_function.py" line="0" name="test_function" time="0.0009"> <properties> <property name="test_id" value="1501" /> </properties></testcase>

Warning

Please note that using this feature will break schema verifications for the latest JUnitXML schema.This might be a problem when used with some CI servers.

record_xml_attribute

To add an additional xml attribute to a testcase element, you can userecord_xml_attribute fixture. This can also be used to override existing values:

def test_function(record_xml_attribute): record_xml_attribute("assertions", "REQ-1234") record_xml_attribute("classname", "custom_classname") print("hello world") assert True

Unlike record_property, this will not add a new child element.Instead, this will add an attribute assertions="REQ-1234" inside the generatedtestcase tag and override the default classname with "classname=custom_classname":

<testcase classname="custom_classname" file="test_function.py" line="0" name="test_function" time="0.003" assertions="REQ-1234"> <system-out> hello world </system-out></testcase>

Warning

record_xml_attribute is an experimental feature, and its interface might be replacedby something more powerful and general in future versions. Thefunctionality per-se will be kept, however.

Using this over record_xml_property can help when using ci tools to parse the xml report.However, some parsers are quite strict about the elements and attributes that are allowed.Many tools use an xsd schema (like the example below) to validate incoming xml.Make sure you are using attribute names that are allowed by your parser.

Below is the Scheme used by Jenkins to validate the XML report:

<xs:element name="testcase"> <xs:complexType> <xs:sequence> <xs:element ref="skipped" minOccurs="0" maxOccurs="1"/> <xs:element ref="error" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="failure" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="system-out" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="system-err" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required"/> <xs:attribute name="assertions" type="xs:string" use="optional"/> <xs:attribute name="time" type="xs:string" use="optional"/> <xs:attribute name="classname" type="xs:string" use="optional"/> <xs:attribute name="status" type="xs:string" use="optional"/> </xs:complexType></xs:element>

Warning

Please note that using this feature will break schema verifications for the latest JUnitXML schema.This might be a problem when used with some CI servers.

record_testsuite_property

New in version 4.5.

If you want to add a properties node at the test-suite level, which may contains propertiesthat are relevant to all tests, you can use the record_testsuite_property session-scoped fixture:

The record_testsuite_property session-scoped fixture can be used to add properties relevantto all tests.

import pytest@pytest.fixture(scope="session", autouse=True)def log_global_env_facts(record_testsuite_property): record_testsuite_property("ARCH", "PPC") record_testsuite_property("STORAGE_TYPE", "CEPH")class TestMe: def test_foo(self): assert True

The fixture is a callable which receives name and value of a <property> tagadded at the test-suite level of the generated xml:

<testsuite errors="0" failures="0" name="pytest" skipped="0" tests="1" time="0.006"> <properties> <property name="ARCH" value="PPC"/> <property name="STORAGE_TYPE" value="CEPH"/> </properties> <testcase classname="test_me.TestMe" file="test_me.py" line="16" name="test_foo" time="0.000243663787842"/></testsuite>

name must be a string, value will be converted to a string and properly xml-escaped.

The generated XML is compatible with the latest xunit standard, contrary to record_propertyand record_xml_attribute.

Creating resultlog format files

To create plain-text machine-readable result files you can issue:

pytest --resultlog=path

and look at the content at the path location. Such files are used e.g.by the PyPy-test web page to show test results over several revisions.

Warning

This option is rarely used and is scheduled for removal in pytest 6.0.

If you use this option, consider using the new pytest-reportlog plugin instead.

See the deprecation docsfor more information.

Sending test report to online pastebin service

Creating a URL for each test failure:

pytest --pastebin=failed

This will submit test run information to a remote Paste service andprovide a URL for each failure. You may select tests as usual or addfor example -x if you only want to send one particular failure.

Creating a URL for a whole test session log:

pytest --pastebin=all

Currently only pasting to the http://bpaste.net service is implemented.

Changed in version 5.2.

If creating the URL fails for any reason, a warning is generated instead of failing theentire test suite.

Early loading plugins

You can early-load plugins (internal and external) explicitly in the command-line with the -p option:

pytest -p mypluginmodule

The option receives a name parameter, which can be:

  • A full module dotted name, for example myproject.plugins. This dotted name must be importable.

  • The entry-point name of a plugin. This is the name passed to setuptools when the plugin isregistered. For example to early-load the pytest-cov plugin you can use:

    pytest -p pytest_cov

Disabling plugins

To disable loading specific plugins at invocation time, use the -p optiontogether with the prefix no:.

Example: to disable loading the plugin doctest, which is responsible forexecuting doctest tests from text files, invoke pytest like this:

pytest -p no:doctest

Calling pytest from Python code

You can invoke pytest from Python code directly:

pytest.main()

this acts as if you would call “pytest” from the command line.It will not raise SystemExit but return the exitcode instead.You can pass in options and arguments:

pytest.main(["-x", "mytestdir"])

You can specify additional plugins to pytest.main:

# content of myinvoke.pyimport pytestclass MyPlugin: def pytest_sessionfinish(self): print("*** test run reporting finishing")pytest.main(["-qq"], plugins=[MyPlugin()])

Running it will show that MyPlugin was added and itshook was invoked:

$ python myinvoke.py.FEsxX. [100%]*** test run reporting finishing================================== ERRORS ==================================_______________________ ERROR at setup of test_error _______________________ @pytest.fixture def error_fixture():> assert 0E assert 0test_example.py:6: AssertionError================================= FAILURES =================================________________________________ test_fail _________________________________ def test_fail():> assert 0E assert 0test_example.py:14: AssertionError========================= short test summary info ==========================FAILED test_example.py::test_fail - assert 0ERROR test_example.py::test_error - assert 0

Note

Calling pytest.main() will result in importing your tests and any modulesthat they import. Due to the caching mechanism of python’s import system,making subsequent calls to pytest.main() from the same process will notreflect changes to those files between the calls. For this reason, makingmultiple calls to pytest.main() from the same process (in order to re-runtests, for example) is not recommended.

Usage and Invocations — pytest documentation (2024)

References

Top Articles
Ithaca Reggae Fest 2023 Lineup - Jun 23 - 24, 2023
Fifth Annual Ithaca Reggae Fest comes to Stewart Park in June - The Ithaca Voice
Trivago Manhattan
Refinery29 Horoscopes
Camping World Of New River
Ink Free News Kosciusko County
Arcanis Secret Santa
Does Shell Gas Station Sell Pregnancy Tests
Craigslist Placer County
The Ultimate Guide To Jelly Bean Brain Leaks: Causes, Symptoms, And Solutions
Lox Club Gift Code
Poochies Liquor Store
Po Box 6726 Portland Or 97228
Lesson 10 Homework 5.3
6Th Gen Camaro Forums
Sound Of Freedom Showtimes Near Sperry's Moviehouse Holland
Binny Arcot
Icue Color Profiles
Liquor World Sharon Ma
Does Publix Sell Sephora Gift Cards
Weather | Livingston Daily Voice
Peoplesoft Oracle Americold Login
Find Words Containing Specific Letters | WordFinder®
Unmhealth My Mysecurebill
Heyimbee Forum
Tackytwinzzbkup
Craigslist Cars And Trucks By Owner Seattle
Kino am Raschplatz - Vorschau
Recharging Iban Staff
Diablo 3 Metascore
Plus Portal Ibn Seena Academy
Con Edison Outage Map Staten Island
Sayre Australian Shepherds
Watch Shark Tank TV Show - ABC.com
Used Cars for Sale in Phoenix, AZ (with Photos)
Diabetes Care - Horizon Blue Cross Blue Shield of New Jersey
North Haven Power School
Ssndob Cm
Dr Seuss Star Bellied Sneetches Pdf
Disney Immersive Experience Cleveland Discount Code
Ekaterina Lisina Wiki
Mybrownhanky Com
Ultimate Guide to Los Alamos, CA: A Small Town Big On Flavor
Carros Jeep Wrangler Tachira | MercadoLibre 📦
The Ultimate Guide To Lovenexy: Exploring Intimacy And Passion
Gunsmoke Noonday Devil Cast
Democrat And Chronicle Obituaries For This Week
Closest Asian Supermarket
Samanthaschwartz Fapello
Imagetrend Elite Delaware
Craigslist Boats Rochester
Latest Posts
Article information

Author: Neely Ledner

Last Updated:

Views: 5508

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Neely Ledner

Birthday: 1998-06-09

Address: 443 Barrows Terrace, New Jodyberg, CO 57462-5329

Phone: +2433516856029

Job: Central Legal Facilitator

Hobby: Backpacking, Jogging, Magic, Driving, Macrame, Embroidery, Foraging

Introduction: My name is Neely Ledner, I am a bright, determined, beautiful, adventurous, adventurous, spotless, calm person who loves writing and wants to share my knowledge and understanding with you.