Answer principles round 2: 0 🔴, 0 🟡 (0 misread); check the names the trials read through a module alias too
This commit is contained in:
@@ -13,19 +13,29 @@ 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."""
|
||||
"""Each module the source imports from bin/, with each name it takes from that module or reads through a name bound to it, or None for the module itself."""
|
||||
tree = ast.parse(source)
|
||||
found: list[tuple[str, str | None]] = []
|
||||
for node in ast.walk(ast.parse(source)):
|
||||
# A name the source binds to a module, such as rm in `from review_replay import main as rm`.
|
||||
modules: dict[str, str] = {}
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
|
||||
found += [(node.module, alias.name) for alias in node.names]
|
||||
modules |= {alias.asname or alias.name: f"{node.module}.{alias.name}" for alias in node.names if is_module(f"{node.module}.{alias.name}")}
|
||||
elif isinstance(node, ast.Import):
|
||||
found += [(alias.name, None) for alias in node.names]
|
||||
modules |= {alias.asname: alias.name for alias in node.names if alias.asname}
|
||||
found += [(modules[node.value.id], node.attr) for node in ast.walk(tree) if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id in modules]
|
||||
return [(module, name) for module, name in found if in_bin(module)]
|
||||
|
||||
|
||||
def is_module(dotted: str) -> bool:
|
||||
path = ROOT / "bin" / dotted.replace(".", "/")
|
||||
return path.is_dir() or path.with_suffix(".py").is_file()
|
||||
|
||||
|
||||
def in_bin(module: str) -> bool:
|
||||
top = ROOT / "bin" / module.split(".")[0]
|
||||
return top.is_dir() or top.with_suffix(".py").is_file()
|
||||
return is_module(module.split(".")[0])
|
||||
|
||||
|
||||
class TrialsImports(unittest.TestCase):
|
||||
@@ -43,3 +53,7 @@ class TrialsImports(unittest.TestCase):
|
||||
|
||||
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)])
|
||||
|
||||
def test_a_name_read_through_a_module_alias_is_found(self):
|
||||
source = "from review_replay import main as rm\nimport review_replay.rounds as rr\nrm.code_of(rr.Round)\n"
|
||||
self.assertEqual(bin_imports(source), [("review_replay", "main"), ("review_replay.rounds", None), ("review_replay.main", "code_of"), ("review_replay.rounds", "Round")])
|
||||
|
||||
Reference in New Issue
Block a user