0
0
PytestHow-ToBeginner ยท 3 min read

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

Example

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 tests
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Placing pytest.ini in 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

OptionDescriptionExample
addoptsExtra command-line optionsaddopts = -v --maxfail=1
testpathsDirectories to search for teststestpaths = tests integration
markersRegister custom markersmarkers =\n slow: marks slow tests
python_filesGlob pattern for test filespython_files = test_*.py *_test.py
log_cliEnable logging to consolelog_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.