返回 last30days-skill
test_prescriptions.py
根目录 / tests / test_prescriptions.py
1 """Tests for the fix-prescription registry (doctor plan U3, KTD 7).
2
3 One registry maps (source, failure mode) to its remediation in BOTH
4 natural-language and direct-CLI forms. Consumers: the doctor command (U4)
5 and lib/quality_nudge.py, which builds its fix text from the same entries
6 so the two surfaces cannot drift.
7 """
8
9 import re
10 from pathlib import Path
11 from unittest.mock import patch
12
13 import pytest
14
15 from lib import health, prescriptions
16
17
18 REPO_ROOT = Path(__file__).resolve().parent.parent
19 CONFIGURATION_MD = REPO_ROOT / "CONFIGURATION.md"
20
21 # A CLI fix must start with a runnable token: the engine invocation, an env
22 # assignment (optionally exported), or a documented binary name.
23 RUNNABLE = re.compile(
24 r"^(?:python3 \S*last30days\.py\b"
25 r"|[A-Z][A-Z0-9_]*="
26 r"|export [A-Z][A-Z0-9_]*="
27 r"|(?:brew|pipx|pip|scoop|npx|npm|xurl|yt-dlp|docker|grok) )"
28 )
29
30 # The seed failure inventory from the plan (U3 approach section).
31 SEED_INVENTORY = {
32 ("x", "cookies_missing"),
33 ("x", "cookies_expired"),
34 ("scrapecreators", "key_missing"),
35 ("bluesky", "app_password_missing"),
36 ("digg", "pp_cli_missing"),
37 ("digg", "pp_cli_off_path"),
38 ("digg", "pp_cli_broken"),
39 ("digg", "pp_cli_outdated"),
40 ("youtube", "ytdlp_missing"),
41 ("youtube", "ytdlp_stale"),
42 ("youtube", "ytdlp_broken"),
43 ("truthsocial", "token_missing"),
44 ("xiaohongshu", "service_unreachable"),
45 # Official X path (Grok Bot host): connector lane, bearer, credits.
46 ("x", "bearer_missing"),
47 ("x", "bearer_invalid"),
48 ("x", "payment_required"),
49 ("x", "connector_missing"),
50 }
51
52 OFFICIAL_X_FAILURES = (
53 "bearer_missing", "bearer_invalid", "payment_required", "connector_missing",
54 )
55 # R4 vocabulary the official entries must never carry.
56 GROK_BOT_FORBIDDEN = (
57 "cookie", "cdp", "box-chrome", "bird", "auth_token", "ct0", "xquik",
58 "grok login", "grok cli", "x.com",
59 )
60 GROK_BOT = {"LAST30DAYS_HOST": "grok-bot"}
61
62
63 def _configuration_md_slugs():
64 """GitHub-style anchor slugs for every CONFIGURATION.md heading."""
65 slugs = set()
66 for line in CONFIGURATION_MD.read_text(encoding="utf-8").splitlines():
67 m = re.match(r"#{1,6}\s+(.*)", line)
68 if not m:
69 continue
70 text = re.sub(r"[^\w\s-]", "", m.group(1).lower()).strip()
71 slugs.add(text.replace(" ", "-"))
72 return slugs
73
74
75 # ---------------------------------------------------------------------------
76 # Scenario 1: completeness lint over every registered entry
77 # ---------------------------------------------------------------------------
78
79 class TestCompletenessLint:
80 def test_seed_inventory_is_registered(self):
81 assert SEED_INVENTORY <= set(prescriptions.REGISTRY)
82
83 def test_every_entry_has_cause_and_both_fix_forms(self):
84 for key, entry in prescriptions.REGISTRY.items():
85 assert entry.cause.strip(), f"{key}: empty cause"
86 assert entry.fix_nl.strip(), f"{key}: empty natural-language fix"
87 assert entry.fix_cli.strip(), f"{key}: empty CLI fix"
88
89 def test_every_cli_form_starts_with_a_runnable_token(self):
90 for key, entry in prescriptions.REGISTRY.items():
91 for cli in (entry.fix_cli, *entry.alt_cli):
92 assert RUNNABLE.match(cli), f"{key}: not runnable: {cli!r}"
93
94 def test_nl_fix_never_duplicates_the_cli_string_verbatim(self):
95 for key, entry in prescriptions.REGISTRY.items():
96 assert entry.fix_nl.strip() != entry.fix_cli.strip(), key
97
98 def test_registry_keys_match_entry_fields(self):
99 for (source, failure), entry in prescriptions.REGISTRY.items():
100 assert entry.source == source
101 assert entry.failure == failure
102
103 def test_anchors_point_at_real_configuration_md_headings(self):
104 slugs = _configuration_md_slugs()
105 for key, entry in prescriptions.REGISTRY.items():
106 if entry.anchor:
107 assert entry.anchor in slugs, (
108 f"{key}: anchor #{entry.anchor} not a CONFIGURATION.md heading"
109 )
110
111 def test_no_secret_looking_values(self):
112 """Placeholders only - no copy-pasteable live credentials."""
113 secretish = re.compile(r"(sk-[A-Za-z0-9]{16,}|gsk_[A-Za-z0-9]{16,}|xox[bap]-)")
114 for key, entry in prescriptions.REGISTRY.items():
115 blob = " ".join((entry.cause, entry.fix_nl, entry.fix_cli, *entry.alt_cli))
116 assert not secretish.search(blob), key
117
118
119 # ---------------------------------------------------------------------------
120 # Documented CLI forms for the flagship entries
121 # ---------------------------------------------------------------------------
122
123 class TestDocumentedCliForms:
124 def test_x_cookie_fixes_use_setup_with_browser_cookie_consent(self):
125 expected = "python3 skills/last30days/scripts/last30days.py setup --allow-browser-cookies"
126 assert prescriptions.get("x", "cookies_missing").fix_cli == expected
127 assert prescriptions.get("x", "cookies_expired").fix_cli == expected
128
129 def test_scrapecreators_fix_is_the_github_device_flow(self):
130 entry = prescriptions.get("scrapecreators", "key_missing")
131 assert entry.fix_cli == "python3 skills/last30days/scripts/last30days.py setup --github"
132
133 def test_ytdlp_install_and_reinstall_reference_u1_health_strings(self):
134 """Binary-class fixes reference U1's tables instead of restating them."""
135 install, reinstall = health._MANAGER_PRESCRIPTIONS["yt-dlp"]["brew"]
136 assert prescriptions.get("youtube", "ytdlp_missing").fix_cli == install
137 assert prescriptions.get("youtube", "ytdlp_broken").fix_cli == reinstall
138
139 def test_digg_install_references_u1_printing_press_command(self):
140 entry = prescriptions.get("digg", "pp_cli_missing")
141 assert entry.fix_cli == health._pp_install_cmd("digg-pp-cli")
142
143 def test_outdated_digg_cli_prescribes_the_printing_press_install(self):
144 entry = prescriptions.get("digg", "pp_cli_outdated")
145 assert entry.fix_cli == health.pp_install_cmd("digg")
146 assert "AI and tech" in entry.cause
147 assert "every Digg topic" in entry.fix_nl
148
149
150 # ---------------------------------------------------------------------------
151 # Scenario 2: quality_nudge text derives from the same registry entries
152 # ---------------------------------------------------------------------------
153
154 def _nudge(config_overrides=None, result_overrides=None, ytdlp_installed=False):
155 from lib.quality_nudge import compute_quality_score
156 from lib import youtube_yt
157
158 config = {
159 "AUTH_TOKEN": None,
160 "CT0": None,
161 "XAI_API_KEY": None,
162 "XQUIK_API_KEY": None,
163 "SCRAPECREATORS_API_KEY": None,
164 }
165 config.update(config_overrides or {})
166 results = {"x_error": None, "youtube_error": None, "reddit_error": None}
167 results.update(result_overrides or {})
168 with patch.object(youtube_yt, "is_ytdlp_installed", return_value=ytdlp_installed):
169 return compute_quality_score(config, results)
170
171
172 class TestSharedWithQualityNudge:
173 def test_x_cookie_expired_nudge_is_built_from_the_registry_entry(self):
174 """Configured X that errored is a real outage, not an optional omission."""
175 entry = prescriptions.get("x", "cookies_expired")
176 q = _nudge(
177 config_overrides={"AUTH_TOKEN": "tok123"},
178 result_overrides={"x_error": "401 unauthorized"},
179 ytdlp_installed=True,
180 )
181 assert q["nudge_text"] is not None
182 assert entry.fix_nl in q["nudge_text"]
183 assert q["core_missing"] == ["x"]
184 assert q["core_errored"] == ["x"]
185
186 def test_x_cookie_missing_is_an_optional_omission_not_a_nudge(self):
187 q = _nudge(ytdlp_installed=True)
188 assert q["nudge_text"] is None
189 assert q["core_missing"] == []
190
191 def test_x_error_nudge_on_grok_bot_names_bearer_never_x_login(self):
192 """R4: the nudge after an X error on a Grok Bot host routes through
193 the policy-aware lookup and never says to log into x.com."""
194 config = dict(GROK_BOT, X_BEARER_TOKEN="dummy-bearer")
195 entry = prescriptions.for_x(config, "cookies_expired")
196 assert entry.failure == "bearer_invalid"
197 q = _nudge(
198 config_overrides=config,
199 result_overrides={"x_error": "401 unauthorized"},
200 ytdlp_installed=True,
201 )
202 assert q["core_errored"] == ["x"]
203 assert entry.fix_nl in q["nudge_text"]
204 lowered = q["nudge_text"].lower()
205 for word in GROK_BOT_FORBIDDEN:
206 assert word not in lowered, word
207
208 def test_x_credits_nudge_on_grok_bot_says_top_up(self):
209 config = dict(GROK_BOT, X_BEARER_TOKEN="dummy-bearer")
210 entry = prescriptions.for_x(config, "payment_required")
211 q = _nudge(
212 config_overrides=config,
213 result_overrides={"x_error": "xapi: payment required (X API credits exhausted)"},
214 ytdlp_installed=True,
215 )
216 assert entry.fix_nl in q["nudge_text"]
217 assert "top up" in q["nudge_text"].lower()
218 assert "x.com" not in q["nudge_text"].lower()
219
220 def test_x_error_nudge_off_grok_bot_is_unchanged(self):
221 entry = prescriptions.get("x", "cookies_expired")
222 q = _nudge(
223 config_overrides={"AUTH_TOKEN": "tok123"},
224 result_overrides={"x_error": "xquik: payment required (402)"},
225 ytdlp_installed=True,
226 )
227 assert entry.fix_nl in q["nudge_text"]
228
229 def test_ytdlp_missing_nudge_uses_registry_cli(self):
230 entry = prescriptions.get("youtube", "ytdlp_missing")
231 q = _nudge(config_overrides={"AUTH_TOKEN": "tok123"}, ytdlp_installed=False)
232 assert entry.fix_cli in q["nudge_text"]
233
234 def test_ytdlp_stale_degraded_nudge_uses_registry_cli_forms(self):
235 entry = prescriptions.get("youtube", "ytdlp_stale")
236 q = _nudge(
237 config_overrides={"AUTH_TOKEN": "tok123"},
238 ytdlp_installed=True,
239 result_overrides={
240 "youtube_videos_count": 6,
241 "youtube_transcripts_count": 0,
242 },
243 )
244 assert entry.fix_cli in q["nudge_text"]
245 for alt in entry.alt_cli:
246 assert alt in q["nudge_text"]
247
248 def test_quality_nudge_source_no_longer_hardcodes_fix_strings(self):
249 """The migrated fix strings must live in the registry only.
250
251 Trigger logic legitimately still reads credential names (e.g.
252 ``config.get("XAI_API_KEY")``); this guards the FIX text.
253 """
254 source = (
255 REPO_ROOT / "skills/last30days/scripts/lib/quality_nudge.py"
256 ).read_text(encoding="utf-8")
257 assert "brew " not in source
258 assert "api.x.ai" not in source
259 assert "log into x.com" not in source
260 assert "yt-dlp: brew" not in source
261
262
263 # ---------------------------------------------------------------------------
264 # Policy-aware X lookup (Grok Bot host names only the official path)
265 # ---------------------------------------------------------------------------
266
267 class TestPolicyAwareXLookup:
268 def test_default_host_returns_todays_entries(self):
269 assert prescriptions.for_x({}, "cookies_missing") is prescriptions.get("x", "cookies_missing")
270 assert prescriptions.for_x({}, "cookies_expired") is prescriptions.get("x", "cookies_expired")
271 assert prescriptions.for_x({"LAST30DAYS_HOST": "codex"}, "cookies_missing").failure == "cookies_missing"
272
273 def test_grok_bot_maps_cookie_and_grok_failures_to_official_entries(self):
274 assert prescriptions.for_x(GROK_BOT, "cookies_missing").failure == "bearer_missing"
275 assert prescriptions.for_x(GROK_BOT, "cookies_expired").failure == "bearer_invalid"
276 assert prescriptions.for_x(GROK_BOT, "grok_cli_missing").failure == "bearer_missing"
277 assert prescriptions.for_x(GROK_BOT, "grok_not_authenticated").failure == "bearer_missing"
278
279 def test_official_entries_pass_through_on_every_host(self):
280 for failure in OFFICIAL_X_FAILURES:
281 for config in ({}, GROK_BOT):
282 assert prescriptions.for_x(config, failure).failure == failure
283
284 def test_unknown_failure_falls_back_generically_on_grok_bot(self):
285 entry = prescriptions.for_x(GROK_BOT, "flux_capacitor_missing")
286 assert entry.fix_nl == prescriptions.GENERIC_FIX_NL
287
288 def test_official_entries_use_only_official_vocabulary(self):
289 for failure in OFFICIAL_X_FAILURES:
290 entry = prescriptions.get("x", failure)
291 blob = " ".join((entry.cause, entry.fix_nl, entry.fix_cli, *entry.alt_cli)).lower()
292 for word in GROK_BOT_FORBIDDEN:
293 assert word not in blob, (failure, word)
294
295 def test_bearer_copy_carries_the_week_caveat_not_parity(self):
296 for failure in ("bearer_missing", "bearer_invalid", "connector_missing"):
297 nl = prescriptions.get("x", failure).fix_nl
298 assert "X_BEARER_TOKEN" in nl, failure
299 assert "about the last week" in nl, failure
300 assert "full-archive" in nl, failure
301
302 def test_bearer_missing_offers_the_connector_first(self):
303 nl = prescriptions.get("x", "bearer_missing").fix_nl
304 assert nl.index("Grok Bot settings") < nl.index("X_BEARER_TOKEN")
305 assert "30-day" in nl
306 assert "XAI_API_KEY" in nl and "console.x.ai" in nl
307
308 def test_payment_required_says_top_up(self):
309 entry = prescriptions.get("x", "payment_required")
310 assert "top up" in entry.fix_nl.lower()
311 assert "credits" in entry.fix_nl.lower()
312
313
314 # ---------------------------------------------------------------------------
315 # Scenario 3: unregistered failure -> generic fallback, no crash
316 # ---------------------------------------------------------------------------
317
318 class TestFallback:
319 def test_lookup_returns_none_for_unregistered(self):
320 assert prescriptions.lookup("linkedin", "flux_capacitor_missing") is None
321
322 def test_get_returns_generic_configuration_md_pointer(self):
323 entry = prescriptions.get("linkedin", "flux_capacitor_missing")
324 assert "CONFIGURATION.md" in entry.fix_nl
325 assert RUNNABLE.match(entry.fix_cli)
326 assert entry.source == "linkedin"
327 assert entry.failure == "flux_capacitor_missing"
328
329 def test_get_returns_registered_entry_when_present(self):
330 assert prescriptions.get("x", "cookies_missing") is prescriptions.REGISTRY[
331 ("x", "cookies_missing")
332 ]
333
334
335 # ---------------------------------------------------------------------------
336 # Composition with U1 dependency probes (health.DependencyProbe)
337 # ---------------------------------------------------------------------------
338
339 class TestDependencyProbeComposition:
340 def test_ok_probe_needs_no_prescription(self):
341 probe = health.DependencyProbe(name="yt-dlp", status=health.OK, detail="2026.06.01")
342 assert prescriptions.for_dependency_probe(probe) is None
343
344 def test_probe_prescription_wins_the_cli_form(self):
345 """U1's machine-aware string (pipx owner here) overrides the static CLI."""
346 probe = health.DependencyProbe(
347 name="yt-dlp",
348 status=health.BROKEN,
349 detail="yt-dlp resolves to /x/yt-dlp but won't execute: stale shim",
350 prescription="pipx reinstall yt-dlp",
351 )
352 entry = prescriptions.for_dependency_probe(probe)
353 assert entry is not None
354 assert entry.fix_cli == "pipx reinstall yt-dlp"
355 # Registry vocabulary (NL form) is retained.
356 assert entry.fix_nl == prescriptions.get("youtube", "ytdlp_broken").fix_nl
357
358 def test_digg_off_path_probe_maps_to_the_path_entry(self):
359 probe = health.DependencyProbe(
360 name="digg-pp-cli",
361 status=health.MISSING,
362 detail=(
363 "digg-pp-cli is installed at /home/u/.local/bin/digg-pp-cli but "
364 "that directory is not on this process's PATH"
365 ),
366 prescription='add $HOME/.local/bin to PATH (e.g. export PATH="$HOME/.local/bin:$PATH") so digg-pp-cli resolves',
367 off_path=True,
368 )
369 entry = prescriptions.for_dependency_probe(probe)
370 assert entry is not None
371 assert entry.failure == "pp_cli_off_path"
372
373 def test_digg_broken_probe_maps_to_the_reinstall_entry(self):
374 """An installed-but-broken digg binary must get reinstall-framed
375 text, never the never-installed "install it" entry (F6); the
376 probe's own prescription wins the CLI form, mirroring
377 test_probe_prescription_wins_the_cli_form."""
378 reinstall = f"re-run the Printing Press install: {health.pp_install_cmd('digg')}"
379 probe = health.DependencyProbe(
380 name="digg-pp-cli",
381 status=health.BROKEN,
382 detail=(
383 "digg-pp-cli resolves to /home/u/.local/bin/digg-pp-cli "
384 "but won't execute"
385 ),
386 prescription=reinstall,
387 )
388 entry = prescriptions.for_dependency_probe(probe)
389 assert entry is not None
390 assert entry.failure == "pp_cli_broken"
391 assert entry.fix_cli == reinstall
392 # Registry vocabulary (NL form) is retained and reinstall-framed.
393 assert entry.fix_nl == prescriptions.get("digg", "pp_cli_broken").fix_nl
394 assert "reinstall" in entry.fix_nl
395 assert entry.fix_nl != prescriptions.get("digg", "pp_cli_missing").fix_nl
396
397 def test_digg_timeout_probe_also_maps_to_the_reinstall_entry(self):
398 probe = health.DependencyProbe(
399 name="digg-pp-cli",
400 status=health.TIMEOUT,
401 detail="digg-pp-cli --version timed out",
402 prescription="reinstall digg-pp-cli",
403 )
404 entry = prescriptions.for_dependency_probe(probe)
405 assert entry is not None
406 assert entry.failure == "pp_cli_broken"
407
408 def test_unregistered_dependency_wraps_the_probe(self):
409 probe = health.DependencyProbe(
410 name="ffmpeg",
411 status=health.MISSING,
412 detail="ffmpeg not found on PATH",
413 prescription="brew install ffmpeg",
414 )
415 entry = prescriptions.for_dependency_probe(probe)
416 assert entry is not None
417 assert entry.fix_cli == "brew install ffmpeg"
418 assert entry.fix_nl # still has a natural-language form
419
420
421 # ---------------------------------------------------------------------------
422 # Composition with U2 backend findings (lib/backends.py)
423 # ---------------------------------------------------------------------------
424
425 class TestBackendComposition:
426 def test_bird_cookie_prescription_embeds_the_registry_cli(self):
427 from lib import backends, bird_x
428
429 entry = prescriptions.get("x", "cookies_missing")
430 ok_node = health.DependencyProbe(name="node", status=health.OK, detail="v22.0.0")
431 with patch.object(bird_x, "is_bird_installed", return_value=True), \
432 patch.object(health, "probe_dependency", return_value=ok_node):
433 finding = backends._X_PROBES["bird"]({})
434 assert finding.status == health.MISSING
435 assert entry.fix_cli in finding.prescription
436
437 def test_scrapecreators_prescription_embeds_the_registry_cli(self):
438 from lib import backends
439
440 entry = prescriptions.get("scrapecreators", "key_missing")
441 finding = backends._SC_SPEC.probe({})
442 assert finding.status == health.MISSING
443 assert entry.fix_cli in finding.prescription
444 # test_backend_descriptors requires the key name to stay present.
445 assert "SCRAPECREATORS_API_KEY" in finding.prescription
446
447
448 class TestAltCliArityPin:
449 """Greptile PR review: quality_nudge composes YouTube nudges from the two
450 platform alternates on the ytdlp entries. The consumer is now tolerant of
451 any arity (degrades wording instead of crashing), and this pin keeps the
452 wording rich: both entries must keep at least the scoop + pip alternates."""
453
454 @pytest.mark.parametrize("failure", ["ytdlp_missing", "ytdlp_stale"])
455 def test_ytdlp_entries_keep_two_platform_alternates(self, failure):
456 entry = prescriptions.get("youtube", failure)
457 assert len(entry.alt_cli) >= 2, (
458 f"youtube/{failure} lost a platform alternate; quality_nudge "
459 "wording degrades (tolerant, but fix the entry or the prose)"
460 )
461
462
463 @pytest.mark.parametrize("failure", ["bearer_missing", "connector_missing"])
464 def test_official_x_repair_names_grok_bots_built_in_tools_before_the_connector(failure):
465 fix = prescriptions.for_x(GROK_BOT, failure).fix_nl
466 assert "built-in X tools" in fix
467 assert fix.index("built-in X tools") < fix.index("X for Grok Bot")
468
468 lines PYTHON