Debian Codegraph @

tests/rank_license_usage_test.py

raw
1 #!/usr/bin/env python3
2 # Copyright: 2026, Maximiliano Curia <[email protected]>
3 #
4 # License: ISC
5 # Permission to use, copy, modify, and/or distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 # .
9 # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 # PERFORMANCE OF THIS SOFTWARE.
16
17 """Behaviour tests for scripts/rank-license-usage-codesearch.py.
18
19 The script's filename has hyphens, so it is loaded through the CF0 harness
20 (tests/dcs_helpers.load_script) rather than imported by name. Network is
21 faked with FakeTransport; time.sleep is neutralised so retry/backoff is fast.
22 """
23
24 from __future__ import annotations
25
26 import sys
27 import time
28 import urllib.request
29 from pathlib import Path
30 from typing import Any
31
32 import pytest
33
34 ROOT = Path(__file__).resolve().parent.parent
35 sys.path.insert(0, str(ROOT / "scripts"))
36
37 import dcs_client # noqa: E402
38
39 from tests.dcs_helpers import FakeTransport, load_script, make_http_error # noqa: E402
40
41 RANK = load_script("rank-license-usage-codesearch.py")
42
43 AUTH_FORBIDDEN = 403
44 BAD_REQUEST = 400
45 SERVER_ERROR = 503
46
47
48 @pytest.fixture(autouse=True)
49 def _no_real_sleep(monkeypatch: pytest.MonkeyPatch) -> None:
50 monkeypatch.setattr(time, "sleep", lambda *_: None)
51
52
53 # RANK is a dynamically loaded module, so its symbols are untyped (Any).
54 def _client(cache_dir: Path, *, refresh: bool = True) -> Any:
55 config = dcs_client.DcsConfig(
56 key="key",
57 user_agent="test-agent",
58 cache_dir=cache_dir,
59 sleep=0.0,
60 refresh=refresh,
61 )
62 return dcs_client.DcsClient(config)
63
64
65 def _candidate() -> Any:
66 return RANK.Candidate(label="X", query="q", match_mode="literal")
67
68
69 def _use_transport(monkeypatch: pytest.MonkeyPatch, transport: FakeTransport) -> None:
70 monkeypatch.setattr(urllib.request, "urlopen", transport)
71
72
73 def test_retryable_exhausted_raises_searcherror(
74 tmp_path: Path, monkeypatch: pytest.MonkeyPatch
75 ) -> None:
76 transport = FakeTransport([make_http_error(SERVER_ERROR)], repeat=True)
77 _use_transport(monkeypatch, transport)
78 client = _client(tmp_path)
79 with pytest.raises(dcs_client.SearchError):
80 client.search_live("q", "literal")
81 assert transport.calls == dcs_client.MAX_ATTEMPTS
82
83
84 def test_rank_skips_exhausted_candidate(
85 tmp_path: Path, monkeypatch: pytest.MonkeyPatch
86 ) -> None:
87 transport = FakeTransport([make_http_error(SERVER_ERROR)], repeat=True)
88 _use_transport(monkeypatch, transport)
89 client = _client(tmp_path)
90 # A retry-exhausted candidate is skipped, not fatal: rank() returns [].
91 assert RANK.fetch_results(client.search_live, [_candidate()], progress=True) == []
92
93
94 def test_auth_failure_is_fatal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
95 transport = FakeTransport([make_http_error(AUTH_FORBIDDEN)], repeat=True)
96 _use_transport(monkeypatch, transport)
97 client = _client(tmp_path)
98 with pytest.raises(SystemExit):
99 RANK.fetch_results(
100 client.search_live, [_candidate(), _candidate()], progress=True
101 )
102 # Aborted on the first request rather than retried per candidate.
103 assert transport.calls == 1
104
105
106 def test_bad_query_is_fatal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
107 transport = FakeTransport([make_http_error(BAD_REQUEST)], repeat=True)
108 _use_transport(monkeypatch, transport)
109 client = _client(tmp_path)
110 with pytest.raises(SystemExit):
111 RANK.fetch_results(client.search_live, [_candidate()], progress=True)
112 assert transport.calls == 1
113
114
115 def test_offline_report_uses_cache_only(
116 tmp_path: Path, monkeypatch: pytest.MonkeyPatch
117 ) -> None:
118 # A transport that raises if touched proves search_cached never hits the net.
119 _use_transport(monkeypatch, FakeTransport([]))
120 client = _client(tmp_path, refresh=False)
121 candidate = _candidate()
122 outcome = dcs_client.SearchOutcome(dcs_client.SearchState.HITS, [{"package": "p"}])
123 path = client._cache_path(candidate.query, candidate.match_mode)
124 client._write_cache(path, outcome)
125 results = RANK.fetch_results(client.search_cached, [candidate], progress=False)
126 assert len(results) == 1
127 assert results[0].state is dcs_client.SearchState.HITS
128 assert results[0].packages == 1
129
130
131 def test_progress_reported_only_when_requested(capsys: pytest.CaptureFixture) -> None:
132 # rank() decides on its `progress` argument, not on any client attribute -
133 # a plain function stands in for the search here.
134 def fake_search(query: str, match_mode: str) -> Any:
135 return dcs_client.SearchOutcome(dcs_client.SearchState.HITS, [])
136
137 RANK.fetch_results(fake_search, [_candidate()], progress=True)
138 assert "[1/1]" in capsys.readouterr().err
139 RANK.fetch_results(fake_search, [_candidate()], progress=False)
140 assert "[1/1]" not in capsys.readouterr().err
141
142
143 def test_text_candidates_reports_skips_as_data() -> None:
144 # BSD-3-Clause's distinguishing text collides with its BSD-2-Clause sibling
145 # (and Artistic-1.0 in common-licenses), so it has no distinctive window.
146 candidates, skipped = RANK.text_license_candidates(["BSD-2-Clause", "BSD-3-Clause"])
147 assert skipped == ["BSD-3-Clause"] # returned as data, not printed
148 assert [c.label for c in candidates] == ["BSD-2-clause"]
149
150
151 def test_report_includes_header(capsys: pytest.CaptureFixture) -> None:
152 results = [
153 RANK.Result(_candidate(), state=dcs_client.SearchState.HITS, packages=3, hits=9)
154 ]
155 RANK.report(results, threshold=5)
156 out = capsys.readouterr().out
157 assert "# 1 candidate(s); threshold=5 packages" in out
158
159
160 def test_build_parser_defaults() -> None:
161 ns = RANK.build_parser().parse_args([])
162 assert ns.threshold == RANK.DEFAULT_THRESHOLD
163 assert ns.max_chars is None
164 assert ns.limit == 0
165 assert ns.exceptions is False
166 assert ns.text_mode is False
167
168
169 def test_text_mode_with_exceptions_rejected() -> None:
170 # The conflict is enforced by the parser (mutually-exclusive group),
171 # not a hand-rolled check inside main().
172 with pytest.raises(SystemExit):
173 RANK.build_parser().parse_args(["--text-mode", "--exceptions"])
174
175
176 def test_collect_candidates_signature() -> None:
177 # Called with explicit args, no argparse.Namespace.
178 candidates, skipped = RANK.collect_candidates(
179 ["MIT"], exceptions=False, text_mode=False
180 )
181 assert skipped == []
182 assert [c.label for c in candidates] == ["Expat"] # MIT -> canonical Expat
183
184
185 def test_limit_slices_before_build(monkeypatch: pytest.MonkeyPatch) -> None:
186 # The costly window-builder must run for at most `limit` ids, not for all
187 # of them - i.e. the limit slices ids before the build, not after.
188 calls = 0
189 real = RANK.distinctive_window
190
191 def spy(*args: Any, **kwargs: Any) -> Any:
192 nonlocal calls
193 calls += 1
194 return real(*args, **kwargs)
195
196 monkeypatch.setattr(RANK, "distinctive_window", spy)
197 ids = ["BSD-2-Clause", "BSD-3-Clause", "ISC"]
198 RANK.collect_candidates(ids, exceptions=False, text_mode=True, limit=1)
199 assert calls == 1