How to Use addopts in pytest Config for Custom Test Runs
Use
addopts in your pytest.ini file to specify default command-line options for pytest runs. This lets you add flags like -v or --maxfail=2 automatically every time you run tests without typing them manually.Syntax
The addopts option is placed inside the [pytest] section of your pytest.ini file. It accepts a string of command-line options that pytest will use by default when running tests.
Example parts:
[pytest]: Section header for pytest configuration.addopts = -v --maxfail=2: Default options to run tests verbosely and stop after 2 failures.
ini
[pytest]
addopts = -v --maxfail=2Example
This example shows a pytest.ini file with addopts set to run tests verbosely and stop after two failures. When you run pytest in the terminal, these options apply automatically.
ini
[pytest]
addopts = -v --maxfail=2Output
============================= test session starts ==============================
collected 3 items
test_sample.py::test_one PASSED
test_sample.py::test_two FAILED
test_sample.py::test_three FAILED
=========================== short test summary info ===========================
FAILED test_sample.py::test_two - AssertionError
FAILED test_sample.py::test_three - AssertionError
========================= 2 failed, 1 passed in 0.12s =========================
Common Pitfalls
Common mistakes when using addopts include:
- Placing
addoptsoutside the[pytest]section, so pytest ignores it. - Using incorrect syntax or unsupported options, causing pytest to error.
- Forgetting that
addoptsapplies to all pytest runs, which might conflict with command-line options.
Always check your pytest.ini file syntax and test your options manually first.
ini
# Wrong: addopts outside [pytest] section [other_section] addopts = -v # Correct: [pytest] addopts = -v
Quick Reference
| Option | Description | Example |
|---|---|---|
| -v | Run tests in verbose mode | addopts = -v |
| --maxfail=NUM | Stop after NUM failures | addopts = --maxfail=2 |
| -k EXPRESSION | Run tests matching EXPRESSION | addopts = -k 'test_login' |
| --tb=style | Set traceback style (auto, short, line, native) | addopts = --tb=short |
Key Takeaways
Put addopts inside the [pytest] section of pytest.ini to set default test options.
Use addopts to save typing common pytest flags like -v or --maxfail=2 every run.
Check syntax carefully; wrong placement or options cause pytest errors or ignored settings.
addopts options apply to all pytest runs unless overridden by command-line arguments.
Use addopts to customize pytest behavior consistently across your project.