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

Assert exception is raised

Use with pytest.raises(ValueError): as a context manager:

# inside my_test.py
def test_raises_index_error():

    with pytest.raises(IndexError):
        arr = [1,2,3]
        arr[1]

Run using $ pytext at the root:

$ pytest
============================= test session starts ==============================
platform linux -- Python 3.8.10, pytest-7.1.2, pluggy-1.0.0
plugins: anyio-3.3.4
collected 1 item                                                               

tests/my_test.py .                                                        [100%]

============================== 1 passed in 0.02s ===============================

Dialogue & Discussion