0
0
PytestHow-ToBeginner ยท 4 min read

How to Configure pytest Options for Custom Test Runs

You can configure pytest options by using command-line flags, creating a pytest.ini or tox.ini configuration file, or defining custom hooks in conftest.py. These methods let you control test discovery, output format, markers, and more to customize your test runs.
๐Ÿ“

Syntax

pytest options can be set in three main ways:

  • Command-line flags: Pass options directly when running pytest.
  • Configuration files: Use pytest.ini, tox.ini, or setup.cfg to set options persistently.
  • conftest.py hooks: Write Python code to customize pytest behavior.

Example command-line syntax:

pytest [options] [file_or_dir]

Example config file section:

[pytest]
addopts = -v --maxfail=2
markers = slow: marks tests as slow
ini
[pytest]
addopts = -v --maxfail=2
markers = slow: marks tests as slow
๐Ÿ’ป

Example

This example shows how to configure pytest to run tests verbosely, stop after 2 failures, and mark slow tests in a pytest.ini file. Then it runs pytest with these options automatically applied.

ini and python
[pytest]
addopts = -v --maxfail=2
markers = slow: marks tests as slow

# test_sample.py
import pytest

@pytest.mark.slow
def test_one():
    assert 1 == 1

def test_two():
    assert 2 == 2

def test_three():
    assert 3 == 4  # This will fail

def test_four():
    assert 4 == 5  # This will fail

def test_five():
    assert 5 == 5
Output
test_sample.py::test_one PASSED test_sample.py::test_two PASSED test_sample.py::test_three FAILED test_sample.py::test_four FAILED === 2 failed, 3 passed in 0.03s ===
โš ๏ธ

Common Pitfalls

Common mistakes when configuring pytest options include:

  • Placing options in the wrong config file or wrong section.
  • Using deprecated or misspelled option names.
  • Forgetting to reload pytest after changing config files.
  • Conflicting options between command line and config files.

Example of wrong and right config:

ini
# Wrong (missing [pytest] header)
addopts = -v

# Right
[pytest]
addopts = -v
๐Ÿ“Š

Quick Reference

OptionDescriptionExample
-v, --verboseIncrease verbosity of test outputpytest -v
--maxfail=numStop after num failurespytest --maxfail=3
-k exprRun tests matching exprpytest -k 'test_login'
-m markexprRun tests with markerpytest -m slow
addoptsSet default command-line options in configaddopts = -v --maxfail=2
markersDefine custom markersmarkers = slow: marks slow tests
โœ…

Key Takeaways

Configure pytest options via command-line flags, config files, or conftest.py hooks.
Use a [pytest] section in pytest.ini or tox.ini to set persistent options like addopts and markers.
Command-line options override config file settings when both are used.
Always include the [pytest] header in config files to avoid ignored settings.
Test your configuration by running pytest and checking the output matches your options.