Exclude directories and files from pytest collection
Use explicit ignore paths or directory patterns, and distinguish collection exclusions from deselecting already discovered tests.
Use --ignore=path to exclude a file or directory during ordinary pytest collection. Repeat it for several paths. To make the same exclusions part of the project's normal command, put them in addopts.
Ignore specific paths
python -m pytest --ignore=legacy_tests
python -m pytest --ignore=legacy_tests --ignore=generated_tests
python -m pytest --ignore=tests/test_legacy.py
Command-line relative paths are interpreted from the working directory. Run from a consistent location or use unambiguous paths.
Store project-wide options
# pytest.ini
[pytest]
addopts = --ignore=legacy_tests --ignore=generated_tests
These options are used when that configuration is selected. Verify the configuration shown by pytest, especially when a repository has several test projects. Relative ignore paths in addopts still need a consistent invocation directory; placing a string in a config file does not make every command-line path relative to that file.
For directory-name patterns:
[pytest]
norecursedirs = .* build dist node_modules venv .venv legacy_*
norecursedirs controls recursive discovery and supports filename-style patterns. Setting it replaces the default list, so preserve the defaults your project needs. Pytest also has special handling for recognized virtual-environment directories; that is different from assuming every directory called venv is excluded by an invariant name list.
Configure a file exclusion in conftest.py
# conftest.py next to test_legacy.py
collect_ignore = ["test_legacy.py"]
These paths are relative to the relevant conftest.py location. Keep the file's scope clear instead of importing it from tests manually.
FAQ
How is --deselect different?
--ignore avoids traversing or importing the excluded collection path. --deselect=tests/test_api.py::test_old_endpoint removes a matching collected item, so collection-time imports and errors can still occur.
Can I exclude a virtual environment with a custom name?
Add the directory pattern explicitly when appropriate. Use --collect-only to inspect discovery. Recognized environments are normally skipped during recursive collection unless collection of virtual environments is enabled, but explicit targets can change which paths are visited.
Does an exclusion prevent someone from running that file explicitly?
Do not treat discovery settings as an access-control boundary. In particular, explicit command-line collection targets can bypass recursive-discovery exclusions. Keep generated or environment directories out of the normal test tree and verify the exact invocation used by CI.
References: pytest collection rules, pytest configuration reference.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan