swev-id: pytest-dev__pytest-6197 Fix: avoid importing non-test __init__.py during collection; restore 5.2.2 behavior#25
Open
casey-brooks wants to merge 1 commit intopytest-dev__pytest-6197from
Conversation
Author
Local Verification
|
noa-lucent
approved these changes
Dec 25, 2025
noa-lucent
left a comment
There was a problem hiding this comment.
Changes look good: guarding package init import behind python_files/explicit selection restores expected behavior, and regression tests cover the updated scenarios.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
__init__.pyunless the file matchespython_filesor was explicitly requestedpython_filesopt-in, src/ layout, and namespace packagesTesting
Fixes #19
Root cause
Package.collectunconditionally imported the package via_mount_obj_if_needed(), which executes__init__.pyeven when the file is not considered a test module. This regressed after the package-scoped fixture work in 5.2.3.Fix details
_should_import_init()to decide when__init__.pyshould be mounted/collected (matchespython_filesor the file was explicitly targeted)collect()andsetup()behind this check so that boundary-level hooks remain intact without importing non-test packages prematurelypython_filesopt-in, src layout, namespace package)Reproduction steps and observed failure
pkg/__init__.pywithassert Falseand place unrelated tests elsewhere (e.g.tests/test_ok.py).pytestfrom the project root under 5.2.3.AssertionErrorwhile importingpkg/__init__.pyeven though it is not a test module.Compatibility
python_filesopt-in still collects package__init__.pycontaining tests.__init__.py) remain unaffected.pytest pkg/__init__.py) continues to work via theinitialpathsguard.