Compare commits
1 Commits
step35/133
...
step35/109
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80f82c9ecd |
@@ -1,271 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Import Graph Visualizer — Issue #133
|
||||
|
||||
Parses Python files in a codebase and generates a module-level import
|
||||
dependency graph in DOT format. Detects circular imports.
|
||||
|
||||
Usage:
|
||||
python3 scripts/import_graph.py /path/to/hermes-agent
|
||||
python3 scripts/import_graph.py /path/to/hermes-agent --output deps.dot
|
||||
python3 scripts/import_graph.py /path/to/hermes-agent --render-png
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from collections import defaultdict
|
||||
from typing import Dict, Set, List, Optional
|
||||
|
||||
|
||||
def python_files(root: Path) -> List[Path]:
|
||||
"""Yield all .py files under root, excluding common noise dirs."""
|
||||
exlude_dirs = {'.git', '__pycache__', '.venv', 'venv', 'node_modules', 'dist', 'build', '.tox'}
|
||||
for path in root.rglob('*.py'):
|
||||
if any(part in exlude_dirs for part in path.parts):
|
||||
continue
|
||||
yield path
|
||||
|
||||
|
||||
def module_name(filepath: Path, root: Path) -> str:
|
||||
"""Convert a .py file path to its dotted module name relative to root."""
|
||||
rel = filepath.relative_to(root)
|
||||
parts = list(rel.parts)
|
||||
if parts[-1] == '__init__.py':
|
||||
parts = parts[:-1] # package __init__ → the package itself
|
||||
elif parts[-1].endswith('.py'):
|
||||
parts[-1] = parts[-1][:-3] # strip .py
|
||||
# Remove any __pycache__ segments
|
||||
parts = [p for p in parts if p != '__pycache__']
|
||||
return '.'.join(parts)
|
||||
|
||||
|
||||
def compute_package_base(filepath: Path) -> Path:
|
||||
"""Return the directory containing the top-level __init__.py for this file's package.
|
||||
For a file at a/b/c/d.py, return a/b/c if c is a package, else a/b, else a."""
|
||||
parent = filepath.parent
|
||||
while parent != parent.parent: # while we can go up
|
||||
if (parent / '__init__.py').exists():
|
||||
parent = parent.parent
|
||||
else:
|
||||
break
|
||||
return parent
|
||||
|
||||
|
||||
def resolve_import(from_node: ast.ImportFrom, current_file: Path, root: Path) -> Optional[str]:
|
||||
"""Resolve a single ImportFrom target to an absolute dotted module name.
|
||||
Returns None if the import is external (stdlib/third-party) or unresolvable."""
|
||||
level = from_node.level # 0 = absolute, >0 = relative
|
||||
imported = from_node.module # may be None for `from . import X`
|
||||
|
||||
# External (stdlib/third-party) if level==0 and not a local package
|
||||
# We detect local packages by checking if the module path could exist under root
|
||||
|
||||
if level == 0 and imported:
|
||||
# Absolute import — check if it points to something inside the scanned root
|
||||
candidate = root / imported.replace('.', '/')
|
||||
if candidate.exists() or (candidate / '__init__.py').exists():
|
||||
return imported
|
||||
# Could be a submodule of something we're scanning
|
||||
# e.g. from hermes.tools import foo and we're scanning hermes/
|
||||
return imported
|
||||
|
||||
# Relative import
|
||||
# Compute the package base of the current file
|
||||
package_base = compute_package_base(current_file)
|
||||
rel_to_base = current_file.parent.relative_to(package_base) if package_base != current_file.parent else Path()
|
||||
|
||||
if level == 1: # from . import X or from .X import Y
|
||||
target_package = current_file.parent
|
||||
else: # level >= 2: from ..X import Y etc.
|
||||
up = level - 1
|
||||
target_package = current_file.parent
|
||||
for _ in range(up):
|
||||
if target_package != target_package.parent:
|
||||
target_package = target_package.parent
|
||||
else:
|
||||
return None # went past root
|
||||
|
||||
if imported:
|
||||
target_module = imported.replace('.', '/')
|
||||
full_path = target_package / target_module
|
||||
# Convert back to dotted relative to root
|
||||
if full_path.exists() or (full_path.with_suffix('.py')).exists() or (full_path / '__init__.py').exists():
|
||||
try:
|
||||
rel = full_path.relative_to(root)
|
||||
parts = list(rel.parts)
|
||||
if (full_path / '__init__.py').exists():
|
||||
pass # keep all parts
|
||||
elif full_path.is_file() and full_path.name.endswith('.py'):
|
||||
parts[-1] = parts[-1][:-3]
|
||||
return '.'.join(parts)
|
||||
except ValueError:
|
||||
pass
|
||||
return None
|
||||
else:
|
||||
# from . import X — target_package is the package itself
|
||||
try:
|
||||
rel = target_package.relative_to(root)
|
||||
return '.'.join(rel.parts)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def scan_imports(root: Path) -> Dict[str, Set[str]]:
|
||||
"""Scan all Python files under root and return {module: {imported_modules}}."""
|
||||
graph = defaultdict(set)
|
||||
all_modules = set()
|
||||
|
||||
# First pass: collect all module names
|
||||
for filepath in python_files(root):
|
||||
mod = module_name(filepath, root)
|
||||
all_modules.add(mod)
|
||||
|
||||
# Second pass: resolve imports
|
||||
for filepath in python_files(root):
|
||||
src_mod = module_name(filepath, root)
|
||||
try:
|
||||
content = filepath.read_text(errors='ignore')
|
||||
tree = ast.parse(content, filename=str(filepath))
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
for alias in node.names:
|
||||
name = alias.name.split('.')[0] # top-level package only
|
||||
# If name matches a local module, add edge
|
||||
if any(m.startswith(name) for m in all_modules):
|
||||
graph[src_mod].add(name)
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
# level 0 = absolute, level >0 = relative
|
||||
resolved = resolve_import(node, filepath, root)
|
||||
if resolved:
|
||||
# For `from X.Y import Z`, the dependency is on X.Y
|
||||
graph[src_mod].add(resolved)
|
||||
else:
|
||||
# Unresolvable — likely external (stdlib/third-party)
|
||||
pass
|
||||
|
||||
return dict(graph)
|
||||
|
||||
|
||||
def detect_cycles(graph: Dict[str, Set[str]]) -> List[List[str]]:
|
||||
"""Detect all cycles in the directed graph using DFS."""
|
||||
cycles = []
|
||||
visited = set()
|
||||
rec_stack = set()
|
||||
path = []
|
||||
|
||||
def dfs(node: str):
|
||||
visited.add(node)
|
||||
rec_stack.add(node)
|
||||
path.append(node)
|
||||
|
||||
for neighbor in sorted(graph.get(node, [])):
|
||||
if neighbor not in visited:
|
||||
result = dfs(neighbor)
|
||||
if result:
|
||||
return result
|
||||
elif neighbor in rec_stack:
|
||||
# cycle: from path start of neighbor to now
|
||||
start = path.index(neighbor)
|
||||
return path[start:] + [neighbor]
|
||||
|
||||
path.pop()
|
||||
rec_stack.remove(node)
|
||||
return None
|
||||
|
||||
for node in sorted(graph):
|
||||
if node not in visited:
|
||||
cycle = dfs(node)
|
||||
if cycle:
|
||||
cycles.append(cycle)
|
||||
|
||||
return cycles
|
||||
|
||||
|
||||
def to_dot(graph: Dict[str, Set[str]], cycles: List[List[str]] = None) -> str:
|
||||
"""Generate DOT format output."""
|
||||
cycle_nodes = set()
|
||||
if cycles:
|
||||
for cycle in cycles:
|
||||
cycle_nodes.update(cycle)
|
||||
|
||||
lines = ['digraph import_graph {']
|
||||
lines.append(' rankdir=LR;')
|
||||
lines.append(' node [shape=box, style=filled, fontname="Helvetica"];')
|
||||
lines.append(' edge [arrowhead=vee];')
|
||||
lines.append('')
|
||||
|
||||
for src in sorted(graph):
|
||||
fill = '#2d1b69' if src in cycle_nodes else '#16213e'
|
||||
lines.append(f' "{src}" [fillcolor="{fill}"];')
|
||||
|
||||
for src, deps in sorted(graph.items()):
|
||||
for dst in sorted(deps):
|
||||
color = '#e4572e' if dst in cycle_nodes else '#4a4a6a'
|
||||
lines.append(f' "{src}" -> "{dst}" [color="{color}"];')
|
||||
|
||||
lines.append('}')
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Generate Python import graph for a codebase')
|
||||
parser.add_argument('path', help='Path to Python project (e.g. hermes-agent directory)')
|
||||
parser.add_argument('--output', '-o', help='Write DOT to file instead of stdout')
|
||||
parser.add_argument('--cycles-only', action='store_true', help='Only report cycles, exit 1 if any')
|
||||
parser.add_argument('--render-png', action='store_true', help='Render PNG via graphviz (requires dot)')
|
||||
parser.add_argument('--render-svg', action='store_true', help='Render SVG via graphviz')
|
||||
args = parser.parse_args()
|
||||
|
||||
root = Path(args.path).resolve()
|
||||
if not root.is_dir():
|
||||
print(f"Error: {root} is not a directory", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Scanning {root}...", file=sys.stderr)
|
||||
graph = scan_imports(root)
|
||||
cycles = detect_cycles(graph)
|
||||
|
||||
if args.cycles_only:
|
||||
if cycles:
|
||||
print("CIRCULAR DEPENDENCIES:", file=sys.stderr)
|
||||
for cycle in cycles:
|
||||
print(f" {' → '.join(cycle)}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("No circular dependencies found.", file=sys.stderr)
|
||||
sys.exit(0)
|
||||
|
||||
# Prepare output
|
||||
output = to_dot(graph, cycles)
|
||||
|
||||
if args.output:
|
||||
Path(args.output).write_text(output)
|
||||
print(f"DOT written to {args.output}", file=sys.stderr)
|
||||
|
||||
# Optional rendering
|
||||
if args.render_png or args.render_svg:
|
||||
import subprocess
|
||||
out_path = Path(args.output)
|
||||
if args.render_png:
|
||||
png_out = out_path.with_suffix('.png')
|
||||
subprocess.run(['dot', '-Tpng', str(out_path), '-o', str(png_out)], check=True)
|
||||
print(f"PNG rendered to {png_out}", file=sys.stderr)
|
||||
if args.render_svg:
|
||||
svg_out = out_path.with_suffix('.svg')
|
||||
subprocess.run(['dot', '-Tsvg', str(out_path), '-o', str(svg_out)], check=True)
|
||||
print(f"SVG rendered to {svg_out}", file=sys.stderr)
|
||||
else:
|
||||
print(output)
|
||||
|
||||
# Summary
|
||||
print(f"\nSummary: {len(graph)} modules, {sum(len(d) for d in graph.values())} import edges, {len(cycles)} cycles",
|
||||
file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
212
scripts/test_update_checker.py
Normal file
212
scripts/test_update_checker.py
Normal file
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Tests for update_checker.py — 5.3: Update Checker
|
||||
|
||||
Acceptance criteria verified:
|
||||
✓ Compares installed vs latest
|
||||
✓ Reports major/minor/patch updates
|
||||
✓ Flags breaking changes (major)
|
||||
✓ Output: update report
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
# Add scripts dir to path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts"))
|
||||
|
||||
import update_checker as uc
|
||||
|
||||
|
||||
def test_parse_version():
|
||||
assert uc.parse_version("1.2.3") == (1, 2, 3)
|
||||
assert uc.parse_version("2.0.0") == (2, 0, 0)
|
||||
assert uc.parse_version("0.9.0") == (0, 9, 0)
|
||||
assert uc.parse_version("1.2") == (1, 2, 0)
|
||||
assert uc.parse_version("1") == (1, 0, 0)
|
||||
assert uc.parse_version("invalid") == (0, 0, 0)
|
||||
print("PASS: parse_version")
|
||||
|
||||
|
||||
def test_classify_update_patch():
|
||||
result = uc.classify_update("1.2.3", "1.2.4")
|
||||
assert result is not None
|
||||
assert result['update_type'] == 'patch'
|
||||
assert result['breaking_change'] is False
|
||||
assert result['severity'] == 'low'
|
||||
print("PASS: classify_update_patch")
|
||||
|
||||
|
||||
def test_classify_update_minor():
|
||||
result = uc.classify_update("1.2.3", "1.3.0")
|
||||
assert result is not None
|
||||
assert result['update_type'] == 'minor'
|
||||
assert result['breaking_change'] is False
|
||||
assert result['severity'] == 'medium'
|
||||
print("PASS: classify_update_minor")
|
||||
|
||||
|
||||
def test_classify_update_major():
|
||||
result = uc.classify_update("1.2.3", "2.0.0")
|
||||
assert result is not None
|
||||
assert result['update_type'] == 'major'
|
||||
assert result['breaking_change'] is True
|
||||
assert result['severity'] == 'high'
|
||||
print("PASS: classify_update_major")
|
||||
|
||||
|
||||
def test_classify_update_no_change():
|
||||
result = uc.classify_update("1.2.3", "1.2.3")
|
||||
assert result is None
|
||||
print("PASS: classify_update_no_change")
|
||||
|
||||
|
||||
def test_classify_update_multiple_major():
|
||||
result = uc.classify_update("1.0.0", "3.0.0")
|
||||
assert result is not None
|
||||
assert result['update_type'] == 'major'
|
||||
assert result['breaking_change'] is True
|
||||
print("PASS: classify_update_multiple_major")
|
||||
|
||||
|
||||
def test_text_report_format():
|
||||
updates = [{
|
||||
'package': 'requests',
|
||||
'installed': '2.28.0',
|
||||
'latest': '2.31.0',
|
||||
'update_type': 'minor',
|
||||
'breaking_change': False,
|
||||
'severity': 'medium',
|
||||
}]
|
||||
report = uc.generate_text_report(updates)
|
||||
assert 'DEPENDENCY UPDATE REPORT' in report
|
||||
assert 'requests' in report
|
||||
assert '2.28.0' in report
|
||||
assert '2.31.0' in report
|
||||
assert 'MINOR' in report
|
||||
assert 'MEDIUM' in report
|
||||
print("PASS: text_report_format")
|
||||
|
||||
|
||||
def test_text_report_shows_breaking():
|
||||
updates = [{
|
||||
'package': 'flask',
|
||||
'installed': '2.0.0',
|
||||
'latest': '3.0.0',
|
||||
'update_type': 'major',
|
||||
'breaking_change': True,
|
||||
'severity': 'high',
|
||||
}]
|
||||
report = uc.generate_text_report(updates)
|
||||
assert 'BREAKING CHANGE' in report.upper() or '⚠' in report
|
||||
print("PASS: text_report_shows_breaking")
|
||||
|
||||
|
||||
def test_json_report_structure():
|
||||
updates = [
|
||||
{
|
||||
'package': 'pytest',
|
||||
'installed': '8.0.0',
|
||||
'latest': '8.2.0',
|
||||
'update_type': 'minor',
|
||||
'breaking_change': False,
|
||||
'severity': 'medium',
|
||||
},
|
||||
{
|
||||
'package': 'flask',
|
||||
'installed': '2.0.0',
|
||||
'latest': '3.0.0',
|
||||
'update_type': 'major',
|
||||
'breaking_change': True,
|
||||
'severity': 'high',
|
||||
}
|
||||
]
|
||||
report_json = uc.generate_json_report(updates)
|
||||
data = json.loads(report_json)
|
||||
assert 'generated_at' in data
|
||||
assert data['total_updates'] == 2
|
||||
assert 'summary' in data
|
||||
assert data['summary']['major'] == 1
|
||||
assert data['summary']['minor'] == 1
|
||||
assert data['summary']['breaking'] == 1
|
||||
print("PASS: json_report_structure")
|
||||
|
||||
|
||||
def test_no_updates_report():
|
||||
report = uc.generate_text_report([])
|
||||
assert 'up to date' in report.lower() or 'all packages' in report.lower()
|
||||
print("PASS: no_updates_report")
|
||||
|
||||
|
||||
def test_end_to_end_integration():
|
||||
"""End-to-end: check_updates with mocked data produces valid report."""
|
||||
fake_installed = {
|
||||
"test-pkg-old": "1.0.0",
|
||||
"another-pkg": "2.5.3",
|
||||
}
|
||||
|
||||
def fake_get_latest(pkg):
|
||||
if pkg == "test-pkg-old":
|
||||
return "1.2.4"
|
||||
elif pkg == "another-pkg":
|
||||
return "3.0.0"
|
||||
return None
|
||||
|
||||
with patch('update_checker.get_installed_packages', return_value=fake_installed):
|
||||
with patch('update_checker.get_latest_version', side_effect=fake_get_latest):
|
||||
updates = uc.check_updates()
|
||||
|
||||
assert len(updates) == 2
|
||||
|
||||
test_pkg = next(u for u in updates if u['package'] == 'test-pkg-old')
|
||||
assert test_pkg['update_type'] == 'minor'
|
||||
assert test_pkg['breaking_change'] is False
|
||||
|
||||
another = next(u for u in updates if u['package'] == 'another-pkg')
|
||||
assert another['update_type'] == 'major'
|
||||
assert another['breaking_change'] is True
|
||||
|
||||
report = uc.generate_text_report(updates)
|
||||
assert 'DEPENDENCY UPDATE REPORT' in report
|
||||
assert 'MINOR' in report
|
||||
assert 'BREAKING CHANGE' in report.upper()
|
||||
|
||||
print(f"PASS: end_to_end_integration ({len(updates)} updates)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
passed = 0
|
||||
failed = 0
|
||||
tests = [
|
||||
test_parse_version,
|
||||
test_classify_update_patch,
|
||||
test_classify_update_minor,
|
||||
test_classify_update_major,
|
||||
test_classify_update_no_change,
|
||||
test_classify_update_multiple_major,
|
||||
test_text_report_format,
|
||||
test_text_report_shows_breaking,
|
||||
test_json_report_structure,
|
||||
test_no_updates_report,
|
||||
test_end_to_end_integration,
|
||||
]
|
||||
for test_func in tests:
|
||||
try:
|
||||
test_func()
|
||||
passed += 1
|
||||
except AssertionError as e:
|
||||
print(f"FAIL: {test_func.__name__} — {e}")
|
||||
failed += 1
|
||||
except Exception as e:
|
||||
print(f"ERROR: {test_func.__name__} — {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
failed += 1
|
||||
print(f"\n{passed} passed, {failed} failed")
|
||||
sys.exit(0 if failed == 0 else 1)
|
||||
246
scripts/update_checker.py
Normal file
246
scripts/update_checker.py
Normal file
@@ -0,0 +1,246 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
5.3: Update Checker — Compare installed vs latest package versions
|
||||
|
||||
Check if dependencies have newer versions available. Query PyPI for each
|
||||
installed package, compare versions, and generate an update report with
|
||||
major/minor/patch classification and breaking change flags.
|
||||
|
||||
Usage:
|
||||
python3 scripts/update_checker.py
|
||||
python3 scripts/update_checker.py --json
|
||||
python3 scripts/update_checker.py --output updates.md
|
||||
python3 scripts/update_checker.py --package requests,pytest
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
from urllib.request import urlopen
|
||||
from urllib.error import URLError, HTTPError
|
||||
|
||||
|
||||
def get_installed_packages() -> Dict[str, str]:
|
||||
"""Get all installed packages via pip list --format=json."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['pip', 'list', '--format=json'],
|
||||
capture_output=True, text=True, timeout=30
|
||||
)
|
||||
if result.returncode != 0:
|
||||
print(f"Warning: pip list failed: {result.stderr}", file=sys.stderr)
|
||||
return {}
|
||||
packages = json.loads(result.stdout)
|
||||
return {p['name'].lower(): p['version'] for p in packages}
|
||||
except (json.JSONDecodeError, subprocess.TimeoutExpired, KeyError) as e:
|
||||
print(f"Warning: failed to parse pip list: {e}", file=sys.stderr)
|
||||
return {}
|
||||
|
||||
|
||||
def get_latest_version(package_name: str) -> Optional[str]:
|
||||
"""Query PyPI JSON API for the latest version of a package."""
|
||||
url = f"https://pypi.org/pypi/{package_name}/json"
|
||||
try:
|
||||
with urlopen(url, timeout=10) as resp:
|
||||
if resp.status == 200:
|
||||
data = json.loads(resp.read())
|
||||
return data.get('info', {}).get('version')
|
||||
except (URLError, HTTPError, json.JSONDecodeError, TimeoutError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def parse_version(version_str: str) -> Tuple[int, int, int]:
|
||||
"""Parse semantic version string into (major, minor, patch)."""
|
||||
# Strip any extras like dev, post, rc
|
||||
cleaned = version_str.split('.')[0:3]
|
||||
# Pad to 3 parts
|
||||
while len(cleaned) < 3:
|
||||
cleaned.append('0')
|
||||
try:
|
||||
major = int(cleaned[0]) if cleaned[0].isdigit() else 0
|
||||
minor = int(cleaned[1]) if len(cleaned) > 1 and cleaned[1].isdigit() else 0
|
||||
patch = int(cleaned[2]) if len(cleaned) > 2 and cleaned[2].isdigit() else 0
|
||||
return (major, minor, patch)
|
||||
except (ValueError, IndexError):
|
||||
return (0, 0, 0)
|
||||
|
||||
|
||||
def classify_update(installed: str, latest: str) -> Optional[Dict]:
|
||||
"""Determine update type between installed and latest versions."""
|
||||
if not latest:
|
||||
return None
|
||||
|
||||
inst_ver = parse_version(installed)
|
||||
latest_ver = parse_version(latest)
|
||||
|
||||
if inst_ver == latest_ver:
|
||||
return None # Already up to date
|
||||
|
||||
# Calculate delta
|
||||
major_diff = latest_ver[0] - inst_ver[0]
|
||||
minor_diff = latest_ver[1] - inst_ver[1]
|
||||
patch_diff = latest_ver[2] - inst_ver[2]
|
||||
|
||||
# Determine update type
|
||||
if major_diff > 0:
|
||||
update_type = 'major'
|
||||
breaking = True
|
||||
severity = 'high'
|
||||
elif minor_diff > 0:
|
||||
update_type = 'minor'
|
||||
breaking = False
|
||||
severity = 'medium'
|
||||
elif patch_diff > 0:
|
||||
update_type = 'patch'
|
||||
breaking = False
|
||||
severity = 'low'
|
||||
else:
|
||||
# Shouldn't happen but handle weird cases
|
||||
return None
|
||||
|
||||
return {
|
||||
'package': None, # filled by caller
|
||||
'installed': installed,
|
||||
'latest': latest,
|
||||
'update_type': update_type,
|
||||
'breaking_change': breaking,
|
||||
'severity': severity,
|
||||
}
|
||||
|
||||
|
||||
def check_updates(packages: Dict[str, str] = None,
|
||||
filter_packages: List[str] = None) -> List[Dict]:
|
||||
"""
|
||||
Check all installed packages (or filtered subset) for updates.
|
||||
|
||||
Args:
|
||||
packages: Dict of {name: version}. If None, queries pip list.
|
||||
filter_packages: Optional list of package names to check only.
|
||||
|
||||
Returns:
|
||||
List of update report dicts sorted by severity.
|
||||
"""
|
||||
if packages is None:
|
||||
packages = get_installed_packages()
|
||||
|
||||
if filter_packages:
|
||||
packages = {k: v for k, v in packages.items()
|
||||
if k.lower() in [p.lower() for p in filter_packages]}
|
||||
|
||||
updates = []
|
||||
print(f"Checking {len(packages)} packages...", file=sys.stderr)
|
||||
|
||||
for pkg_name, installed_ver in packages.items():
|
||||
latest_ver = get_latest_version(pkg_name)
|
||||
if not latest_ver:
|
||||
continue
|
||||
|
||||
update_info = classify_update(installed_ver, latest_ver)
|
||||
if update_info:
|
||||
update_info['package'] = pkg_name
|
||||
updates.append(update_info)
|
||||
|
||||
# Sort: breaking first, then severity, then package name
|
||||
updates.sort(key=lambda u: (
|
||||
-1 if u['breaking_change'] else 0,
|
||||
{'high': 0, 'medium': 1, 'low': 2}[u['severity']],
|
||||
u['package']
|
||||
))
|
||||
|
||||
return updates
|
||||
|
||||
|
||||
def generate_text_report(updates: List[Dict]) -> str:
|
||||
"""Generate human-readable text report."""
|
||||
lines = []
|
||||
lines.append("=" * 60)
|
||||
lines.append("DEPENDENCY UPDATE REPORT")
|
||||
lines.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
lines.append("=" * 60)
|
||||
lines.append("")
|
||||
|
||||
if not updates:
|
||||
lines.append("✓ All packages are up to date.")
|
||||
return "\n".join(lines)
|
||||
|
||||
lines.append(f"Found {len(updates)} package(s) with available updates:")
|
||||
lines.append("")
|
||||
|
||||
for u in updates:
|
||||
breaking_marker = " ⚠ BREAKING CHANGE" if u['breaking_change'] else ""
|
||||
lines.append(f" {u['package']}:")
|
||||
lines.append(f" Installed: {u['installed']}")
|
||||
lines.append(f" Latest: {u['latest']}")
|
||||
lines.append(f" Update: {u['update_type'].upper()}{breaking_marker}")
|
||||
lines.append(f" Severity: {u['severity'].upper()}")
|
||||
lines.append("")
|
||||
|
||||
lines.append("=" * 60)
|
||||
lines.append("Recommendation: Review breaking changes carefully before upgrading.")
|
||||
lines.append("Consider pinning versions or using a virtual environment.")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def generate_json_report(updates: List[Dict]) -> str:
|
||||
"""Generate JSON report compatible with machine consumption."""
|
||||
report = {
|
||||
'generated_at': datetime.now().isoformat(),
|
||||
'total_updates': len(updates),
|
||||
'updates': updates,
|
||||
'summary': {
|
||||
'major': sum(1 for u in updates if u['update_type'] == 'major'),
|
||||
'minor': sum(1 for u in updates if u['update_type'] == 'minor'),
|
||||
'patch': sum(1 for u in updates if u['update_type'] == 'patch'),
|
||||
'breaking': sum(1 for u in updates if u['breaking_change']),
|
||||
}
|
||||
}
|
||||
return json.dumps(report, indent=2)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Check dependencies for available updates"
|
||||
)
|
||||
parser.add_argument(
|
||||
'--json', action='store_true',
|
||||
help='Output JSON report for machine consumption'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--output', '-o', type=str,
|
||||
help='Write report to file instead of stdout'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--package', '-p', type=str,
|
||||
help='Comma-separated list of specific packages to check'
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
# Build filter list if provided
|
||||
filter_list = None
|
||||
if args.package:
|
||||
filter_list = [p.strip() for p in args.package.split(',') if p.strip()]
|
||||
|
||||
# Run checks
|
||||
updates = check_updates(filter_packages=filter_list)
|
||||
|
||||
# Generate report
|
||||
if args.json:
|
||||
report = generate_json_report(updates)
|
||||
else:
|
||||
report = generate_text_report(updates)
|
||||
|
||||
# Output
|
||||
if args.output:
|
||||
Path(args.output).write_text(report)
|
||||
print(f"Report written to {args.output}", file=sys.stderr)
|
||||
else:
|
||||
print(report)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,53 +0,0 @@
|
||||
"""Smoke test for import_graph — verifies it works on a real Python codebase.
|
||||
|
||||
We run import_graph.py against the compounding-intelligence repo itself
|
||||
and validate that DOT output is well-formed and includes expected modules.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1] # tests/ → repo root
|
||||
|
||||
|
||||
def test_import_graph_creates_dot():
|
||||
"""import_graph.py produces valid DOT output for this repo."""
|
||||
script = REPO_ROOT / 'scripts' / 'import_graph.py'
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(script), str(REPO_ROOT), '--output', '/dev/null'],
|
||||
capture_output=True, text=True, timeout=30
|
||||
)
|
||||
assert result.returncode == 0, f"script failed: {result.stderr}"
|
||||
# Should have printed a summary
|
||||
assert ' modules,' in result.stderr or 'Summary:' in result.stderr
|
||||
|
||||
|
||||
def test_import_graph_excludes_site_packages():
|
||||
"""import_graph.py does not crash on unparseable files or external deps."""
|
||||
script = REPO_ROOT / 'scripts' / 'import_graph.py'
|
||||
# Run on a tiny fixture if available, else just ensure it exits cleanly
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(script), str(REPO_ROOT / 'scripts')],
|
||||
capture_output=True, text=True, timeout=30
|
||||
)
|
||||
assert result.returncode == 0
|
||||
|
||||
|
||||
def test_import_graph_cycles_only_flag():
|
||||
"""--cycles-only exits 0 when no cycles, 1 when cycles exist."""
|
||||
script = REPO_ROOT / 'scripts' / 'import_graph.py'
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(script), str(REPO_ROOT / 'scripts'), '--cycles-only'],
|
||||
capture_output=True, text=True, timeout=30
|
||||
)
|
||||
# The scripts/ dir should have no cycles — exit 0
|
||||
assert result.returncode in (0, 1), "unexpected return code"
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Run inline
|
||||
test_import_graph_creates_dot()
|
||||
test_import_graph_excludes_site_packages()
|
||||
test_import_graph_cycles_only_flag()
|
||||
print("All import_graph smoke tests passed.")
|
||||
212
tests/test_update_checker.py
Normal file
212
tests/test_update_checker.py
Normal file
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Tests for update_checker.py — 5.3: Update Checker
|
||||
|
||||
Acceptance criteria verified:
|
||||
✓ Compares installed vs latest
|
||||
✓ Reports major/minor/patch updates
|
||||
✓ Flags breaking changes (major)
|
||||
✓ Output: update report
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
# Add scripts dir to path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts"))
|
||||
|
||||
import update_checker as uc
|
||||
|
||||
|
||||
def test_parse_version():
|
||||
assert uc.parse_version("1.2.3") == (1, 2, 3)
|
||||
assert uc.parse_version("2.0.0") == (2, 0, 0)
|
||||
assert uc.parse_version("0.9.0") == (0, 9, 0)
|
||||
assert uc.parse_version("1.2") == (1, 2, 0)
|
||||
assert uc.parse_version("1") == (1, 0, 0)
|
||||
assert uc.parse_version("invalid") == (0, 0, 0)
|
||||
print("PASS: parse_version")
|
||||
|
||||
|
||||
def test_classify_update_patch():
|
||||
result = uc.classify_update("1.2.3", "1.2.4")
|
||||
assert result is not None
|
||||
assert result['update_type'] == 'patch'
|
||||
assert result['breaking_change'] is False
|
||||
assert result['severity'] == 'low'
|
||||
print("PASS: classify_update_patch")
|
||||
|
||||
|
||||
def test_classify_update_minor():
|
||||
result = uc.classify_update("1.2.3", "1.3.0")
|
||||
assert result is not None
|
||||
assert result['update_type'] == 'minor'
|
||||
assert result['breaking_change'] is False
|
||||
assert result['severity'] == 'medium'
|
||||
print("PASS: classify_update_minor")
|
||||
|
||||
|
||||
def test_classify_update_major():
|
||||
result = uc.classify_update("1.2.3", "2.0.0")
|
||||
assert result is not None
|
||||
assert result['update_type'] == 'major'
|
||||
assert result['breaking_change'] is True
|
||||
assert result['severity'] == 'high'
|
||||
print("PASS: classify_update_major")
|
||||
|
||||
|
||||
def test_classify_update_no_change():
|
||||
result = uc.classify_update("1.2.3", "1.2.3")
|
||||
assert result is None
|
||||
print("PASS: classify_update_no_change")
|
||||
|
||||
|
||||
def test_classify_update_multiple_major():
|
||||
result = uc.classify_update("1.0.0", "3.0.0")
|
||||
assert result is not None
|
||||
assert result['update_type'] == 'major'
|
||||
assert result['breaking_change'] is True
|
||||
print("PASS: classify_update_multiple_major")
|
||||
|
||||
|
||||
def test_text_report_format():
|
||||
updates = [{
|
||||
'package': 'requests',
|
||||
'installed': '2.28.0',
|
||||
'latest': '2.31.0',
|
||||
'update_type': 'minor',
|
||||
'breaking_change': False,
|
||||
'severity': 'medium',
|
||||
}]
|
||||
report = uc.generate_text_report(updates)
|
||||
assert 'DEPENDENCY UPDATE REPORT' in report
|
||||
assert 'requests' in report
|
||||
assert '2.28.0' in report
|
||||
assert '2.31.0' in report
|
||||
assert 'MINOR' in report
|
||||
assert 'MEDIUM' in report
|
||||
print("PASS: text_report_format")
|
||||
|
||||
|
||||
def test_text_report_shows_breaking():
|
||||
updates = [{
|
||||
'package': 'flask',
|
||||
'installed': '2.0.0',
|
||||
'latest': '3.0.0',
|
||||
'update_type': 'major',
|
||||
'breaking_change': True,
|
||||
'severity': 'high',
|
||||
}]
|
||||
report = uc.generate_text_report(updates)
|
||||
assert 'BREAKING CHANGE' in report.upper() or '⚠' in report
|
||||
print("PASS: text_report_shows_breaking")
|
||||
|
||||
|
||||
def test_json_report_structure():
|
||||
updates = [
|
||||
{
|
||||
'package': 'pytest',
|
||||
'installed': '8.0.0',
|
||||
'latest': '8.2.0',
|
||||
'update_type': 'minor',
|
||||
'breaking_change': False,
|
||||
'severity': 'medium',
|
||||
},
|
||||
{
|
||||
'package': 'flask',
|
||||
'installed': '2.0.0',
|
||||
'latest': '3.0.0',
|
||||
'update_type': 'major',
|
||||
'breaking_change': True,
|
||||
'severity': 'high',
|
||||
}
|
||||
]
|
||||
report_json = uc.generate_json_report(updates)
|
||||
data = json.loads(report_json)
|
||||
assert 'generated_at' in data
|
||||
assert data['total_updates'] == 2
|
||||
assert 'summary' in data
|
||||
assert data['summary']['major'] == 1
|
||||
assert data['summary']['minor'] == 1
|
||||
assert data['summary']['breaking'] == 1
|
||||
print("PASS: json_report_structure")
|
||||
|
||||
|
||||
def test_no_updates_report():
|
||||
report = uc.generate_text_report([])
|
||||
assert 'up to date' in report.lower() or 'all packages' in report.lower()
|
||||
print("PASS: no_updates_report")
|
||||
|
||||
|
||||
def test_end_to_end_integration():
|
||||
"""End-to-end: check_updates with mocked data produces valid report."""
|
||||
fake_installed = {
|
||||
"test-pkg-old": "1.0.0",
|
||||
"another-pkg": "2.5.3",
|
||||
}
|
||||
|
||||
def fake_get_latest(pkg):
|
||||
if pkg == "test-pkg-old":
|
||||
return "1.2.4"
|
||||
elif pkg == "another-pkg":
|
||||
return "3.0.0"
|
||||
return None
|
||||
|
||||
with patch('update_checker.get_installed_packages', return_value=fake_installed):
|
||||
with patch('update_checker.get_latest_version', side_effect=fake_get_latest):
|
||||
updates = uc.check_updates()
|
||||
|
||||
assert len(updates) == 2
|
||||
|
||||
test_pkg = next(u for u in updates if u['package'] == 'test-pkg-old')
|
||||
assert test_pkg['update_type'] == 'minor'
|
||||
assert test_pkg['breaking_change'] is False
|
||||
|
||||
another = next(u for u in updates if u['package'] == 'another-pkg')
|
||||
assert another['update_type'] == 'major'
|
||||
assert another['breaking_change'] is True
|
||||
|
||||
report = uc.generate_text_report(updates)
|
||||
assert 'DEPENDENCY UPDATE REPORT' in report
|
||||
assert 'MINOR' in report
|
||||
assert 'BREAKING CHANGE' in report.upper()
|
||||
|
||||
print(f"PASS: end_to_end_integration ({len(updates)} updates)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
passed = 0
|
||||
failed = 0
|
||||
tests = [
|
||||
test_parse_version,
|
||||
test_classify_update_patch,
|
||||
test_classify_update_minor,
|
||||
test_classify_update_major,
|
||||
test_classify_update_no_change,
|
||||
test_classify_update_multiple_major,
|
||||
test_text_report_format,
|
||||
test_text_report_shows_breaking,
|
||||
test_json_report_structure,
|
||||
test_no_updates_report,
|
||||
test_end_to_end_integration,
|
||||
]
|
||||
for test_func in tests:
|
||||
try:
|
||||
test_func()
|
||||
passed += 1
|
||||
except AssertionError as e:
|
||||
print(f"FAIL: {test_func.__name__} — {e}")
|
||||
failed += 1
|
||||
except Exception as e:
|
||||
print(f"ERROR: {test_func.__name__} — {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
failed += 1
|
||||
print(f"\n{passed} passed, {failed} failed")
|
||||
sys.exit(0 if failed == 0 else 1)
|
||||
Reference in New Issue
Block a user