Skip to content

Instantly share code, notes, and snippets.

Forked from kwmiebach/
Created June 3, 2018 17:42
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
pytest cheat sheet


(Remember to create a symlink pytest for py.test)

pytest [options] [file_or_dir] [file_or_dir] ...


pytest --help|zless

Some options

 -x                    Stop after first failure
 -k "expression"       Only run tests that match expession (and fixtures)
 -s                    Do not capture output

 -v                    Verbose
 -q, --quiet           Less verbose

 -l, --showlocals      Show local variables in tracebacks
 -rs                   Show extra summary info for SKIPPED
 -r chars              Show extra test summary info as specified by chars:
                       (f)ailed, (E)error, (s)skipped, (x)failed, (X)passed
                       (w)pytest-warnings (p)passed, (P)passed with output,
                       (a)all except pP.

Shorter tracebacks, python tracebacks

pytest --tb=short
pytest --tb=line # even shorter

Use the Python standard traceback formatting:

pytest --tb=native

Output capturing

pytest -s # disable all capturing

Print a message after the test

The text is printed always, even in silent mode. See

def report():
  print("""This is printed AFTER the test""")
import atexit

Collect information test suite / dry run

py.test --collect-only  

(will not display fixture code but fixture code will be run always)

Output verbose messages

py.test -v  

Run a single test: specify, like so

py.test -q -s

(fixture code will also run)

Ignore / exclude certain files or directories

--ignore=lib/foo/ --ignore=lib/hello/

Call pytest through python

python -m pytest -q  

Call pytest from python

import pytest
# put all arguments into a string. example:
# another example:
pytest.main("-x mytestdir")
# or pass in a list of arguments:
pytest.main(['-x', 'mytestdir'])

Show available markers

py.test --markers  

Create a reusable marker

content of pytest.ini:

markers =
   webtest: mark a test as a webtest.

Only run tests with names that match the "string expression"

py.test -k "TestClass and not test_one" 

(fixture code will also run)

Only run tests that match the node ID


(fixture code will also run)

Stop after

py.test -x  # stop after first failure

py.test --maxfail=2  # stop after two failures

py.test --maxfail=2 -rf  # exit after 2 failures, report fail info.

Show local variables in tracebacks

py.test --showlocals 
py.test -l  # (shortcut)

py.test --tb=long  # the default informative traceback formatting
py.test --tb=native  # the Python standard library formatting
py.test --tb=short  # a shorter traceback format
py.test --tb=line  # only one line per failure
py.test --tb=no  # no tracebak output

Drop to PDB on first failure

(then end test session)

py.test -x --pdb 

List of the slowest 10 test durations.

py.test --durations=10  

Send tests to multiple CPUs

py.test -n 4  

Run tests with decorator "slowest"

Run tests with decorator @pytest.mark.slowest or slowest = pytest.mark.slowest; @slowest

py.test -m slowest  

Show active plugins

Find out which plugins are active in your environment

py.test --traceconfig  


if pytest-instafail is installed, show errors and failures instantly instead of waiting until the end of test suite:

py.test --instafail  

Expected exceptions



def test_recursion_depth():
    with pytest.raises(RuntimeError) as excinfo:
        def f():
    assert 'maximum recursion' in str(excinfo.value)

More usage examples:

Excinfo is a py.code.ExceptionInfo instance:

Its main attributes are type (the exception class), value (the current instance), and traceback (see -

Also see


Simple use:

import pytest
pytest.skip("Skipping for some reason")

Show skip reasons / info:

py.test -rs


Test using parametrize

import pytest

   ('n', 'expected'), [
       (1, 2),
       (2, 3),
       (3, 4),
       (4, 5),
       pytest.mark.xfail((1, 0)),
       pytest.mark.xfail(reason="some bug")((1, 0)),
       pytest.mark.skipif('sys.version_info >= (3,0)')((10, 11)),
def test_increment(n, expected):
   assert n + 1 == expected

Helper to write dict to /tmp/data.json

def dump1(data, fname="/tmp/data.json"):
    from json import JSONEncoder
    class DateTimeAndDecimalEncoder(JSONEncoder):
        def default(self, obj):
          import datetime
          import decimal
          if isinstance(obj, datetime.datetime):
            encoded_object = obj.isoformat()
            # e.g. "2014-06-22T04:44:14.057000"
          elif isinstance(obj, decimal.Decimal):
            return str(obj)
            encoded_object =JSONEncoder.default(self, obj)
          return encoded_object

    def dumps_pretty(s):
        # datetime.datetime(2013, 9, 13, 9, 59, 11) is not JSON serializable
        import json
        return"%s" % json.dumps(s,
          separators=(',', ': '),

    f = open(fname, "w")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment