Run mutate-changes on a script its tests import by file name, and name a crash inside mutmut in one line
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
"""Files whose tests import them by file name, which mutmut names right only from 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, and 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 that a test beside it imports by its file name moved to its own folder, named from the checkout's top.
|
||||
|
||||
A folder that holds one of configs keeps its files: the settings there decide how its tests import them."""
|
||||
regrouped: dict[str, dict[str, frozenset[int]]] = {}
|
||||
for folder, files in grouped.items():
|
||||
configured = any(os.path.isfile(os.path.join(top, folder, name)) for name in configs)
|
||||
for path, lines in files.items():
|
||||
own = posixpath.join(folder, posixpath.dirname(path))
|
||||
moved = not configured and 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"))
|
||||
target, name = (posixpath.normpath(own), posixpath.basename(path)) if moved else (folder, path)
|
||||
regrouped.setdefault(target, {})[name] = lines
|
||||
return regrouped
|
||||
|
||||
|
||||
def top_level_imports(folder: str) -> set[str]:
|
||||
"""The modules the test files in folder import by their first name. A test file that doesn't parse names none."""
|
||||
names: set[str] = set()
|
||||
for test in 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
|
||||
Reference in New Issue
Block a user