pyupcheck 0.4.0__tar.gz → 0.4.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {pyupcheck-0.4.0/pyupcheck.egg-info → pyupcheck-0.4.2}/PKG-INFO +1 -1
  2. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/depshift/__init__.py +1 -1
  3. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/depshift/apisurface.py +1 -1
  4. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/depshift/cli.py +30 -6
  5. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/depshift/config.py +1 -1
  6. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/depshift/precise.py +1 -1
  7. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/depshift/scanner.py +1 -2
  8. pyupcheck-0.4.2/depshift/welcome.py +150 -0
  9. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/pyproject.toml +1 -1
  10. {pyupcheck-0.4.0 → pyupcheck-0.4.2/pyupcheck.egg-info}/PKG-INFO +1 -1
  11. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/pyupcheck.egg-info/SOURCES.txt +5 -1
  12. pyupcheck-0.4.2/tests/test_analyzer.py +104 -0
  13. pyupcheck-0.4.2/tests/test_apisurface.py +134 -0
  14. pyupcheck-0.4.2/tests/test_deps.py +159 -0
  15. pyupcheck-0.4.2/tests/test_scanner.py +155 -0
  16. pyupcheck-0.4.0/depshift/welcome.py +0 -36
  17. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/LICENSE +0 -0
  18. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/README.md +0 -0
  19. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/depshift/analyzer.py +0 -0
  20. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/depshift/cache.py +0 -0
  21. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/depshift/changelog.py +0 -0
  22. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/depshift/deps.py +0 -0
  23. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/depshift/report.py +0 -0
  24. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/pyupcheck.egg-info/dependency_links.txt +0 -0
  25. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/pyupcheck.egg-info/entry_points.txt +0 -0
  26. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/pyupcheck.egg-info/requires.txt +0 -0
  27. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/pyupcheck.egg-info/top_level.txt +0 -0
  28. {pyupcheck-0.4.0 → pyupcheck-0.4.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyupcheck
3
- Version: 0.4.0
3
+ Version: 0.4.2
4
4
  Summary: Check if upgrading a Python dependency will break your code
5
5
  Author: AgbaDev
6
6
  License-Expression: MIT
@@ -1,3 +1,3 @@
1
1
  """depshift - Check if upgrading a Python dependency will break your code."""
2
2
 
3
- __version__ = "0.4.0"
3
+ __version__ = "0.4.2"
@@ -8,7 +8,7 @@ what was removed, what changed signature, what parameters disappeared.
8
8
 
9
9
  import ast
10
10
  import io
11
- import os
11
+
12
12
  import tarfile
13
13
  import zipfile
14
14
  from dataclasses import dataclass, field
@@ -133,6 +133,9 @@ def _run_single_check(package: str, target_version: Optional[str], directory: st
133
133
  existing_keys = {(r.usage.file, r.usage.line, r.usage.attr_chain) for r in risks}
134
134
  for pr in precise:
135
135
  key = (pr.usage.file, pr.usage.line, pr.usage.attr_chain)
136
+ if key in existing_keys:
137
+ continue # changelog already flagged this exact usage
138
+ existing_keys.add(key)
136
139
  precise_findings.append({
137
140
  "file": pr.usage.file, "line": pr.usage.line,
138
141
  "code": pr.usage.code, "api": pr.usage.attr_chain,
@@ -243,16 +246,16 @@ def _print_terminal_result(r: dict, quiet: bool):
243
246
  @click.pass_context
244
247
  def main(ctx):
245
248
  """pyupcheck - Check if upgrading a Python dependency will break your code."""
246
- if ctx.invoked_subcommand is not None:
249
+ if ctx.invoked_subcommand is not None and ctx.invoked_subcommand != "banner":
247
250
  from depshift.welcome import show_if_first_run
248
251
  show_if_first_run(console)
249
252
 
250
253
 
251
254
  @main.command("banner")
252
- def show_banner():
253
- """Show the pyupcheck banner."""
254
- from depshift.welcome import BANNER
255
- console.print(BANNER)
255
+ def show_banner_cmd():
256
+ """Show the pyupcheck banner with live version info."""
257
+ from depshift.welcome import show_banner
258
+ show_banner(console)
256
259
 
257
260
 
258
261
  # ── check ─────────────────────────────────────────────────────────────────────
@@ -481,7 +484,7 @@ def fix(directory, dry_run, no_cache):
481
484
  except OSError as e:
482
485
  console.print(f"[red]Could not write {req_path}:[/] {e}")
483
486
 
484
- console.print(f"\n[green]Done.[/] Run [bold]pip install -r requirements.txt[/] to apply.")
487
+ console.print("\n[green]Done.[/] Run [bold]pip install -r requirements.txt[/] to apply.")
485
488
 
486
489
 
487
490
  # ── ci-setup ──────────────────────────────────────────────────────────────────
@@ -639,6 +642,27 @@ def diff(package, from_version, to_version, github_token, no_cache, since):
639
642
  if no_cache:
640
643
  cache_mod.disable_cache()
641
644
 
645
+ # validate versions are real and parseable before doing any work
646
+ from packaging.version import Version, InvalidVersion
647
+ for label, v in (("from", from_version), ("to", to_version)):
648
+ try:
649
+ Version(v)
650
+ except InvalidVersion:
651
+ console.print(f"[red]Error:[/] '{v}' is not a valid version string ({label}_version).")
652
+ sys.exit(2)
653
+
654
+ try:
655
+ available = set(get_available_versions(package))
656
+ except Exception as e:
657
+ console.print(f"[red]Error:[/] could not fetch {package} from PyPI: {e}")
658
+ sys.exit(2)
659
+
660
+ for label, v in (("from", from_version), ("to", to_version)):
661
+ if v not in available:
662
+ console.print(f"[red]Error:[/] {package} {v} not found on PyPI ({label}_version). "
663
+ f"Run [bold]pyupcheck versions {package}[/] to see available versions.")
664
+ sys.exit(2)
665
+
642
666
  with console.status(f"Fetching changes for [bold]{package}[/] {from_version} -> {to_version}..."):
643
667
  try:
644
668
  changes = get_changes_between(package, from_version, to_version, github_token=github_token)
@@ -2,7 +2,7 @@
2
2
 
3
3
  import os
4
4
  from dataclasses import dataclass, field
5
- from typing import List, Set
5
+ from typing import Set
6
6
 
7
7
  try:
8
8
  import tomllib
@@ -6,7 +6,7 @@ arguments you pass, so it can flag a removed parameter you actually use.
6
6
  """
7
7
 
8
8
  from dataclasses import dataclass
9
- from typing import List, Optional
9
+ from typing import List
10
10
 
11
11
  from depshift.scanner import Usage
12
12
  from depshift.apisurface import APIChange
@@ -2,8 +2,7 @@
2
2
 
3
3
  import ast
4
4
  import os
5
- from dataclasses import dataclass, field
6
- from pathlib import Path
5
+ from dataclasses import dataclass
7
6
  from typing import List, Optional, Set
8
7
 
9
8
 
@@ -0,0 +1,150 @@
1
+ """Live animated banner — fetches real data from PyPI on every run."""
2
+
3
+ import time
4
+ from pathlib import Path
5
+ from depshift import __version__
6
+
7
+ MARKER = Path.home() / ".cache" / "pyupcheck" / ".welcomed"
8
+
9
+ ASCII_LOGO = """\
10
+ ██████╗ ██╗ ██╗██╗ ██╗██████╗ ██████╗██╗ ██╗███████╗ ██████╗██╗ ██╗
11
+ ██╔══██╗╚██╗ ██╔╝██║ ██║██╔══██╗██╔════╝██║ ██║██╔════╝██╔════╝██║ ██╔╝
12
+ ██████╔╝ ╚████╔╝ ██║ ██║██████╔╝██║ ███████║█████╗ ██║ █████╔╝
13
+ ██╔═══╝ ╚██╔╝ ██║ ██║██╔═══╝ ██║ ██╔══██║██╔══╝ ██║ ██╔═██╗
14
+ ██║ ██║ ╚██████╔╝██║ ╚██████╗██║ ██║███████╗╚██████╗██║ ██╗
15
+ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═════╝╚═╝ ╚═╝"""
16
+
17
+
18
+ def _fetch_pypi_data() -> dict:
19
+ """Fetch live pyupcheck data from PyPI. Returns dict with version, releases, changelog."""
20
+ try:
21
+ import httpx
22
+ resp = httpx.get("https://pypi.org/pypi/pyupcheck/json", timeout=5)
23
+ resp.raise_for_status()
24
+ data = resp.json()
25
+ info = data.get("info", {})
26
+ releases = data.get("releases", {})
27
+
28
+ from packaging.version import Version, InvalidVersion
29
+ parsed = []
30
+ for v in releases:
31
+ try:
32
+ parsed.append(Version(v))
33
+ except InvalidVersion:
34
+ pass
35
+ parsed.sort(reverse=True)
36
+
37
+ # build release list with upload dates
38
+ release_list = []
39
+ for v in parsed[:6]:
40
+ vs = str(v)
41
+ files = releases.get(vs, [])
42
+ date = ""
43
+ for f in files:
44
+ upload = f.get("upload_time", "")
45
+ if upload:
46
+ date = upload[:10]
47
+ break
48
+ release_list.append({"version": vs, "date": date})
49
+
50
+ return {
51
+ "latest": info.get("version", __version__),
52
+ "summary": info.get("summary", ""),
53
+ "releases": release_list,
54
+ }
55
+ except Exception:
56
+ return {"latest": __version__, "summary": "", "releases": []}
57
+
58
+
59
+ def _type_out(console, text: str, style: str = "", delay: float = 0.018):
60
+ """Print text character by character with a typing effect."""
61
+ import sys
62
+ for ch in text:
63
+ sys.stdout.write(ch)
64
+ sys.stdout.flush()
65
+ time.sleep(delay + (0.04 if ch in ".,!:>" else 0))
66
+ sys.stdout.write("\n")
67
+ sys.stdout.flush()
68
+
69
+
70
+ def _print_banner(console):
71
+ # logo — print in bold cyan
72
+ console.print(f"\n[bold cyan]{ASCII_LOGO}[/]\n")
73
+
74
+ # tagline typed out
75
+ _type_out(console, " Know if a dependency upgrade will break your code before you run it.", delay=0.012)
76
+ console.print()
77
+
78
+ # live fetch with spinner
79
+ with console.status("[dim] Connecting to PyPI...[/]", spinner="dots2"):
80
+ time.sleep(0.3)
81
+ data = _fetch_pypi_data()
82
+
83
+ latest = data["latest"]
84
+ releases = data["releases"]
85
+ installed = __version__
86
+ up_to_date = installed == latest
87
+
88
+ # installed vs latest
89
+ _type_out(console, f" Installed {installed}", delay=0.02)
90
+ time.sleep(0.15)
91
+
92
+ if up_to_date:
93
+ _type_out(console, f" Latest {latest} (you are up to date)", delay=0.02)
94
+ else:
95
+ _type_out(console, f" Latest {latest} <- upgrade available", delay=0.02)
96
+
97
+ time.sleep(0.1)
98
+ _type_out(console, " PyPI https://pypi.org/project/pyupcheck", delay=0.015)
99
+ _type_out(console, " GitHub https://github.com/Astronomox/pyupcheck-Astronomox", delay=0.015)
100
+ _type_out(console, " Author AgbaDev (Astronomox)", delay=0.02)
101
+ console.print()
102
+
103
+ # release history streamed in
104
+ if releases:
105
+ _type_out(console, " Fetching release history...", delay=0.02)
106
+ time.sleep(0.4)
107
+
108
+ for r in releases:
109
+ v = r["version"]
110
+ d = r["date"]
111
+ is_latest = v == latest
112
+ is_installed = v == installed
113
+
114
+ tag = ""
115
+ if is_latest and is_installed:
116
+ tag = " [latest + installed]"
117
+ elif is_latest:
118
+ tag = " [latest]"
119
+ elif is_installed:
120
+ tag = " [installed]"
121
+
122
+ bullet = ">" if is_latest else " "
123
+ line = f" {bullet} v{v:<10} {d}{tag}"
124
+ _type_out(console, line, delay=0.008)
125
+ time.sleep(0.06)
126
+
127
+ console.print()
128
+
129
+ if not up_to_date:
130
+ _type_out(console, " Run: pip install pyupcheck --upgrade", delay=0.018)
131
+ console.print()
132
+
133
+ _type_out(console, " Run: pyupcheck --help to get started.", delay=0.018)
134
+ console.print()
135
+
136
+
137
+ def show_if_first_run(console):
138
+ if MARKER.exists():
139
+ return
140
+ try:
141
+ MARKER.parent.mkdir(parents=True, exist_ok=True)
142
+ MARKER.touch()
143
+ except Exception:
144
+ pass
145
+ _print_banner(console)
146
+
147
+
148
+ def show_banner(console):
149
+ """Always show the live banner — used by pyupcheck banner."""
150
+ _print_banner(console)
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pyupcheck"
7
- version = "0.4.0"
7
+ version = "0.4.2"
8
8
  description = "Check if upgrading a Python dependency will break your code"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyupcheck
3
- Version: 0.4.0
3
+ Version: 0.4.2
4
4
  Summary: Check if upgrading a Python dependency will break your code
5
5
  Author: AgbaDev
6
6
  License-Expression: MIT
@@ -18,4 +18,8 @@ pyupcheck.egg-info/SOURCES.txt
18
18
  pyupcheck.egg-info/dependency_links.txt
19
19
  pyupcheck.egg-info/entry_points.txt
20
20
  pyupcheck.egg-info/requires.txt
21
- pyupcheck.egg-info/top_level.txt
21
+ pyupcheck.egg-info/top_level.txt
22
+ tests/test_analyzer.py
23
+ tests/test_apisurface.py
24
+ tests/test_deps.py
25
+ tests/test_scanner.py
@@ -0,0 +1,104 @@
1
+ """Tests for the changelog-based analyzer."""
2
+
3
+ import pytest
4
+
5
+ from depshift.scanner import Usage
6
+ from depshift.changelog import ChangeEntry
7
+ from depshift.analyzer import analyze, normalize_api, match_usage_to_change
8
+
9
+
10
+ def make_usage(attr_chain: str, usage_type: str = "function_call") -> Usage:
11
+ return Usage(
12
+ file="test.py", line=1, code=f"{attr_chain}()",
13
+ attr_chain=attr_chain, usage_type=usage_type,
14
+ )
15
+
16
+
17
+ def make_change(kind: str, api: str, version: str = "2.0") -> ChangeEntry:
18
+ return ChangeEntry(
19
+ kind=kind, api=api,
20
+ description=f"{kind} {api}",
21
+ version=version,
22
+ )
23
+
24
+
25
+ # ── normalize_api ─────────────────────────────────────────────────────────────
26
+
27
+ def test_normalize_api_strips_parens():
28
+ assert normalize_api("requests.get()", "requests") == "requests.get"
29
+
30
+
31
+ def test_normalize_api_lowercases():
32
+ assert normalize_api("requests.get", "requests") == "requests.get"
33
+
34
+
35
+ def test_normalize_api_prepends_package():
36
+ result = normalize_api("get", "requests")
37
+ assert result == "requests.get"
38
+
39
+
40
+ # ── match_usage_to_change ─────────────────────────────────────────────────────
41
+
42
+ def test_direct_match_removed():
43
+ usage = make_usage("requests.get")
44
+ change = make_change("removed", "requests.get")
45
+ risk = match_usage_to_change(usage, change, "requests")
46
+ assert risk is not None
47
+ assert risk.severity == "breaking"
48
+
49
+
50
+ def test_direct_match_deprecated():
51
+ usage = make_usage("requests.packages")
52
+ change = make_change("deprecated", "requests.packages")
53
+ risk = match_usage_to_change(usage, change, "requests")
54
+ assert risk is not None
55
+ assert risk.severity == "deprecated"
56
+
57
+
58
+ def test_no_match_different_api():
59
+ usage = make_usage("requests.get")
60
+ change = make_change("removed", "requests.post")
61
+ risk = match_usage_to_change(usage, change, "requests")
62
+ assert risk is None
63
+
64
+
65
+ def test_child_match():
66
+ usage = make_usage("requests.packages.urllib3")
67
+ change = make_change("removed", "requests.packages")
68
+ risk = match_usage_to_change(usage, change, "requests")
69
+ assert risk is not None
70
+
71
+
72
+ # ── analyze ───────────────────────────────────────────────────────────────────
73
+
74
+ def test_analyze_returns_risks_and_safe():
75
+ usages = [
76
+ make_usage("requests.get"),
77
+ make_usage("requests.post"),
78
+ make_usage("requests.Session"),
79
+ ]
80
+ changes = [
81
+ make_change("removed", "requests.get"),
82
+ ]
83
+ risks, safe = analyze(usages, changes, "requests")
84
+ assert len(risks) == 1
85
+ assert risks[0].usage.attr_chain == "requests.get"
86
+ assert len(safe) == 2
87
+
88
+
89
+ def test_analyze_no_changes_all_safe():
90
+ usages = [make_usage("requests.get"), make_usage("requests.post")]
91
+ risks, safe = analyze(usages, [], "requests")
92
+ assert len(risks) == 0
93
+ assert len(safe) == 2
94
+
95
+
96
+ def test_analyze_sort_order():
97
+ usages = [make_usage("flask.deprecated_thing"), make_usage("flask.removed_thing")]
98
+ changes = [
99
+ make_change("deprecated", "flask.deprecated_thing"),
100
+ make_change("removed", "flask.removed_thing"),
101
+ ]
102
+ risks, _ = analyze(usages, changes, "flask")
103
+ # breaking should come first
104
+ assert risks[0].severity == "breaking"
@@ -0,0 +1,134 @@
1
+ """Tests for the API surface extractor and differ."""
2
+
3
+ import ast
4
+ import pytest
5
+
6
+ from depshift.apisurface import (
7
+ APISurface, FuncSig, _SurfaceVisitor, _is_public_api,
8
+ diff_surfaces,
9
+ )
10
+
11
+
12
+ # ── _is_public_api ────────────────────────────────────────────────────────────
13
+
14
+ def test_public_module_is_public():
15
+ assert _is_public_api("requests.auth") is True
16
+
17
+
18
+ def test_private_module_is_not_public():
19
+ assert _is_public_api("requests._compat") is False
20
+
21
+
22
+ def test_dunder_is_public():
23
+ assert _is_public_api("requests.__version__") is True
24
+
25
+
26
+ def test_nested_private_not_public():
27
+ assert _is_public_api("pkg.sub._internal.func") is False
28
+
29
+
30
+ # ── _SurfaceVisitor ───────────────────────────────────────────────────────────
31
+
32
+ def parse_visitor(source: str, module="pkg") -> _SurfaceVisitor:
33
+ tree = ast.parse(source)
34
+ v = _SurfaceVisitor(module)
35
+ v.visit(tree)
36
+ return v
37
+
38
+
39
+ def test_visitor_extracts_function():
40
+ v = parse_visitor("def get(url, verify=True): pass")
41
+ assert "get" in v.functions
42
+ assert "url" in v.functions["get"].params
43
+ assert "verify" in v.functions["get"].params
44
+
45
+
46
+ def test_visitor_extracts_class():
47
+ v = parse_visitor("class Session: pass")
48
+ assert "Session" in v.classes
49
+
50
+
51
+ def test_visitor_extracts_method():
52
+ v = parse_visitor("class Session:\n def get(self, url): pass")
53
+ assert "Session" in v.classes
54
+ assert "Session.get" in v.functions
55
+
56
+
57
+ def test_visitor_skips_private():
58
+ v = parse_visitor("def _internal(): pass\ndef public(): pass")
59
+ assert "_internal" not in v.functions
60
+ assert "public" in v.functions
61
+
62
+
63
+ def test_visitor_detects_async():
64
+ v = parse_visitor("async def fetch(url): pass")
65
+ assert v.functions["fetch"].is_async is True
66
+
67
+
68
+ def test_visitor_detects_varargs():
69
+ v = parse_visitor("def func(*args): pass")
70
+ assert v.functions["func"].has_varargs is True
71
+
72
+
73
+ def test_visitor_detects_kwargs():
74
+ v = parse_visitor("def func(**kw): pass")
75
+ assert v.functions["func"].has_kwargs is True
76
+
77
+
78
+ # ── diff_surfaces ─────────────────────────────────────────────────────────────
79
+
80
+ def make_surface(version: str, funcs: dict, modules=None, classes=None) -> APISurface:
81
+ s = APISurface(version=version)
82
+ s.modules = set(modules or ["pkg"])
83
+ s.classes = set(classes or [])
84
+ for name, params in funcs.items():
85
+ s.functions[name] = FuncSig(name=name, params=params)
86
+ return s
87
+
88
+
89
+ def test_diff_removed_function():
90
+ old = make_surface("1.0", {"pkg.get": ["url", "verify"]})
91
+ new = make_surface("2.0", {})
92
+ changes = diff_surfaces(old, new)
93
+ kinds = [c.kind for c in changes]
94
+ assert "removed_function" in kinds
95
+
96
+
97
+ def test_diff_removed_param():
98
+ old = make_surface("1.0", {"pkg.get": ["url", "verify"]})
99
+ new = make_surface("2.0", {"pkg.get": ["url"]})
100
+ changes = diff_surfaces(old, new)
101
+ param_changes = [c for c in changes if c.kind == "removed_param"]
102
+ assert len(param_changes) == 1
103
+ assert param_changes[0].param == "verify"
104
+
105
+
106
+ def test_diff_no_change():
107
+ old = make_surface("1.0", {"pkg.get": ["url"]})
108
+ new = make_surface("2.0", {"pkg.get": ["url"]})
109
+ changes = diff_surfaces(old, new)
110
+ assert len(changes) == 0
111
+
112
+
113
+ def test_diff_kwargs_accept_forgives_param_removal():
114
+ old = make_surface("1.0", {"pkg.get": ["url", "verify"]})
115
+ s = make_surface("2.0", {"pkg.get": ["url"]})
116
+ s.functions["pkg.get"].has_kwargs = True
117
+ changes = diff_surfaces(old, s)
118
+ param_changes = [c for c in changes if c.kind == "removed_param"]
119
+ assert len(param_changes) == 0
120
+
121
+
122
+ def test_diff_removed_class():
123
+ old = make_surface("1.0", {}, classes=["pkg.OldClass"])
124
+ new = make_surface("2.0", {})
125
+ changes = diff_surfaces(old, new)
126
+ class_changes = [c for c in changes if c.kind == "removed_class"]
127
+ assert len(class_changes) == 1
128
+
129
+
130
+ def test_diff_skips_private():
131
+ old = make_surface("1.0", {"pkg._internal": ["x"]})
132
+ new = make_surface("2.0", {})
133
+ changes = diff_surfaces(old, new)
134
+ assert len(changes) == 0
@@ -0,0 +1,159 @@
1
+ """Tests for dependency file parsers."""
2
+
3
+ import os
4
+ import tempfile
5
+
6
+ import pytest
7
+
8
+ from depshift.deps import (
9
+ parse_requirements_txt,
10
+ parse_setup_cfg,
11
+ parse_setup_py,
12
+ parse_conda_env,
13
+ discover_dependencies,
14
+ )
15
+
16
+
17
+ def write(path: str, content: str):
18
+ with open(path, "w") as f:
19
+ f.write(content)
20
+
21
+
22
+ # ── requirements.txt ─────────────────────────────────────────────────────────
23
+
24
+ def test_requirements_basic():
25
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
26
+ f.write("flask==2.3.3\nrequests>=2.28\nnumpy\n")
27
+ path = f.name
28
+ try:
29
+ deps = parse_requirements_txt(path)
30
+ names = [d.name for d in deps]
31
+ assert "flask" in names
32
+ assert "requests" in names
33
+ assert "numpy" in names
34
+ finally:
35
+ os.unlink(path)
36
+
37
+
38
+ def test_requirements_pinned_version():
39
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
40
+ f.write("flask==2.3.3\n")
41
+ path = f.name
42
+ try:
43
+ deps = parse_requirements_txt(path)
44
+ flask = next(d for d in deps if d.name == "flask")
45
+ assert flask.pinned_version == "2.3.3"
46
+ finally:
47
+ os.unlink(path)
48
+
49
+
50
+ def test_requirements_skips_comments():
51
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
52
+ f.write("# this is a comment\nflask==2.3.3\n")
53
+ path = f.name
54
+ try:
55
+ deps = parse_requirements_txt(path)
56
+ assert len(deps) == 1
57
+ finally:
58
+ os.unlink(path)
59
+
60
+
61
+ def test_requirements_skips_git_deps():
62
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
63
+ f.write("git+https://github.com/org/repo.git\nflask==2.3.3\n")
64
+ path = f.name
65
+ try:
66
+ deps = parse_requirements_txt(path)
67
+ assert len(deps) == 1
68
+ assert deps[0].name == "flask"
69
+ finally:
70
+ os.unlink(path)
71
+
72
+
73
+ # ── setup.cfg ────────────────────────────────────────────────────────────────
74
+
75
+ def test_setup_cfg_basic():
76
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".cfg", delete=False) as f:
77
+ f.write("[metadata]\nname = myapp\n\n[options]\ninstall_requires =\n flask>=2.0\n requests==2.28.0\n")
78
+ path = f.name
79
+ try:
80
+ deps = parse_setup_cfg(path)
81
+ names = [d.name for d in deps]
82
+ assert "flask" in names
83
+ assert "requests" in names
84
+ finally:
85
+ os.unlink(path)
86
+
87
+
88
+ def test_setup_cfg_pinned():
89
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".cfg", delete=False) as f:
90
+ f.write("[options]\ninstall_requires =\n requests==2.28.0\n")
91
+ path = f.name
92
+ try:
93
+ deps = parse_setup_cfg(path)
94
+ req = next(d for d in deps if d.name == "requests")
95
+ assert req.pinned_version == "2.28.0"
96
+ finally:
97
+ os.unlink(path)
98
+
99
+
100
+ # ── setup.py ─────────────────────────────────────────────────────────────────
101
+
102
+ def test_setup_py_basic():
103
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
104
+ f.write('from setuptools import setup\nsetup(name="myapp", install_requires=["flask>=2.0", "requests"])\n')
105
+ path = f.name
106
+ try:
107
+ deps = parse_setup_py(path)
108
+ names = [d.name for d in deps]
109
+ assert "flask" in names
110
+ assert "requests" in names
111
+ finally:
112
+ os.unlink(path)
113
+
114
+
115
+ # ── conda environment.yml ─────────────────────────────────────────────────────
116
+
117
+ def test_conda_env_basic():
118
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".yml", delete=False) as f:
119
+ f.write("name: myenv\ndependencies:\n - python=3.11\n - pip:\n - flask==2.3.3\n - requests>=2.28\n")
120
+ path = f.name
121
+ try:
122
+ deps = parse_conda_env(path)
123
+ names = [d.name for d in deps]
124
+ assert "flask" in names
125
+ assert "requests" in names
126
+ finally:
127
+ os.unlink(path)
128
+
129
+
130
+ def test_conda_env_pinned():
131
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".yml", delete=False) as f:
132
+ f.write("name: myenv\ndependencies:\n - pip:\n - flask==2.3.3\n")
133
+ path = f.name
134
+ try:
135
+ deps = parse_conda_env(path)
136
+ flask = next(d for d in deps if d.name == "flask")
137
+ assert flask.pinned_version == "2.3.3"
138
+ finally:
139
+ os.unlink(path)
140
+
141
+
142
+ # ── discover_dependencies ─────────────────────────────────────────────────────
143
+
144
+ def test_discover_finds_requirements_txt():
145
+ with tempfile.TemporaryDirectory() as d:
146
+ write(os.path.join(d, "requirements.txt"), "flask==2.3.3\nrequests>=2.28\n")
147
+ deps = discover_dependencies(d)
148
+ names = [dep.name for dep in deps]
149
+ assert "flask" in names
150
+ assert "requests" in names
151
+
152
+
153
+ def test_discover_deduplicates():
154
+ with tempfile.TemporaryDirectory() as d:
155
+ write(os.path.join(d, "requirements.txt"), "flask==2.3.3\n")
156
+ write(os.path.join(d, "requirements-dev.txt"), "flask==2.3.3\npytest\n")
157
+ deps = discover_dependencies(d)
158
+ flask_count = sum(1 for d in deps if d.name == "flask")
159
+ assert flask_count == 1
@@ -0,0 +1,155 @@
1
+ """Tests for the AST-based code scanner."""
2
+
3
+ import os
4
+ import tempfile
5
+ import textwrap
6
+
7
+ import pytest
8
+
9
+ from depshift.scanner import scan_file, scan_directory
10
+
11
+
12
+ def write_temp(code: str, suffix=".py") -> str:
13
+ f = tempfile.NamedTemporaryFile(mode="w", suffix=suffix, delete=False)
14
+ f.write(textwrap.dedent(code))
15
+ f.close()
16
+ return f.name
17
+
18
+
19
+ def cleanup(*paths):
20
+ for p in paths:
21
+ try:
22
+ os.unlink(p)
23
+ except Exception:
24
+ pass
25
+
26
+
27
+ # ── basic imports ────────────────────────────────────────────────────────────
28
+
29
+ def test_detects_simple_import():
30
+ path = write_temp("import requests\n")
31
+ try:
32
+ usages = scan_file(path, "requests")
33
+ apis = [u.attr_chain for u in usages]
34
+ assert "requests" in apis
35
+ finally:
36
+ cleanup(path)
37
+
38
+
39
+ def test_detects_from_import():
40
+ path = write_temp("from requests import get\n")
41
+ try:
42
+ usages = scan_file(path, "requests")
43
+ apis = [u.attr_chain for u in usages]
44
+ assert "requests.get" in apis
45
+ finally:
46
+ cleanup(path)
47
+
48
+
49
+ def test_detects_aliased_import():
50
+ path = write_temp("import requests as req\nreq.get('http://example.com')\n")
51
+ try:
52
+ usages = scan_file(path, "requests")
53
+ apis = [u.attr_chain for u in usages]
54
+ assert any("requests" in a for a in apis)
55
+ finally:
56
+ cleanup(path)
57
+
58
+
59
+ # ── function calls ───────────────────────────────────────────────────────────
60
+
61
+ def test_detects_function_call():
62
+ path = write_temp("import requests\nrequests.get('http://example.com')\n")
63
+ try:
64
+ usages = scan_file(path, "requests")
65
+ calls = [u for u in usages if u.usage_type == "function_call"]
66
+ assert any(u.attr_chain == "requests.get" for u in calls)
67
+ finally:
68
+ cleanup(path)
69
+
70
+
71
+ def test_captures_kwargs():
72
+ path = write_temp("import requests\nrequests.get('http://x.com', verify=False, timeout=5)\n")
73
+ try:
74
+ usages = scan_file(path, "requests")
75
+ call = next(u for u in usages if u.usage_type == "function_call" and "get" in u.attr_chain)
76
+ assert call.kwargs is not None
77
+ assert "verify" in call.kwargs
78
+ assert "timeout" in call.kwargs
79
+ finally:
80
+ cleanup(path)
81
+
82
+
83
+ def test_detects_nested_attr_chain():
84
+ path = write_temp("import requests\nfrom requests.packages import urllib3\n")
85
+ try:
86
+ usages = scan_file(path, "requests")
87
+ apis = [u.attr_chain for u in usages]
88
+ assert any("requests" in a for a in apis)
89
+ finally:
90
+ cleanup(path)
91
+
92
+
93
+ # ── dynamic imports ──────────────────────────────────────────────────────────
94
+
95
+ def test_detects_importlib_import_module():
96
+ path = write_temp("import importlib\nmod = importlib.import_module('flask')\n")
97
+ try:
98
+ usages = scan_file(path, "flask")
99
+ assert any(u.usage_type == "dynamic_import" for u in usages)
100
+ finally:
101
+ cleanup(path)
102
+
103
+
104
+ def test_detects_dunder_import():
105
+ path = write_temp("mod = __import__('flask')\n")
106
+ try:
107
+ usages = scan_file(path, "flask")
108
+ assert any(u.usage_type == "dynamic_import" for u in usages)
109
+ finally:
110
+ cleanup(path)
111
+
112
+
113
+ # ── exclusions ───────────────────────────────────────────────────────────────
114
+
115
+ def test_no_false_positives_other_package():
116
+ path = write_temp("import flask\nflask.Flask(__name__)\n")
117
+ try:
118
+ usages = scan_file(path, "requests")
119
+ assert len(usages) == 0
120
+ finally:
121
+ cleanup(path)
122
+
123
+
124
+ def test_syntax_error_returns_empty():
125
+ path = write_temp("def broken(\n")
126
+ try:
127
+ usages = scan_file(path, "requests")
128
+ assert usages == []
129
+ finally:
130
+ cleanup(path)
131
+
132
+
133
+ # ── directory scan ───────────────────────────────────────────────────────────
134
+
135
+ def test_scan_directory():
136
+ with tempfile.TemporaryDirectory() as d:
137
+ f1 = os.path.join(d, "a.py")
138
+ f2 = os.path.join(d, "b.py")
139
+ with open(f1, "w") as f:
140
+ f.write("import requests\n")
141
+ with open(f2, "w") as f:
142
+ f.write("import flask\n")
143
+ usages = scan_directory(d, "requests")
144
+ assert any("requests" in u.attr_chain for u in usages)
145
+ assert all("flask" not in u.attr_chain for u in usages)
146
+
147
+
148
+ def test_scan_directory_excludes_venv():
149
+ with tempfile.TemporaryDirectory() as d:
150
+ venv_dir = os.path.join(d, ".venv")
151
+ os.makedirs(venv_dir)
152
+ with open(os.path.join(venv_dir, "site.py"), "w") as f:
153
+ f.write("import requests\n")
154
+ usages = scan_directory(d, "requests")
155
+ assert len(usages) == 0
@@ -1,36 +0,0 @@
1
- """Show a welcome banner on first run."""
2
-
3
- from pathlib import Path
4
- from depshift import __version__
5
-
6
- MARKER = Path.home() / ".cache" / "pyupcheck" / ".welcomed"
7
-
8
- BANNER = f"""
9
- [bold cyan] ██████╗ ██╗ ██╗██╗ ██╗██████╗ ██████╗██╗ ██╗███████╗ ██████╗██╗ ██╗[/]
10
- [bold cyan]██╔══██╗╚██╗ ██╔╝██║ ██║██╔══██╗██╔════╝██║ ██║██╔════╝██╔════╝██║ ██╔╝[/]
11
- [bold cyan]██████╔╝ ╚████╔╝ ██║ ██║██████╔╝██║ ███████║█████╗ ██║ █████╔╝ [/]
12
- [bold cyan]██╔═══╝ ╚██╔╝ ██║ ██║██╔═══╝ ██║ ██╔══██║██╔══╝ ██║ ██╔═██╗ [/]
13
- [bold cyan]██║ ██║ ╚██████╔╝██║ ╚██████╗██║ ██║███████╗╚██████╗██║ ██╗[/]
14
- [bold cyan]╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═════╝╚═╝ ╚═╝[/]
15
-
16
- [bold white] Know if a dependency upgrade will break your code before you run it.[/]
17
-
18
- [dim]Version[/] [green]{__version__}[/]
19
- [dim]PyPI[/] [blue]https://pypi.org/project/pyupcheck[/]
20
- [dim]GitHub[/] [blue]https://github.com/Astronomox/pyupcheck-Astronomox[/]
21
- [dim]Author[/] [cyan]AgbaDev (Astronomox)[/]
22
- [dim]Issues[/] [blue]https://github.com/Astronomox/pyupcheck-Astronomox/issues[/]
23
-
24
- [dim] Run [bold]pyupcheck --help[/][dim] to get started.[/]
25
- """
26
-
27
-
28
- def show_if_first_run(console):
29
- if MARKER.exists():
30
- return
31
- try:
32
- MARKER.parent.mkdir(parents=True, exist_ok=True)
33
- MARKER.touch()
34
- except Exception:
35
- pass
36
- console.print(BANNER)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes