"""Tests for Python AST symbol, inheritance, import, and call graph extraction.""" from __future__ import annotations from pathlib import Path from lgpython.ast_graph import discover_python_files, extract_python_graph, module_names_for_file def test_discover_python_files_ignores_caches_and_venvs(sample_pkg: Path) -> None: (sample_pkg / "__pycache__").mkdir() (sample_pkg / "__pycache__" / "junk.py").write_text("x = 1\n", encoding="utf-8") (sample_pkg / ".venv" / "lib").mkdir(parents=True) (sample_pkg / ".venv" / "lib" / "site.py").write_text("x = 2\n", encoding="utf-8") files = discover_python_files(sample_pkg) assert files == [ "src/mathops.py", "src/textops.py", "tests/test_mathops.py", "tests/test_textops.py", ] def test_module_names_for_file_strips_src_and_init() -> None: assert "mathops" in module_names_for_file("src/mathops.py") assert "src.mathops" in module_names_for_file("src/mathops.py") assert "pkg" in module_names_for_file("src/pkg/__init__.py") def test_extract_python_graph_captures_classes_methods_inheritance_and_calls( sample_pkg: Path, ) -> None: files = discover_python_files(sample_pkg) symbols, edges = extract_python_graph(sample_pkg, files) assert "src/mathops.py::Accumulator" in symbols assert "src/mathops.py::BoundedAccumulator" in symbols assert "src/mathops.py::BoundedAccumulator.add" in symbols assert "src/mathops.py::double_sum" in symbols assert ("src/mathops.py::BoundedAccumulator", "src/mathops.py::Accumulator") in edges assert ("src/mathops.py::double_sum", "src/mathops.py::add_numbers") in edges assert ("src/textops.py", "src/mathops.py") in edges assert ("src/textops.py::format_sum", "src/mathops.py::add_numbers") in edges def test_extract_python_graph_handles_relative_imports_and_syntax_errors(tmp_path: Path) -> None: pkg = tmp_path / "pkg" pkg.mkdir() (pkg / "__init__.py").write_text("", encoding="utf-8") (pkg / "core.py").write_text("def compute():\n return 42\n", encoding="utf-8") (pkg / "caller.py").write_text( "from .core import compute\n\ndef run():\n return compute()\n", encoding="utf-8", ) (pkg / "broken.py").write_text("def oops(:\n", encoding="utf-8") files = discover_python_files(tmp_path) symbols, edges = extract_python_graph(tmp_path, files) assert "pkg/broken.py" in symbols assert ("pkg/caller.py", "pkg/core.py") in edges assert ("pkg/caller.py::run", "pkg/core.py::compute") in edges