"""Files that tests import by their file name, which mutmut finds only when it runs in the file's own folder. A test in docker/scripts/ that runs `import run_harness` gets it because pytest, or unittest's discover, puts that folder on sys.path. mutmut run from the checkout's top names the same file docker.scripts.run_harness, so it finds none of the tests' calls to it.""" import ast import os import pathlib import posixpath from mutate_changes.changed_lines import is_test def imported_by_file_name(top: str, grouped: dict[str, dict[str, frozenset[int]]], configs: tuple[str, ...]) -> dict[str, dict[str, frozenset[int]]]: """grouped, with each file in its "." group moved to its own folder where a test beside it imports it by its file name and the folder has no __init__.py. A file in a folder that holds one of configs stays, as does every file where the top holds one: the settings there decide how its tests import it.""" if "." not in grouped or any(os.path.isfile(os.path.join(top, name)) for name in configs): return grouped regrouped: dict[str, dict[str, frozenset[int]]] = {name: files for name, files in grouped.items() if name != "."} for path, lines in grouped["."].items(): own = posixpath.dirname(path) or "." moved = posixpath.basename(path)[:-3] in top_level_imports(os.path.join(top, own)) and not os.path.isfile(os.path.join(top, own, "__init__.py")) regrouped.setdefault(own if moved else ".", {})[posixpath.basename(path) if moved else path] = lines return regrouped def top_level_imports(folder: str) -> set[str]: """The top-level module names that the test files in folder import, as `a` for `import a.b`. A test file that can't be read or parsed adds none.""" names: set[str] = set() for test in sorted(pathlib.Path(folder).glob("*.py")): if not is_test(test.name): continue try: tree = ast.parse(test.read_text(encoding="utf-8")) except (OSError, SyntaxError, UnicodeDecodeError, ValueError): continue for node in ast.walk(tree): if isinstance(node, ast.Import): names.update(alias.name.partition(".")[0] for alias in node.names) elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: names.add(node.module.partition(".")[0]) return names