46 lines
1.8 KiB
Python
46 lines
1.8 KiB
Python
import ast
|
|
import importlib
|
|
import importlib.util
|
|
import pathlib
|
|
import sys
|
|
import unittest
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
|
|
from repo_checks import ROOT
|
|
|
|
TRIALS = ROOT / "reviewer-merge-trials"
|
|
|
|
|
|
def bin_imports(source: str) -> list[tuple[str, str | None]]:
|
|
"""Each module the source imports from bin/, with each name it takes from that module, or None for the module itself."""
|
|
found: list[tuple[str, str | None]] = []
|
|
for node in ast.walk(ast.parse(source)):
|
|
if isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
|
|
found += [(node.module, alias.name) for alias in node.names]
|
|
elif isinstance(node, ast.Import):
|
|
found += [(alias.name, None) for alias in node.names]
|
|
return [(module, name) for module, name in found if in_bin(module)]
|
|
|
|
|
|
def in_bin(module: str) -> bool:
|
|
top = ROOT / "bin" / module.split(".")[0]
|
|
return top.is_dir() or top.with_suffix(".py").is_file()
|
|
|
|
|
|
class TrialsImports(unittest.TestCase):
|
|
"""docs/decisions.md says to rerun the trials' scripts when a new model joins the ladder or a reviewer changes, so a refactor of bin/ must not break what they import."""
|
|
|
|
def test_each_name_a_trials_script_imports_from_bin_exists(self):
|
|
scripts = sorted(TRIALS.glob("*.py"))
|
|
self.assertTrue(scripts)
|
|
for script in scripts:
|
|
for module, name in bin_imports(script.read_text(encoding="utf-8")):
|
|
with self.subTest(script=script.name, module=module, name=name):
|
|
imported = importlib.import_module(module)
|
|
if name is not None:
|
|
self.assertTrue(hasattr(imported, name) or importlib.util.find_spec(f"{module}.{name}"))
|
|
|
|
def test_an_import_of_a_bin_module_is_found_and_a_stdlib_one_is_not(self):
|
|
self.assertEqual(bin_imports("import json\nfrom failure import Failure\nimport review_replay.main as rm\n"), [("failure", "Failure"), ("review_replay.main", None)])
|