Configuring Pytest/shaare/bti1Ng
Configuring Pytest
- As you start using Pytest extensively, typing
-vor-mon the command line every time becomes tedious. - Centralize your defaults in
pyproject.tomlunder the[tool.pytest.ini_options]table. - A single source of truth means every developer—and your CI system—runs tests with the same settings.
- Putting Pytest alongside other PEP 518 tools (Black, isort, Flake8) keeps your repo tidy and consistent.
Why a Configuration File?
- Consistency: Run
pytestwithout remembering flags; everyone gets the same behavior. - Simplicity: Remove boilerplate from docs and CI scripts.
- Project-specific discovery: Set
testpaths,python_filesand markers in one place. - Cleaner output: Declare markers to silence
PytestUnknownMarkWarning, enable color and rich tracebacks by default.
Configuration File Hierarchy
Pytest searches for settings in this order, using the first match from the current or a parent directory:
pyproject.tomlunder[tool.pytest.ini_options]pytest.initox.iniwith a[pytest]sectionsetup.cfgunder[tool:pytest]
Embrace pyproject.toml as the modern hub for all your tool configurations.
Creating pyproject.toml
- Create or open
pyproject.tomlat your project root. - Add a
[tool.pytest.ini_options]table. - Define your defaults using TOML syntax and inline strings.
Common Configuration Options
-
addopts
Defines default command-line flags that Pytest applies on every run (verbosity, reporting, color, etc.). -
markers
Pre-registers custom markers with descriptions so that you can categorize tests and avoid unknown-marker warnings. -
testpaths
Restricts test discovery to the listed directories, preventing Pytest from scanning other parts of the project. -
python_files
Specifies filename patterns that Pytest treats as test files (e.g.,test_*.py). -
python_classes
Indicates class name patterns Pytest will consider when looking for test classes (e.g., classes starting withTest). -
python_functions
Sets function name patterns Pytest uses to identify individual test functions (e.g., functions beginning withtest_). -
Other options
norecursedirs: directories to skip during discoveryminversion: enforce a minimum Pytest versionfilterwarnings: configure how warnings are handled- and many more built-in settings for fine-tuning
Example of pyproject.toml
from typing import TypedDict
import re
class TextAttributes(TypedDict):
word_count: int
unique_words: set[str]
average_word_length: float
longest_word: str
def calculate_text_attributes(input_text: str) -> TextAttributes:
split_text = re.findall(r"\w+", input_text)
word_length_sum = sum(len(word) for word in split_text)
avg_word_length = (
word_length_sum / len(split_text)
if len(split_text)
else 0
)
return {
"word_count": len(split_text),
"unique_words": set(text.lower() for text in split_text),
"average_word_length": avg_word_length,
"longest_word": (
max(split_text, key=len) if split_text else ""
),
}
(97)