How to Use setup.cfg for pytest Configuration
[tool:pytest] section in your setup.cfg file. This lets you set test paths, markers, and other settings without command-line arguments or pytest.ini files.Syntax
The setup.cfg file uses an INI-style format. To configure pytest, add a [tool:pytest] section. Inside this section, you list pytest options as key-value pairs.
Common keys include addopts for extra command-line options, testpaths for test directories, and markers to register custom markers.
[tool:pytest]
addopts = -v --maxfail=2
testpaths = tests
markers =
slow: marks tests as slow
smoke: marks smoke testsExample
This example shows a setup.cfg file configuring pytest to run tests in the tests folder, show verbose output, stop after 2 failures, and register two custom markers.
Run pytest in the terminal, and it will use these settings automatically.
[tool:pytest]
addopts = -v --maxfail=2
testpaths = tests
markers =
slow: marks tests as slow
smoke: marks smoke testsCommon Pitfalls
One common mistake is using [pytest] instead of [tool:pytest] in setup.cfg. pytest only recognizes the [tool:pytest] section there.
Another issue is incorrect indentation or missing newlines in the markers list, which can cause pytest to ignore marker registrations.
Also, avoid placing setup.cfg in the wrong directory; it must be in the root folder of your project.
[pytest] addopts = -v # WRONG: pytest ignores this section in setup.cfg [tool:pytest] addopts = -v # CORRECT: pytest reads this section
Quick Reference
| Option | Description | Example |
|---|---|---|
| addopts | Extra command-line options for pytest | addopts = -v --maxfail=1 |
| testpaths | Directories where pytest looks for tests | testpaths = tests src/tests |
| markers | Register custom markers with descriptions | markers = slow: marks slow tests smoke: marks smoke tests |
| python_files | Glob pattern for test file names | python_files = test_*.py *_test.py |
| python_classes | Test class name patterns | python_classes = Test* |
| python_functions | Test function name patterns | python_functions = test_* |