Show Menu

pytest usage Cheat Sheet by

A cheatsheet for using pytest


pip install pytest

Running pytest

pytest test_m­
Run tests in module
pytest testing/
Run multiple modules
pytest test_m­­od.p­­y:­­:te­­st­_func
Run a specific test within a module.
pytest test_m­­od.p­­y:­­:Te­­st­C­l­as­­s::­­te­s­t­_m­­ethod
Run a specific method of a class.


pytest allows you to use the standard Python assert for verifying expect­ations and values in Python tests. For example, you can write the following:
assert a % 2 == 0
assert that you have a certain value.
assert a % 2 == 0,
"value was odd, should be even"
specify a message with the assertion like this

Grouping in tests

mark it in tests
pytest tests/ -m "­san­ity­tes­ts"
run using -m flag

Disable tests

reason­="no way of currently testing this")

Assertion of expected exceptions

Test if the exception is raised
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
Test for specific exception info
def test_recursion_depth():
with pytest.ra­ise­s(R­unt­ime­Error) as excinfo:
assert "­max­imu­m" in str(ex­cin­fo.v­alue)


pip install pytest-xdist
pytest tests/ -n 3
Pytest does not run in parallel by default, therefor we need to enable this behaviour through a plugin.


In testing, a fixture provides a defined, reliable and consistent context for the tests. This could include enviro­nment (for example a database configured with known parame­ters) or content (such as a dataset).
def input_value():
input = 10
return input
Create fixture in conftest
def test_divisible_by_3(input_value):
assert input_­value % 3 == 0
Use it in tests
def sending_user(mail_admin):
user = mail_admin.create_user()
yield user
using yield to setup and teardown test enviro­nment
Pytest fixtures have scope. This scope controls how often the fixture is executed or, in other words, how often the setup and teardown of the fixture is performed.

Data parame­ter­ization

The builtin­rk.p­ar­ame­trize decorator enables parame­tri­zation of arguments for a test function
Define parame­trized tests
@pytes­t.m­­ram­etr­ize­("num, output",
def test_m­ult­ipl­ica­tio­n_1­1(num, output):
assert 11*num == output
Running specific tests of a parame­trized test.


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter
          Pytest Cheat Sheet