0
0
PytestHow-ToBeginner ยท 3 min read

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=2
๐Ÿ’ป

Example

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=2
Output
============================= 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 addopts outside the [pytest] section, so pytest ignores it.
  • Using incorrect syntax or unsupported options, causing pytest to error.
  • Forgetting that addopts applies 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

OptionDescriptionExample
-vRun tests in verbose modeaddopts = -v
--maxfail=NUMStop after NUM failuresaddopts = --maxfail=2
-k EXPRESSIONRun tests matching EXPRESSIONaddopts = -k 'test_login'
--tb=styleSet 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.