Pytest Options: Best Practices and Examples

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 directory 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' when running pytest.

This will only run tests whose name match the string "test_name"

Example: To run only test test_foo():

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

Mark.parametrize example

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

Example: Run the same test 3 times, for different pairs of input/outputs:

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

Output (3 tests were run):

$ pytest tests.py 
=================== test session starts =================
collected 3 items

tests.py ...                                       [100%]

Enable doctest

See how to create doctests here: Python Docstrings Examples: Doctest

Add this pytest.ini to have doctests also run when you run pytest:

[pytest]
addopts = --doctest-modules