How to Use pytest.ini for Configuring Pytest
Use
pytest.ini to configure pytest by placing it in your project root with key-value settings. It lets you set options like test paths, markers, and command-line flags to customize test runs without typing them every time.Syntax
The pytest.ini file uses an INI-style format with sections and key-value pairs. The main section is [pytest], where you define pytest settings. Common keys include addopts for extra command-line options, testpaths for test directories, and markers to register custom markers.
ini
[pytest]
addopts = -v --maxfail=2
testpaths = tests
markers =
slow: marks tests as slow
smoke: marks smoke testsExample
This example shows a pytest.ini file that sets verbose output, stops after 2 failures, looks for tests in the tests folder, and registers two custom markers: slow and smoke. Running pytest will use these settings automatically.
ini
[pytest]
addopts = -v --maxfail=2
testpaths = tests
markers =
slow: marks tests as slow
smoke: marks smoke testsCommon Pitfalls
Common mistakes include:
- Placing
pytest.iniin the wrong directory (it must be in the project root or current working directory). - Incorrect indentation or missing the
[pytest]section header. - Not registering custom markers in
pytest.ini, which causes warnings. - Using unsupported keys or typos in option names.
Always validate your pytest.ini syntax and location.
ini
# Wrong: missing section header addopts = -v # Correct: [pytest] addopts = -v
Quick Reference
| Option | Description | Example |
|---|---|---|
| addopts | Extra command-line options | addopts = -v --maxfail=1 |
| testpaths | Directories to search for tests | testpaths = tests integration |
| markers | Register custom markers | markers =\n slow: marks slow tests |
| python_files | Glob pattern for test files | python_files = test_*.py *_test.py |
| log_cli | Enable logging to console | log_cli = true |
Key Takeaways
Place pytest.ini in your project root to configure pytest globally.
Use the [pytest] section with key-value pairs like addopts and testpaths.
Register custom markers in pytest.ini to avoid warnings.
Check syntax carefully to prevent pytest from ignoring your config.
pytest.ini saves time by avoiding repeated command-line options.