返回 last30days-skill
test_x_judge.py
根目录 / tests / test_x_judge.py
1 """Tests for x_judge.py — corpus judging for retrieve-judge-retry."""
2
3 import pytest
4
5 from skills.last30days.scripts.lib import x_judge
6
7
8 class TestJudgeXCorpus:
9 """Tests for judge_x_corpus."""
10
11 def test_empty_corpus_returns_not_flood(self):
12 """Empty corpus should not be flagged as off-topic flood."""
13 result = x_judge.judge_x_corpus([], "Rome")
14 assert result["on_topic_ratio"] == 1.0
15 assert not result["is_off_topic_flood"]
16 assert result["on_topic_items"] == []
17 assert result["off_topic_items"] == []
18
19 def test_on_topic_corpus_passes(self):
20 """Corpus with mostly on-topic posts should pass."""
21 items = [
22 {"author_handle": "mamboitaliano__", "text": "Beautiful Rome sunset"},
23 {"author_handle": "mamboitaliano__", "text": "Trevi Fountain in Rome"},
24 {"author_handle": "mamboitaliano__", "text": "Rome Colosseum today"},
25 {"author_handle": "turismoromaweb", "text": "Visit Rome Italy"},
26 ]
27 result = x_judge.judge_x_corpus(items, "Rome")
28 assert result["on_topic_ratio"] >= 0.5
29 assert not result["is_off_topic_flood"]
30 assert len(result["on_topic_items"]) >= 3
31
32 def test_off_topic_flood_detected(self):
33 """Corpus with mostly off-topic posts should be flagged as flood."""
34 # Rome fixture: 8 on-topic posts, 32 off-topic posts
35 on_topic = [
36 {"author_handle": "mamboitaliano__", "text": "Beautiful Rome sunset"},
37 {"author_handle": "mamboitaliano__", "text": "Trevi Fountain in Rome"},
38 {"author_handle": "mamboitaliano__", "text": "Rome Colosseum today"},
39 {"author_handle": "turismoromaweb", "text": "Visit Rome Italy"},
40 {"author_handle": "romecityphoto", "text": "Rome city at night"},
41 {"author_handle": "visitrome", "text": "Rome vacation tips"},
42 {"author_handle": "italytravel", "text": "Rome and Florence tour"},
43 {"author_handle": "rometraveler", "text": "Rome landmarks to see"},
44 ]
45 off_topic = [
46 {"author_handle": "visegrad24", "text": "Zelensky addresses NATO summit"},
47 {"author_handle": "visegrad24", "text": "Poland border update"},
48 {"author_handle": "visegrad24", "text": "Ukraine military news"},
49 {"author_handle": "PrettyCitiesX", "text": "London bridge at sunset"},
50 {"author_handle": "PrettyCitiesX", "text": "Paris Eiffel tower"},
51 {"author_handle": "PrettyCitiesX", "text": "Tokyo skyline"},
52 {"author_handle": "earthserenityy", "text": "Mountain landscape photo"},
53 {"author_handle": "earthserenityy", "text": "Beach sunset vibes"},
54 ]
55 # Repeat off-topic to get 32 items
56 all_off_topic = off_topic * 4
57 items = on_topic + all_off_topic
58
59 result = x_judge.judge_x_corpus(items, "Rome")
60 assert result["on_topic_ratio"] < 0.4
61 assert result["is_off_topic_flood"]
62 assert len(result["on_topic_items"]) == 8
63
64 def test_no_substring_collision_ai_in_said(self):
65 """'AI' as a topic token should NOT match 'said' (no substring collisions).
66
67 This verifies that topic judging uses proper word tokenization, not
68 substring matching. If substring matching were used, 'ai' would match
69 inside 'said', causing false positives.
70 """
71 items = [
72 {"author_handle": "offtopic", "text": "He said something interesting"},
73 {"author_handle": "offtopic", "text": "She said the weather was nice"},
74 {"author_handle": "offtopic", "text": "They said it was great"},
75 ]
76 result = x_judge.judge_x_corpus(items, "AI")
77 # None of these posts contain "AI" as a word, so all should be off-topic
78 assert len(result["on_topic_items"]) == 0
79 assert len(result["off_topic_items"]) == 3
80
81 def test_no_substring_collision_rome_in_promoter(self):
82 """'rome' as a topic token should NOT match 'promoter' (no substring collisions)."""
83 items = [
84 {"author_handle": "offtopic", "text": "A viral promoter of products"},
85 {"author_handle": "offtopic", "text": "She is a band promoter"},
86 ]
87 result = x_judge.judge_x_corpus(items, "Rome")
88 # None of these posts contain "Rome" as a word
89 assert len(result["on_topic_items"]) == 0
90 assert len(result["off_topic_items"]) == 2
91
92 def test_us_pronoun_does_not_match_us_topic(self):
93 """Lowercase 'us' pronoun should not match 'US' country topic."""
94 items = [
95 {"author_handle": "offtopic", "text": "Tell us what you think"},
96 {"author_handle": "offtopic", "text": "Join us for the event"},
97 ]
98 # "US" topic vs "us" pronoun in text - case-sensitive check filters
99 result = x_judge.judge_x_corpus(items, "US")
100 assert len(result["on_topic_items"]) == 0
101 assert len(result["off_topic_items"]) == 2
102
103 def test_us_acronym_matches_us_topic(self):
104 """Uppercase 'US' country acronym in text matches 'US' topic."""
105 items = [
106 {"author_handle": "ontopic", "text": "The US is expanding trade"},
107 {"author_handle": "ontopic", "text": "US policy update"},
108 ]
109 result = x_judge.judge_x_corpus(items, "US")
110 assert len(result["on_topic_items"]) == 2
111 assert len(result["off_topic_items"]) == 0
112
113 def test_us_with_context_matches(self):
114 """'US economy' matches posts about US economy."""
115 items = [
116 {"author_handle": "ontopic", "text": "The US economy is growing"},
117 {"author_handle": "ontopic", "text": "Economy news from America"},
118 ]
119 result = x_judge.judge_x_corpus(items, "US economy")
120 # First post has "US" (acronym) and "economy" → on-topic
121 # Second post has "economy" only → on-topic
122 assert len(result["on_topic_items"]) >= 1
123
124 def test_multi_token_us_query_with_pronoun(self):
125 """The pronoun is excluded from overlap and the query denominator."""
126 items = [
127 {"author_handle": "pronoun", "text": "Tell us about the economy"},
128 {"author_handle": "country", "text": "Tell US about the economy"},
129 {"author_handle": "unrelated", "text": "Tell us about the weather"},
130 ]
131 assert x_judge._compute_relevance("US economy growth", items[0]["text"]) == 0.5
132 assert x_judge._compute_relevance("US economy growth", items[1]["text"]) == pytest.approx(2 / 3)
133 result = x_judge.judge_x_corpus(items, "US economy growth")
134 assert result["on_topic_items"] == items[:2]
135 assert result["off_topic_items"] == [items[2]]
136 assert result["on_topic_ratio"] == pytest.approx(2 / 3)
137
138 def test_handle_stats_computed(self):
139 """Handle stats should track on-topic and total counts."""
140 items = [
141 {"author_handle": "handle_a", "text": "Rome is beautiful"},
142 {"author_handle": "handle_a", "text": "Paris is nice"},
143 {"author_handle": "handle_b", "text": "Rome vacation"},
144 {"author_handle": "handle_b", "text": "Rome food"},
145 ]
146 result = x_judge.judge_x_corpus(items, "Rome")
147 assert result["handle_stats"]["handle_a"]["total"] == 2
148 assert result["handle_stats"]["handle_b"]["total"] == 2
149 # handle_b has 2 on-topic posts about Rome
150 assert result["handle_stats"]["handle_b"]["on_topic"] == 2
151
152
153 class TestPromotableHandles:
154 """Tests for promotable_handles — split FROM promotion."""
155
156 def test_explicit_handles_always_promoted(self):
157 """Explicit handles (--x-handle) should always be promoted."""
158 items = [
159 {"author_handle": "steipete", "text": "random post about nothing"},
160 ]
161 explicit, extracted = x_judge.promotable_handles(
162 items, "quantum widgets", ["steipete"], explicit_handles=["steipete"]
163 )
164 assert "steipete" in explicit
165 assert "steipete" not in extracted
166
167 def test_extracted_handle_promoted_with_on_topic_posts(self):
168 """Extracted handle with ≥2 on-topic posts should be promoted."""
169 items = [
170 {"author_handle": "mamboitaliano__", "text": "Rome sunset beautiful"},
171 {"author_handle": "mamboitaliano__", "text": "Rome Colosseum tour"},
172 {"author_handle": "mamboitaliano__", "text": "Trevi Fountain Rome"},
173 ]
174 explicit, extracted = x_judge.promotable_handles(
175 items, "Rome", ["mamboitaliano__"], explicit_handles=[]
176 )
177 assert "mamboitaliano__" in extracted
178 assert len(explicit) == 0
179
180 def test_extracted_handle_not_promoted_with_off_topic_posts(self):
181 """Extracted handle with off-topic posts should not be promoted."""
182 items = [
183 {"author_handle": "visegrad24", "text": "Zelensky addresses summit"},
184 {"author_handle": "visegrad24", "text": "Poland military update"},
185 {"author_handle": "visegrad24", "text": "Ukraine border news"},
186 # One post mentions Rome but mostly off-topic
187 {"author_handle": "visegrad24", "text": "Rome, Italy in caption"},
188 ]
189 explicit, extracted = x_judge.promotable_handles(
190 items, "Rome", ["visegrad24"], explicit_handles=[]
191 )
192 assert "visegrad24" not in extracted
193 assert len(explicit) == 0
194
195 def test_explicit_handle_not_in_extracted_still_promoted(self):
196 """Explicit handle not in extracted list should still be promoted."""
197 items = [] # No items for this handle
198 explicit, extracted = x_judge.promotable_handles(
199 items, "topic", [], explicit_handles=["explicit_handle"]
200 )
201 assert "explicit_handle" in explicit
202
203 def test_min_hits_threshold(self):
204 """Handle needs MIN_ON_TOPIC_HITS to be promoted."""
205 items = [
206 {"author_handle": "onepost", "text": "Rome is nice"}, # Only 1 on-topic
207 ]
208 explicit, extracted = x_judge.promotable_handles(
209 items, "Rome", ["onepost"], explicit_handles=[]
210 )
211 # Not enough on-topic hits (needs ≥2)
212 assert "onepost" not in extracted
213
214
215 class TestShouldRetryXSearch:
216 """Tests for should_retry_x_search."""
217
218 def test_skip_retry_on_quick_depth(self):
219 """Quick depth should skip retry."""
220 items = [
221 {"author_handle": "off_topic", "text": "completely unrelated content"},
222 ] * 40
223 assert not x_judge.should_retry_x_search(items, "Rome", depth="quick")
224
225 def test_trigger_retry_on_off_topic_flood(self):
226 """Off-topic flood should trigger retry."""
227 off_topic = [
228 {"author_handle": "off_topic", "text": "completely unrelated content"},
229 ] * 40
230 assert x_judge.should_retry_x_search(off_topic, "Rome", depth="default")
231
232 def test_no_retry_on_good_corpus(self):
233 """On-topic corpus should not trigger retry."""
234 on_topic = [
235 {"author_handle": "romefan", "text": "Rome vacation photos"},
236 {"author_handle": "romefan", "text": "Rome colosseum visit"},
237 {"author_handle": "romefan", "text": "Rome food tour"},
238 {"author_handle": "romefan", "text": "Rome sunset beautiful"},
239 ]
240 assert not x_judge.should_retry_x_search(on_topic, "Rome", depth="default")
241
242
243 class TestPruneOffTopicItems:
244 """Tests for prune_off_topic_items."""
245
246 def test_prunes_off_topic_keeps_on_topic(self):
247 """Should prune off-topic items and keep on-topic ones."""
248 items = [
249 {"author_handle": "on", "text": "Rome vacation"},
250 {"author_handle": "off", "text": "Paris travel"},
251 {"author_handle": "on", "text": "Rome colosseum"},
252 {"author_handle": "off", "text": "London sights"},
253 ]
254 result = x_judge.prune_off_topic_items(items, "Rome")
255 assert len(result) == 2
256 assert all("Rome" in item["text"] for item in result)
257
258 def test_empty_after_prune_is_ok(self):
259 """Pruning all items should return empty list."""
260 items = [
261 {"author_handle": "off", "text": "completely unrelated"},
262 {"author_handle": "off", "text": "nothing to do with topic"},
263 ]
264 result = x_judge.prune_off_topic_items(items, "Rome")
265 assert result == []
266
267
268 class TestRomeScenario:
269 """Integration tests for the Rome failure scenario from 2026-08-14."""
270
271 @pytest.fixture
272 def rome_off_topic_corpus(self):
273 """The Rome failure corpus: 8 on-topic, 32 off-topic."""
274 on_topic = [
275 {"author_handle": "mamboitaliano__", "text": "Beautiful Rome sunset over the Tiber"},
276 {"author_handle": "mamboitaliano__", "text": "Trevi Fountain in Rome today"},
277 {"author_handle": "mamboitaliano__", "text": "Rome Colosseum morning visit"},
278 {"author_handle": "Turismoromaweb", "text": "Visit Rome Italy for vacation"},
279 {"author_handle": "romecityguide", "text": "Rome city center walking tour"},
280 {"author_handle": "italyrome", "text": "Rome and Vatican day trip"},
281 {"author_handle": "romephotos", "text": "Rome architecture stunning"},
282 {"author_handle": "rometravel", "text": "Rome travel tips for tourists"},
283 ]
284 off_topic = [
285 # visegrad24 - geopolitics account, thin Rome connection
286 {"author_handle": "visegrad24", "text": "Zelensky addresses NATO summit"},
287 {"author_handle": "visegrad24", "text": "Poland border security update"},
288 {"author_handle": "visegrad24", "text": "Ukraine military operations today"},
289 {"author_handle": "visegrad24", "text": "Russia sanctions news breaking"},
290 # PrettyCitiesX - city aesthetics account, has other cities
291 {"author_handle": "PrettyCitiesX", "text": "London bridge at sunset"},
292 {"author_handle": "PrettyCitiesX", "text": "Paris Eiffel tower night"},
293 {"author_handle": "PrettyCitiesX", "text": "Tokyo skyline beautiful"},
294 {"author_handle": "PrettyCitiesX", "text": "New York Central Park"},
295 # earthserenityy - nature photos, no Rome
296 {"author_handle": "earthserenityy", "text": "Mountain landscape photography"},
297 {"author_handle": "earthserenityy", "text": "Beach sunset vibes serene"},
298 {"author_handle": "earthserenityy", "text": "Forest morning fog mystical"},
299 {"author_handle": "earthserenityy", "text": "Ocean waves crashing shore"},
300 # AS Roma sports content (Rome collision)
301 {"author_handle": "asromafc", "text": "AS Roma match tonight Serie A"},
302 {"author_handle": "asromafc", "text": "Roma vs Juventus preview"},
303 {"author_handle": "asromafc", "text": "Forza Roma goal highlights"},
304 {"author_handle": "asromafc", "text": "AS Roma transfer rumors"},
305 # Rome Odunze collision
306 {"author_handle": "nflupdates", "text": "Rome Odunze catches touchdown"},
307 {"author_handle": "nflupdates", "text": "Bears WR Rome Odunze stats"},
308 {"author_handle": "fantasyfb", "text": "Start Rome Odunze this week"},
309 {"author_handle": "fantasyfb", "text": "Rome Odunze fantasy value"},
310 ]
311 # Duplicate off-topic to reach ~32 items
312 return on_topic + off_topic + off_topic[:12]
313
314 def test_rome_corpus_detected_as_off_topic(self, rome_off_topic_corpus):
315 """Rome failure corpus should be detected as off-topic flood."""
316 result = x_judge.judge_x_corpus(rome_off_topic_corpus, "Rome")
317 # ~8/40 = 0.2, well below 0.4 threshold
318 assert result["on_topic_ratio"] < 0.4
319 assert result["is_off_topic_flood"]
320
321 def test_mamboitaliano_promotable(self, rome_off_topic_corpus):
322 """mamboitaliano__ with on-topic Rome posts should be promotable."""
323 explicit, extracted = x_judge.promotable_handles(
324 rome_off_topic_corpus,
325 "Rome",
326 ["mamboitaliano__", "visegrad24", "PrettyCitiesX"],
327 explicit_handles=[],
328 )
329 assert "mamboitaliano__" in extracted
330
331 def test_visegrad24_not_promotable(self, rome_off_topic_corpus):
332 """visegrad24 with off-topic posts should NOT be promotable."""
333 explicit, extracted = x_judge.promotable_handles(
334 rome_off_topic_corpus,
335 "Rome",
336 ["mamboitaliano__", "visegrad24", "PrettyCitiesX"],
337 explicit_handles=[],
338 )
339 assert "visegrad24" not in extracted
340 assert "PrettyCitiesX" not in extracted
341
342 def test_turismoromaweb_promotable_if_explicit(self, rome_off_topic_corpus):
343 """Turismoromaweb should be promoted if explicitly specified."""
344 explicit, extracted = x_judge.promotable_handles(
345 rome_off_topic_corpus,
346 "Rome",
347 ["Turismoromaweb"],
348 explicit_handles=["Turismoromaweb"],
349 )
350 assert "Turismoromaweb" in explicit
351
351 lines PYTHON