fix: ignore virtualenvs in test init guard

This commit is contained in:
Hugo P.Brito
2026-06-30 15:50:49 +01:00
parent 644ecb1e7d
commit bcc994c001
2 changed files with 54 additions and 5 deletions
+30 -5
View File
@@ -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:
+24
View File
@@ -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()