Pytest Options: Best Practices and Examples

Last updated:
Table of Contents

Show stdout output

pass --capture=tee-sys to the command:

$ pytest --capture=tee-sys

Add current dir to path

Call pytest as a module: python -m pytest (instead of just pytest)

Suppress warnings

Add to pytest.ini:

[pytest]
addopts = -p no:warnings

Suppress deprecationwarnings

Add to pytest.ini:

[pytest]
filterwarnings =
    ignore:.+:DeprecationWarning

Run single test

Use -k 'test_name'

Example: To run only test test_foo():

$ pytest path/to/test.py -k 'test_foo'

Mark.parametrize example

To run multiple tests where only the input/outputs are different, use pytest.mark.parametrize:

import pytest

# run 3 tests at once
@pytest.mark.parametrize(
    'num1, num2, result',  # define the parameters
    [[2, 2, 4],            # list of lists with the values
     [1, 1, 2],
     [2, 3, 5]])
def test_add(num1, num2, result):  # parameters must match the names above
    assert num1 + num2 == result

Dialogue & Discussion