From bcc994c001a1b278760b1b6c4f12d12f48bb22f9 Mon Sep 17 00:00:00 2001 From: "Hugo P.Brito" Date: Tue, 30 Jun 2026 15:50:49 +0100 Subject: [PATCH] fix: ignore virtualenvs in test init guard --- scripts/check_test_init_files.py | 35 +++++++++++++++++++++---- tests/lib/check_test_init_files_test.py | 24 +++++++++++++++++ 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/scripts/check_test_init_files.py b/scripts/check_test_init_files.py index 5597ff0eaf..7a98a8362a 100644 --- a/scripts/check_test_init_files.py +++ b/scripts/check_test_init_files.py @@ -5,12 +5,25 @@ from __future__ import annotations import sys from argparse import ArgumentParser +from os import walk from pathlib import Path EXCLUDED_TEST_INIT_ROOTS = { Path("tests/lib/check/fixtures/checks_folder"), } +IGNORED_DIRECTORY_NAMES = { + ".git", + ".mypy_cache", + ".nox", + ".pytest_cache", + ".tox", + ".venv", + "__pycache__", + "node_modules", + "venv", +} + def is_test_init_file(path: Path) -> bool: """Return True when the file is a test __init__.py.""" @@ -27,11 +40,23 @@ def is_excluded_test_init_file(path: Path, root: Path) -> bool: def find_test_init_files(root: Path) -> list[Path]: """Return sorted __init__.py files found under test directories.""" - return sorted( - path - for path in root.rglob("__init__.py") - if is_test_init_file(path) and not is_excluded_test_init_file(path, root) - ) + matches = [] + + for current_root, directories, filenames in walk(root): + directories[:] = [ + directory + for directory in directories + if directory not in IGNORED_DIRECTORY_NAMES + ] + if "__init__.py" in filenames: + path = Path(current_root) / "__init__.py" + else: + continue + + if is_test_init_file(path) and not is_excluded_test_init_file(path, root): + matches.append(path) + + return sorted(matches) def main(argv: list[str] | None = None) -> int: diff --git a/tests/lib/check_test_init_files_test.py b/tests/lib/check_test_init_files_test.py index 1798de4685..9183030e81 100644 --- a/tests/lib/check_test_init_files_test.py +++ b/tests/lib/check_test_init_files_test.py @@ -47,6 +47,30 @@ def test_find_test_init_files_detects_only_test_directories(tmp_path): ] +def test_find_test_init_files_ignores_virtualenv_test_packages(tmp_path): + guard = load_guard_module() + + virtualenv_tests = ( + tmp_path + / ".venv" + / "lib" + / "python3.12" + / "site-packages" + / "package" + / "tests" + ) + virtualenv_tests.mkdir(parents=True) + (virtualenv_tests / "__init__.py").write_text("") + (tmp_path / "tests" / "providers" / "aws").mkdir(parents=True) + (tmp_path / "tests" / "providers" / "aws" / "__init__.py").write_text("") + + matches = guard.find_test_init_files(tmp_path) + + assert [path.relative_to(tmp_path) for path in matches] == [ + Path("tests/providers/aws/__init__.py"), + ] + + def test_main_returns_error_when_test_init_files_exist(tmp_path, capsys): guard = load_guard_module()