Skip to content

Commit

Permalink
- added (simplistic) support for looking up assignments such as those
Browse files Browse the repository at this point in the history
  used for constants;
  • Loading branch information
jaltmayerpizzorno committed Aug 21, 2024
1 parent 58928ed commit 80127e4
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/coverup/codeinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ def _find_name_path(node: ast.AST, name: T.List[str]) -> T.List[ast.AST]:
if isinstance(c, (ast.FunctionDef, ast.AsyncFunctionDef)) and c.name == name[0]:
return [c] if len(name) == 1 else []

if isinstance(c, ast.Assign) and any(t.id == name[0] for t in c.targets):
return [c] if len(name) == 1 else []

if isinstance(c, (ast.Import, ast.ImportFrom)):
# FIXME the first matching import needn't be the one that resolves the name:
# import foo.bar
Expand Down
37 changes: 37 additions & 0 deletions tests/test_codeinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,43 @@ def foo():
assert codeinfo.get_info(tree, 'foo') == None


def test_get_info_assignment():
code = textwrap.dedent("""\
PI = 3.1415
x = 0
if x == 0:
TYPES = (
int,
str,
)
class C:
x = 10
def __init__(self, x: int) -> C:
self._foo = x
"""
)

tree = ast.parse(code)
tree.path = Path("foo.py")

assert codeinfo.get_info(tree, 'PI') == textwrap.dedent("""\
PI = 3.1415"""
)

# FIXME do proper code slicing
assert codeinfo.get_info(tree, 'TYPES') == textwrap.dedent("""\
TYPES = (int, str)"""
)

assert codeinfo.get_info(tree, 'C.x') == textwrap.dedent("""\
class C:
...
x = 10"""
)

def test_get_info_imported(import_fixture):
tmp_path = import_fixture

Expand Down

0 comments on commit 80127e4

Please sign in to comment.