返回 last30days-skill
test_discover_receipts.py
根目录 / tests / test_discover_receipts.py
1 import json
2 import time
3
4 import pytest
5
6 import last30days as cli
7 from lib import discovery_handoff, health, pipeline, render, schema
8
9
10 def _args(directory, *extra):
11 return cli.build_parser().parse_args([
12 "--discover", "AI agents", "--search", "x", "--discover-shallow",
13 "--save-dir", str(directory), *extra,
14 ])
15
16
17 @pytest.mark.parametrize("legacy", [False, True])
18 @pytest.mark.parametrize("discard", [False, True])
19 def test_sweep_warning_survives_saved_protocol_round_trip(tmp_path, monkeypatch, capsys, legacy, discard):
20 warning = "X: xapi window truncated to 7 days"
21 config = {
22 "LAST30DAYS_X_BACKEND": "xapi", "X_BEARER_TOKEN": "dummy",
23 "LAST30DAYS_STORE": str(tmp_path / "research.db"),
24 }
25 calls = []
26
27 def search(_token, topic, from_date, to_date, **kwargs):
28 calls.append(topic)
29 result = {"items": [{
30 "id": "1", "text": f"{topic}: Agent memory protocols improve local runtimes",
31 "url": "https://x.com/example/status/1", "author_handle": "example",
32 "date": to_date, "engagement": {"likes": 900, "reposts": 100},
33 "relevance": 1.0,
34 }]}
35 if len(calls) == 1:
36 result["warning"] = "window truncated to 7 days"
37 return result
38
39 monkeypatch.setattr(pipeline.x_api, "search_x", search)
40 monkeypatch.setattr(pipeline.x_api, "search_handles", lambda *a, **k: [])
41 monkeypatch.setattr(pipeline.x_api, "search_mentions", lambda *a, **k: [])
42 runtime = schema.ProviderRuntime(
43 reasoning_provider="native", planner_model="", rerank_model="",
44 x_search_backend="xapi",
45 )
46 monkeypatch.setattr(pipeline.providers, "resolve_runtime", lambda *a: (runtime, None))
47
48 assert cli._run_discover_protocol_leg(_args(tmp_path, "--nominate-only"), config) == 0
49 capsys.readouterr()
50 bundle_path = tmp_path / discovery_handoff.NOMINATIONS_BUNDLE_FILENAME
51 payload = json.loads(bundle_path.read_text(encoding="utf-8"))
52 assert payload["nominations"]
53 assert payload["warnings"] == [warning]
54 if legacy:
55 payload.pop("warnings")
56 bundle_path.write_text(json.dumps(payload), encoding="utf-8")
57 expected = [] if legacy else [warning]
58 bundle = discovery_handoff.read_nominations_bundle(save_dir=tmp_path)
59 assert bundle.schema_version == "1.0"
60 assert bundle.warnings == expected
61 assert bundle.source_status["x"].state == "ok"
62
63 judgments = tmp_path / "judgments.json"
64 judgments.write_text(json.dumps({
65 "bundle_id": bundle.bundle_id,
66 "judgments": [{"id": row.nomination_id, "junk": discard, "worthiness": 90}
67 for row in bundle.nominations],
68 }), encoding="utf-8")
69 assert cli._run_discover_protocol_leg(_args(tmp_path, "--judgments", str(judgments)), config) == 0
70 resumed = capsys.readouterr()
71 if discard:
72 assert "Nothing solid this window." in resumed.out
73 assert resumed.out.count(warning) == len(expected)
74 assert not (tmp_path / discovery_handoff.PENDING_REPORT_FILENAME).exists()
75 return
76 assert len(calls) > 1
77 pending = discovery_handoff.read_pending_report(save_dir=tmp_path)
78 assert pending.report["topics"]
79 assert pending.report["warnings"].count(warning) == len(expected)
80 assert pending.report["source_status"]["x"]["state"] == "ok"
81
82 assert cli._run_discover_protocol_leg(_args(tmp_path, "--finalize"), config) == 0
83 assert capsys.readouterr().out.count(warning) == len(expected)
84 saved = list(tmp_path.glob("*.md"))
85 assert saved
86 assert saved[0].read_text(encoding="utf-8").count(warning) == len(expected)
87
88
89 @pytest.mark.parametrize("outcome", ["budget-stop", "complete", "first-failure"])
90 def test_empty_nomination_report_preserves_bird_coverage(monkeypatch, outcome):
91 now = [1000.0]
92 calls = []
93 config = {
94 "LAST30DAYS_X_BACKEND": "bird", "AUTH_TOKEN": "dummy", "CT0": "dummy",
95 "_research_deadline": 1005.0,
96 }
97
98 def search(query, count, timeout, deadline=None, **kwargs):
99 calls.append(query)
100 if outcome != "complete":
101 now[0] = deadline - 0.5
102 if outcome == "first-failure":
103 return {"items": [], "error": "Invalid JSON response (anti-bot interstitial)"}
104 return {"items": []}
105
106 monkeypatch.setattr(pipeline.bird_x, "_run_bird_search", search)
107 monkeypatch.setattr(time, "monotonic", lambda: now[0])
108 result = pipeline.run_discover_nominate(
109 domain="Widget compiler development", config=config, depth="quick", requested_sources=["x"],
110 )
111 assert result.pool == []
112 report = pipeline.nominate_nothing_solid_report(result)
113 compact = render.render_discovery(report)
114 receipts = [warning for warning in report.warnings if "search budget" in warning]
115 if outcome == "budget-stop":
116 assert len(calls) == 1
117 assert report.source_status["x"].state == schema.NO_RESULTS
118 assert receipts == [
119 "X: bird Partial coverage: optional zero-result retries skipped because the search budget was exhausted."
120 ]
121 assert receipts[0] in compact
122 elif outcome == "complete":
123 assert len(calls) > 1
124 assert report.source_status["x"].state == schema.NO_RESULTS
125 assert receipts == []
126 else:
127 assert len(calls) == 1
128 assert report.source_status["x"].state == health.SCHEMA_DRIFT
129 assert "Invalid JSON response" in report.source_status["x"].detail
130 assert "Some discovery sources degraded: x." in report.warnings
131 assert receipts == []
132
132 lines PYTHON