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, orsetup.cfgto 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 slowExample
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
| Option | Description | Example |
|---|---|---|
| -v, --verbose | Increase verbosity of test output | pytest -v |
| --maxfail=num | Stop after num failures | pytest --maxfail=3 |
| -k expr | Run tests matching expr | pytest -k 'test_login' |
| -m markexpr | Run tests with marker | pytest -m slow |
| addopts | Set default command-line options in config | addopts = -v --maxfail=2 |
| markers | Define custom markers | markers = 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.