返回 last30days-skill
test_cr20_pipeline.py
根目录 / tests / test_cr20_pipeline.py
1 import pytest
2
3 from lib import env, pipeline, reddit, reddit_public, render
4
5
6 @pytest.mark.parametrize("excluded", [False, True])
7 @pytest.mark.parametrize("selection", ["automatic", "requested", "hiring", "host-plan"])
8 def test_jobs_dispatch_respects_exclusion(monkeypatch, excluded, selection):
9 dispatched = []
10
11 def retrieve(**kwargs):
12 dispatched.append(kwargs["source"])
13 return [], {}
14
15 monkeypatch.setattr(pipeline, "_retrieve_stream", retrieve)
16 monkeypatch.setattr(pipeline, "which", lambda _name: None)
17 config = {"EXCLUDE_SOURCES": "jobs"} if excluded else {}
18 requested = ["reddit", "jobs"] if selection == "requested" else None
19 if selection == "hiring":
20 requested = ["reddit"]
21 external_plan = None
22 if selection == "host-plan":
23 external_plan = {
24 "intent": "research",
25 "freshness_mode": "balanced_recent",
26 "cluster_mode": "topic",
27 "subqueries": [{
28 "label": "primary",
29 "search_query": "OpenAI",
30 "ranking_query": "OpenAI",
31 "sources": ["reddit", "jobs"],
32 }],
33 }
34
35 report = pipeline.run(
36 topic="OpenAI",
37 config=config,
38 depth="quick",
39 requested_sources=requested,
40 hiring_signals_mode=selection == "hiring",
41 external_plan=external_plan,
42 web_backend="none",
43 )
44
45 assert "reddit" in dispatched
46 assert ("jobs" in dispatched) is not excluded
47 assert any("jobs" in sq.sources for sq in report.query_plan.subqueries) is not excluded
48 assert any(status.source == "jobs" and status.attempted for status in report.source_status.values()) is not excluded
49
50
51 def test_jobs_only_hiring_run_rejects_excluded_source_before_dispatch(monkeypatch):
52 dispatched = []
53
54 def retrieve(**kwargs):
55 dispatched.append(kwargs["source"])
56 return [], {}
57
58 monkeypatch.setattr(pipeline, "_retrieve_stream", retrieve)
59 with pytest.raises(RuntimeError, match="No sources are available"):
60 pipeline.run(
61 topic="OpenAI",
62 config={"EXCLUDE_SOURCES": "jobs"},
63 depth="quick",
64 hiring_signals_mode=True,
65 web_backend="none",
66 )
67 assert dispatched == []
68
69
70 def test_unconfigured_search_sources_name_the_sources(monkeypatch):
71 dispatched = []
72
73 def retrieve(**kwargs):
74 dispatched.append(kwargs["source"])
75 return [], {}
76
77 monkeypatch.setattr(pipeline, "_retrieve_stream", retrieve)
78 with pytest.raises(pipeline.NoRequestedSourceAvailable, match="--search can run here: telegram, threads"):
79 pipeline.run(
80 topic="rust async",
81 config={},
82 depth="quick",
83 # local fork: tiktok runs keyless (shortform_oss); threads is SC-keyed.
84 requested_sources=["telegram", "threads"],
85 web_backend="none",
86 )
87 assert dispatched == []
88
89
90 @pytest.mark.parametrize("include_match", [False, True])
91 @pytest.mark.parametrize("filter_kind", ["topic", "keywords"])
92 def test_polymarket_rejections_are_absent_from_fusion_and_output(
93 monkeypatch, filter_kind, include_match,
94 ):
95 topic = "Hermes vs OpenClaw" if filter_kind == "topic" else "Warriors"
96 rejected_title = "Glasgow Warriors rugby championship"
97 accepted_title = "Hermes launch by December?" if filter_kind == "topic" else "Warriors win NBA finals?"
98 rejected = {
99 "id": "rugby",
100 "title": rejected_title,
101 "url": "https://polymarket.com/event/glasgow-rugby",
102 "date": "2026-10-01",
103 "volume1mo": 100000,
104 "relevance": 1.0,
105 }
106 accepted = {
107 "id": "accepted",
108 "title": accepted_title,
109 "url": "https://polymarket.com/event/relevant-market",
110 "date": "2026-10-01",
111 "volume1mo": 100000,
112 "relevance": 1.0,
113 }
114 markets = [rejected, accepted] if include_match else [rejected]
115 monkeypatch.setattr(pipeline, "_retrieve_stream", lambda **_kwargs: (markets, {}))
116 fused_titles = []
117 weighted_rrf = pipeline.weighted_rrf
118
119 def observe_fusion(streams, *args, **kwargs):
120 fused_titles.extend(item.title for items in streams.values() for item in items)
121 return weighted_rrf(streams, *args, **kwargs)
122
123 monkeypatch.setattr(pipeline, "weighted_rrf", observe_fusion)
124 config = {"_polymarket_keywords": ["nba", "gsw"]} if filter_kind == "keywords" else {}
125 report = pipeline.run(
126 topic=topic,
127 config=config,
128 depth="default",
129 requested_sources=["polymarket"],
130 web_backend="none",
131 as_of_date="2026-10-22",
132 external_plan={
133 "intent": "research",
134 "freshness_mode": "balanced_recent",
135 "cluster_mode": "topic",
136 "subqueries": [{
137 "label": label,
138 "search_query": "Warriors Hermes",
139 "ranking_query": "Warriors Hermes",
140 "sources": ["polymarket"],
141 } for label in ("primary", "secondary")],
142 },
143 )
144
145 expected = {accepted_title} if include_match else set()
146 assert {item.title for item in report.items_by_source["polymarket"]} == expected
147 assert set(fused_titles) == expected
148 assert {candidate.title for candidate in report.ranked_candidates} == expected
149 assert report.source_status["polymarket"].items_returned == len(expected)
150 assert rejected_title not in render.render_compact(report)
151
152
153 @pytest.mark.parametrize("freshness_mode", ["strict_recent", "balanced_recent", "evergreen_ok"])
154 @pytest.mark.parametrize("sc_date", ["2026-08-01", "2026-09-22", "2026-10-22", None])
155 def test_reddit_sc_date_filter_precedes_enrichment_and_public_fallback(
156 monkeypatch, freshness_mode, sc_date,
157 ):
158 comment_requests = []
159 public_requests = []
160 stale_url = "https://www.reddit.com/r/music/comments/stale/old_contract/"
161 recent_url = "https://www.reddit.com/r/music/comments/current/tour_schedule/"
162 public_url = "https://www.reddit.com/r/music/comments/public/album_release/"
163 sc_posts = [{
164 "id": "stale",
165 "title": "Kanye old contract dispute",
166 "url": stale_url,
167 "created_at": "2026-08-01",
168 "subreddit": "music",
169 "score": 100,
170 "num_comments": 20,
171 }, {
172 "id": "current",
173 "title": "Kanye new tour schedule released",
174 "url": recent_url,
175 "created_at": sc_date,
176 "subreddit": "music",
177 "score": 80,
178 "num_comments": 10,
179 }]
180
181 def sc_response(url, **kwargs):
182 assert url.startswith(reddit.SCRAPECREATORS_BASE)
183 if url.endswith("/post/comments"):
184 comment_requests.append(kwargs["params"]["url"])
185 return {"comments": [{
186 "body": "Kanye tour dates match the newly announced schedule.",
187 "author": "dummy-fan",
188 "score": 12,
189 "created_utc": 1791504000,
190 }]}
191 assert url.endswith("/search")
192 return {"posts": sc_posts}
193
194 def public_response(*args, **kwargs):
195 public_requests.append((args, kwargs))
196 return [{
197 "id": "public",
198 "title": "Kanye album release announced",
199 "url": public_url,
200 "date": "2026-10-01",
201 "subreddit": "music",
202 "engagement": {"score": 100, "num_comments": 20},
203 "relevance": 1.0,
204 }]
205
206 monkeypatch.setattr(reddit.http, "get", sc_response)
207 monkeypatch.setattr(reddit_public, "search_reddit_public", public_response)
208 report = pipeline.run(
209 topic="Kanye",
210 config={
211 "SCRAPECREATORS_API_KEY": "dummy-scrapecreators-key",
212 env.REDDIT_BACKEND_PIN_VAR: "scrapecreators",
213 },
214 depth="quick",
215 requested_sources=["reddit"],
216 web_backend="none",
217 as_of_date="2026-10-22",
218 external_plan={
219 "intent": "research",
220 "freshness_mode": freshness_mode,
221 "cluster_mode": "topic",
222 "subqueries": [{
223 "label": "primary",
224 "search_query": "Kanye",
225 "ranking_query": "Kanye",
226 "sources": ["reddit"],
227 }],
228 },
229 )
230
231 all_stale = sc_date == "2026-08-01"
232 expected_url = public_url if all_stale else recent_url
233 assert {item.url for item in report.items_by_source["reddit"]} == {expected_url}
234 assert bool(public_requests) is all_stale
235 assert comment_requests == ([] if all_stale else [recent_url])
236 if not all_stale:
237 assert report.items_by_source["reddit"][0].metadata["top_comments"][0]["score"] == 12
238
238 lines PYTHON