返回 last30days-skill
test_cr20_sources.py
根目录 / tests / test_cr20_sources.py
1 import json
2 import re
3 import subprocess
4 from datetime import datetime
5 from pathlib import Path
6 from urllib.parse import parse_qs, urlsplit
7
8 import pytest
9
10 from lib import dates, grok_x, subproc, trustpilot, web_search_keyless, xquik
11
12
13 def test_adapters_are_imported_from_this_checkout():
14 scripts = Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts"
15 for module in (dates, grok_x, trustpilot, web_search_keyless, xquik):
16 assert Path(module.__file__).resolve().is_relative_to(scripts)
17
18
19 def _grok_query(cmd):
20 prompt = cmd[cmd.index("-p") + 1]
21 prefix = "Query (JSON string literal): "
22 return json.loads(next(line[len(prefix):] for line in prompt.splitlines() if line.startswith(prefix)))
23
24
25 def _search_grok(lane, start, end):
26 if lane == "topic":
27 return grok_x.search_x("boundary subject", start, end, depth="deep")["items"]
28 if lane == "from":
29 return grok_x.search_handles(["subject"], "boundary subject", start, end)[0]
30 if lane == "from-topic":
31 return grok_x.search_handles(["subject"], "boundary subject", start, end, and_topic=True)[0]
32 if lane == "mentions":
33 return grok_x.search_mentions(["subject"], start, end)[0]
34 return grok_x.search_name("Boundary Subject", start, end)[0]
35
36
37 def _search_xquik(lane, start, end):
38 if lane == "topic":
39 return xquik.search_xquik("boundary subject", start, end, depth="deep", token="dummy-key")["items"]
40 if lane == "from":
41 return xquik.search_handles(["subject"], "boundary subject", start, end, token="dummy-key")
42 return xquik.search_mentions(["subject"], start, end, token="dummy-key")
43
44
45 @pytest.mark.parametrize("lane", ["topic", "from", "from-topic", "mentions", "name"])
46 @pytest.mark.parametrize("end,exclusive", [
47 ("2024-02-29", "2024-03-01"),
48 ("2024-12-31", "2025-01-01"),
49 ("9999-12-30", "9999-12-31"),
50 ("9999-12-31", None),
51 ])
52 def test_grok_all_lanes_request_the_inclusive_end_date(monkeypatch, lane, end, exclusive):
53 queries = []
54
55 def run(cmd, **kwargs):
56 queries.append(_grok_query(cmd))
57 return subprocess.CompletedProcess(cmd, 0, "[]", "")
58
59 monkeypatch.setattr(grok_x, "binary_path", lambda: "/dummy/grok")
60 monkeypatch.setattr(grok_x, "_check_cli_version", lambda *args: (None, "grok 1.0.70 (f50904eaee6c)"))
61 monkeypatch.setattr(grok_x.subproc, "run_with_timeout", run)
62 _search_grok(lane, "2024-02-01", end)
63 assert queries
64 for query in queries:
65 assert "since:2024-02-01" in query.split()
66 assert [part for part in query.split() if part.startswith("until:")] == (
67 [f"until:{exclusive}"] if exclusive else []
68 )
69
70
71 @pytest.mark.parametrize("lane", ["topic", "from", "mentions"])
72 @pytest.mark.parametrize("end,exclusive", [
73 ("2024-02-29", "2024-03-01"),
74 ("2024-12-31", "2025-01-01"),
75 ("9999-12-30", "9999-12-31"),
76 ("9999-12-31", None),
77 ])
78 def test_xquik_all_lanes_request_the_inclusive_end_date(monkeypatch, lane, end, exclusive):
79 queries = []
80
81 def get(url, **kwargs):
82 queries.append(parse_qs(urlsplit(url).query)["q"][0])
83 return {"tweets": []}
84
85 monkeypatch.setattr(xquik.http, "get", get)
86 _search_xquik(lane, "2024-02-01", end)
87 assert queries
88 for query in queries:
89 assert "since:2024-02-01" in query.split()
90 assert [part for part in query.split() if part.startswith("until:")] == (
91 [f"until:{exclusive}"] if exclusive else []
92 )
93
94
95 def _snowflake(timestamp):
96 instant = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
97 return str((int(instant.timestamp() * 1000) - 1288834974657) << 22)
98
99
100 @pytest.mark.parametrize("adapter,lane", [
101 ("grok", "topic"), ("grok", "from"), ("grok", "from-topic"),
102 ("grok", "mentions"), ("grok", "name"),
103 ("xquik", "topic"), ("xquik", "from"), ("xquik", "mentions"),
104 ])
105 def test_x_adapters_retain_final_day_but_not_following_day(monkeypatch, adapter, lane):
106 timestamps = ["2024-02-29T23:59:59.999Z", "2024-03-01T00:00:00Z"]
107 handle = "subject" if lane.startswith("from") else "observer"
108
109 def matching(query):
110 match = re.search(r"\buntil:(\d{4}-\d{2}-\d{2})\b", query)
111 return [stamp for stamp in timestamps if match is None or stamp[:10] < match.group(1)]
112
113 def grok_run(cmd, **kwargs):
114 posts = [
115 {"url": f"https://x.com/{handle}/status/{_snowflake(stamp)}", "text": "boundary subject", "likes": 10}
116 for stamp in matching(_grok_query(cmd))
117 ]
118 return subprocess.CompletedProcess(cmd, 0, json.dumps(posts), "")
119
120 def xquik_get(url, **kwargs):
121 query = parse_qs(urlsplit(url).query)["q"][0]
122 return {"tweets": [
123 {"id": _snowflake(stamp), "author": {"username": handle}, "text": "boundary subject", "createdAt": stamp}
124 for stamp in matching(query)
125 ]}
126
127 monkeypatch.setattr(grok_x, "binary_path", lambda: "/dummy/grok")
128 monkeypatch.setattr(grok_x, "_check_cli_version", lambda *args: (None, "grok 1.0.70 (f50904eaee6c)"))
129 monkeypatch.setattr(grok_x.subproc, "run_with_timeout", grok_run)
130 monkeypatch.setattr(xquik.http, "get", xquik_get)
131 search = _search_grok if adapter == "grok" else _search_xquik
132 items = search(lane, "2024-02-01", "2024-02-29")
133 assert [item["url"] for item in items] == [f"https://x.com/{handle}/status/{_snowflake(timestamps[0])}"]
134
135
136 def test_grok_validates_the_whole_inclusive_day():
137 timestamps = ["2024-02-29T23:59:59.999Z", "2024-03-01T00:00:00Z"]
138 posts = [
139 {"url": f"https://x.com/observer/status/{_snowflake(stamp)}", "text": "boundary subject", "likes": 10, "created_at": stamp}
140 for stamp in timestamps
141 ]
142 items = grok_x.parse_x_response({"text": json.dumps(posts)}, "boundary subject", "2024-02-01", "2024-02-29")
143 assert [item["date"] for item in items] == ["2024-02-29"]
144
145
146 @pytest.fixture
147 def trustpilot_cli(monkeypatch):
148 calls = []
149 trustpilot._reset_state_for_tests()
150
151 def run(cmd, **kwargs):
152 calls.append(cmd)
153 if cmd[1] == "auth":
154 data = {"isFresh": True}
155 elif cmd[1] == "search":
156 data = {"hits": [{"displayName": "Currys", "domain": "currys.co.uk", "numberOfReviews": 100}]}
157 else:
158 data = {"name": "Selected company", "domain": cmd[-1], "reviewCount": 100}
159 return subproc.SubprocResult(returncode=0, stdout=json.dumps(data), stderr="")
160
161 monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
162 monkeypatch.setattr(trustpilot.subproc, "run_with_timeout", run)
163 yield calls
164 trustpilot._reset_state_for_tests()
165
166
167 @pytest.mark.parametrize("topic,domain", [
168 ("currys.co.uk", "currys.co.uk"),
169 ("woolworths.com.au", "woolworths.com.au"),
170 ("reviews of https://www.currys.co.uk/help", "www.currys.co.uk"),
171 ("Reviews of WOOLWORTHS.COM.AU.", "woolworths.com.au"),
172 ("chownow.com.other", "chownow.com.other"),
173 ("my-brand.com", "my-brand.com"),
174 ])
175 def test_trustpilot_domain_topics_reach_the_cli_intact(trustpilot_cli, topic, domain):
176 response = trustpilot.search_trustpilot(topic, "2026-10-01", "2026-10-22")
177 items = trustpilot.parse_trustpilot_response(response, query=topic)
178 assert [call[-1] for call in trustpilot_cli if call[1] == "info"] == [domain]
179 assert [item["url"] for item in items] == [f"https://www.trustpilot.com/review/{domain}"]
180 assert not [call for call in trustpilot_cli if call[1] == "search"]
181
182
183 def test_trustpilot_explicit_domain_overrides_the_topic(trustpilot_cli):
184 response = trustpilot.search_trustpilot(
185 "currys.co.uk", "2026-10-01", "2026-10-22", explicit_domain="www.woolworths.com.au"
186 )
187 assert response["results"][0]["domain"] == "www.woolworths.com.au"
188 assert [call[-1] for call in trustpilot_cli if call[1] == "info"] == ["www.woolworths.com.au"]
189 assert not [call for call in trustpilot_cli if call[1] == "search"]
190
191
192 def test_trustpilot_company_names_still_resolve_through_search(trustpilot_cli):
193 response = trustpilot.search_trustpilot("Currys", "2026-10-01", "2026-10-22")
194 assert response["results"][0]["domain"] == "currys.co.uk"
195 assert [call[-1] for call in trustpilot_cli if call[1] == "search"] == ["Currys"]
196 assert [call[-1] for call in trustpilot_cli if call[1] == "info"] == ["currys.co.uk"]
197
198
199 @pytest.mark.parametrize("count", [1, 3])
200 def test_startpage_keeps_snippets_with_their_results(monkeypatch, tmp_path, count):
201 second_snippet = f"Only for the second result: {tmp_path.name}"
202 page = f'''
203 <a class="result-title result-link" href="https://first.example"><h2>First result</h2></a>
204 <a class="result-title result-link" href="https://second.example"><h2>Second result</h2></a>
205 <p class="description">{second_snippet}</p>
206 <a class="result-title result-link" href="https://third.example"><h2>Third &amp; final</h2></a><p class="description">Third snippet</p>
207 '''
208
209 def get_text(url, **kwargs):
210 return page if urlsplit(url).hostname == "www.startpage.com" else ""
211
212 monkeypatch.setattr(web_search_keyless.http, "get_text", get_text)
213 items, artifact = web_search_keyless.keyless_search(
214 "example", ("2026-10-01", "2026-10-22"), {}, count=count
215 )
216 assert artifact["keyless_backend"] == "startpage"
217 assert [(item["title"], item["url"], item["snippet"]) for item in items] == [
218 ("First result", "https://first.example", ""),
219 ("Second result", "https://second.example", second_snippet),
220 ("Third & final", "https://third.example", "Third snippet"),
221 ][:count]
222
223
224 def test_startpage_titleless_result_still_bounds_the_previous_snippet(monkeypatch, tmp_path):
225 misplaced = f"Titleless result description: {tmp_path.name}"
226 page = f'''
227 <a class="result-title" href="https://first.example"><h2>First result</h2></a>
228 <a class="result-title" href="https://empty.example"><h2></h2></a>
229 <p class="description">{misplaced}</p>
230 <a class="result-title" href="https://third.example"><h2>Third result</h2></a>
231 <p class="description">Third snippet</p>
232 '''
233 monkeypatch.setattr(web_search_keyless.http, "get_text", lambda *args, **kwargs: page)
234 items = web_search_keyless._search_startpage("example", 3)
235 assert [(item["url"], item["snippet"]) for item in items] == [
236 ("https://first.example", ""),
237 ("https://third.example", "Third snippet"),
238 ]
239
239 lines PYTHON