返回 last30days-skill
test_x_handle_resolution.py
根目录 / tests / test_x_handle_resolution.py
1 """Entity X handles: homepage links, and the hosted-run handle decision check.
2
3 Hosted runs pass --plan, so the engine's search-based auto-resolve stands down
4 and the host model resolves handles. A skipped lookup used to cost nothing:
5 the run went ahead with no --x-handle and X never searched the subject's own
6 posts. These tests pin the keyless homepage reader and the check that makes a
7 hosted entity run either name a handle or say why there is none.
8 """
9
10 from __future__ import annotations
11
12 import io
13 import sys
14 from contextlib import redirect_stderr, redirect_stdout
15 from unittest import mock
16
17 import pytest
18
19 import last30days as cli
20 from lib import resolve
21
22 DUMMY_CONFIG = {"OPENROUTER_API_KEY": "dummy-openrouter-key-000"}
23 DIAG = {
24 "available_sources": ["reddit", "x", "hackernews"],
25 "providers": {"google": False, "openai": False, "xai": False},
26 "x_backend": None,
27 "bird_installed": False,
28 "bird_authenticated": False,
29 "bird_username": None,
30 "native_web_backend": None,
31 "permission_preflight": {},
32 }
33 PLAN_WITH_X = (
34 '{"intent":"product","freshness_mode":"balanced_recent","cluster_mode":"none",'
35 '"subqueries":[{"label":"primary","search_query":"Jev","ranking_query":'
36 '"What are people saying about Jev?","sources":["reddit","x","hackernews"],"weight":1.0}]}'
37 )
38 PLAN_WITHOUT_X = PLAN_WITH_X.replace('"x",', "")
39
40 HOMEPAGE = """
41 <html><body>
42 <a href="https://x.com/intent/tweet?text=hi">Share</a>
43 <a href="https://twitter.com/someone/status/123">Quoted post</a>
44 <p>Follow @notourhandle for updates</p>
45 <footer>
46 <a href="https://x.com/typesafeai">X</a>
47 <a href='https://twitter.com/typesafeai/'>Twitter</a>
48 <a href="https://github.com/typesafe-ai/typesafe-sdk-python">SDK</a>
49 <a href="https://github.com/typesafe-ai">GitHub</a>
50 <a href="https://github.com/features">Features</a>
51 </footer>
52 </body></html>
53 """
54
55
56 class _RetrievalReached(Exception):
57 pass
58
59
60 def _run_main(monkeypatch, argv, *, host_env=None, socials=None, diag=None):
61 for name in ("LAST30DAYS_API_KEY", "LAST30DAYS_API_BASE", "LAST30DAYS_MEMORY_DIR"):
62 monkeypatch.delenv(name, raising=False)
63 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
64 for name, value in (host_env or {}).items():
65 monkeypatch.setenv(name, value)
66 monkeypatch.setattr(sys, "argv", ["last30days.py", *argv])
67 run_mock = mock.Mock(side_effect=_RetrievalReached)
68 socials_mock = mock.Mock(return_value=socials or {"x_handle": "", "github_user": ""})
69 err = io.StringIO()
70 with mock.patch.object(cli.env, "get_config", return_value=dict(DUMMY_CONFIG)), \
71 mock.patch.object(cli.pipeline, "diagnose", mock.Mock(return_value=dict(diag or DIAG))), \
72 mock.patch.object(cli.pipeline, "run", run_mock), \
73 mock.patch("lib.resolve.auto_resolve", mock.Mock(return_value={})), \
74 mock.patch("lib.resolve.official_site_socials", socials_mock), \
75 mock.patch.object(cli.ui, "ProgressDisplay", return_value=mock.Mock()), \
76 redirect_stdout(io.StringIO()), redirect_stderr(err):
77 try:
78 rc = cli.main()
79 except _RetrievalReached:
80 rc = None
81 except SystemExit as exc:
82 rc = exc.code
83 return rc, err.getvalue(), run_mock, socials_mock
84
85
86 HOSTED = {"CLAUDECODE": "1"}
87
88
89 # --- homepage reader -------------------------------------------------------
90
91
92 def test_official_site_socials_reads_profile_links_only():
93 with mock.patch.object(resolve.http, "get_text", return_value=HOMEPAGE) as get:
94 socials = resolve.official_site_socials("typesafe.ai")
95 assert socials == {"x_handle": "typesafeai", "github_user": "typesafe-ai"}
96 assert get.call_args.args[0] == "https://typesafe.ai/"
97
98
99 def test_official_site_socials_leaves_ambiguous_accounts_unresolved():
100 page = """
101 <a href="https://x.com/happycustomer">Customer</a>
102 <a href="https://x.com/someinvestor">Investor</a>
103 <a href="https://github.com/somedependency/lib">Built on</a>
104 <a href="https://github.com/otherdependency">Also</a>
105 """
106 with mock.patch.object(resolve.http, "get_text", return_value=page):
107 assert resolve.official_site_socials("typesafe.ai") == {"x_handle": "", "github_user": ""}
108
109
110 def test_official_site_socials_prefers_the_footer_over_a_repeated_testimonial():
111 page = """
112 <a href="https://x.com/happycustomer">quote</a>
113 <a href="https://x.com/happycustomer">quote again</a>
114 <footer><a href="https://x.com/acmehq">X</a></footer>
115 """
116 with mock.patch.object(resolve.http, "get_text", return_value=page):
117 assert resolve.official_site_socials("example.com")["x_handle"] == "acmehq"
118
119
120 def test_official_site_socials_prefers_the_account_named_after_the_site():
121 page = """
122 <a href="https://x.com/happycustomer">quote</a>
123 <a href="https://x.com/TypeSafeAI">Follow us</a>
124 """
125 with mock.patch.object(resolve.http, "get_text", return_value=page):
126 assert resolve.official_site_socials("www.typesafe.ai")["x_handle"] == "TypeSafeAI"
127
128
129 def test_official_site_socials_treats_capitalizations_as_one_account():
130 page = """
131 <a href="https://x.com/TypeSafeAI">X</a>
132 <a href="https://twitter.com/typesafeai">Twitter</a>
133 <a href="https://github.com/TypeSafe-AI">GitHub</a>
134 <a href="https://github.com/typesafe-ai/sdk">SDK</a>
135 """
136 with mock.patch.object(resolve.http, "get_text", return_value=page):
137 assert resolve.official_site_socials("example.com") == {
138 "x_handle": "TypeSafeAI", "github_user": "TypeSafe-AI",
139 }
140
141
142 def test_official_site_socials_empty_when_page_unreachable():
143 with mock.patch.object(resolve.http, "get_text", return_value=None):
144 assert resolve.official_site_socials("typesafe.ai") == {"x_handle": "", "github_user": ""}
145
146
147 @pytest.mark.parametrize(
148 "site,url",
149 [
150 ("typesafe.ai", "https://typesafe.ai/"),
151 ("https://www.TypeSafe.ai/pricing?x=1", "https://www.typesafe.ai/"),
152 ("not a domain", ""),
153 ("", ""),
154 ],
155 )
156 def test_official_site_url_normalizes_to_homepage(site, url):
157 assert resolve._official_site_url(site) == url
158
159
160 def test_official_site_socials_skips_invalid_site_without_fetching():
161 with mock.patch.object(resolve.http, "get_text") as get:
162 assert resolve.official_site_socials("javascript:alert(1)") == {"x_handle": "", "github_user": ""}
163 get.assert_not_called()
164
165
166 # --- hosted handle decision check -----------------------------------------
167
168
169 def test_hosted_entity_run_planning_x_without_handle_stops(monkeypatch):
170 rc, err, run_mock, _ = _run_main(monkeypatch, ["Jev", "--plan", PLAN_WITH_X], host_env=HOSTED)
171 assert rc == cli.X_HANDLE_DECISION_EXIT
172 assert "X handle decision missing" in err
173 assert "--official-site" in err and "--no-x-handle" in err
174 run_mock.assert_not_called()
175
176
177 def test_official_site_handle_satisfies_the_check(monkeypatch):
178 rc, err, run_mock, socials_mock = _run_main(
179 monkeypatch, ["Jev", "--plan", PLAN_WITH_X, "--official-site", "typesafe.ai"],
180 host_env=HOSTED, socials={"x_handle": "typesafeai", "github_user": "typesafe-ai"},
181 )
182 assert rc is None
183 assert "@typesafeai" in err
184 socials_mock.assert_called_once_with("typesafe.ai")
185 assert run_mock.call_args.kwargs["x_handle"] == "typesafeai"
186
187
188 def test_user_x_handle_beats_the_homepage(monkeypatch):
189 rc, _err, run_mock, _ = _run_main(
190 monkeypatch,
191 ["Jev", "--plan", PLAN_WITH_X, "--official-site", "typesafe.ai", "--x-handle", "CompleteSkeptic"],
192 host_env=HOSTED, socials={"x_handle": "typesafeai", "github_user": ""},
193 )
194 assert rc is None
195 assert run_mock.call_args.kwargs["x_handle"] == "CompleteSkeptic"
196
197
198 def test_official_site_without_x_link_still_needs_a_decision(monkeypatch):
199 rc, err, _run, _ = _run_main(
200 monkeypatch, ["Jev", "--plan", PLAN_WITH_X, "--official-site", "typesafe.ai"],
201 host_env=HOSTED,
202 )
203 assert rc == cli.X_HANDLE_DECISION_EXIT
204 assert "X handle decision missing" in err
205
206
207 def test_no_x_handle_reason_satisfies_the_check(monkeypatch):
208 rc, err, _run, _ = _run_main(
209 monkeypatch,
210 ["Jev", "--plan", PLAN_WITH_X, "--no-x-handle", "official site links no X account"],
211 host_env=HOSTED,
212 )
213 assert rc is None
214 assert "No X handle: official site links no X account" in err
215
216
217 @pytest.mark.parametrize(
218 "argv",
219 [
220 ["Jev", "--plan", PLAN_WITHOUT_X],
221 ["Jev", "--plan", PLAN_WITH_X, "--quick"],
222 ["how do decision models work?", "--plan", PLAN_WITH_X],
223 ["@typesafeai", "--plan", PLAN_WITH_X],
224 ],
225 )
226 def test_check_exempts_runs_that_do_not_need_a_handle(monkeypatch, argv):
227 rc, _err, _run, _ = _run_main(monkeypatch, argv, host_env=HOSTED)
228 assert rc is None
229
230
231 def test_check_does_not_apply_when_x_will_not_run(monkeypatch):
232 # --search without x, EXCLUDE_SOURCES=x, or no X backend all drop x from
233 # diagnose's available_sources; the plan naming x must not stop the run.
234 no_x = dict(DIAG, available_sources=["reddit", "hackernews"])
235 rc, _err, _run, _ = _run_main(
236 monkeypatch, ["Jev", "--plan", PLAN_WITH_X], host_env=HOSTED, diag=no_x,
237 )
238 assert rc is None
239
240
241 def test_check_does_not_apply_outside_agent_hosts(monkeypatch):
242 rc, _err, _run, _ = _run_main(monkeypatch, ["Jev", "--plan", PLAN_WITH_X])
243 assert rc is None
244
245
246 def _dropped_or(page, *, dropped_hosts):
247 from http.client import RemoteDisconnected
248 from unittest.mock import MagicMock
249
250 def opener(req, timeout=None, **_kwargs):
251 if req.full_url.split("/")[2] in dropped_hosts:
252 raise RemoteDisconnected("Remote end closed connection without response")
253 response = MagicMock()
254 response.__enter__.return_value = response
255 response.__exit__.return_value = False
256 response.read.return_value = page.encode("utf-8")
257 response.status = 200
258 response.headers = {}
259 return response
260
261 return opener
262
263
264 def test_official_site_that_drops_the_connection_is_read_on_its_www_form():
265 stderr = io.StringIO()
266 opener = _dropped_or(HOMEPAGE, dropped_hosts={"typesafe.ai"})
267 with mock.patch.object(resolve.http, "_open_request", side_effect=opener), \
268 mock.patch.object(resolve.http.time, "sleep"), \
269 resolve.http.capture_failures() as failures, redirect_stderr(stderr):
270 socials = resolve.official_site_socials("typesafe.ai")
271 assert socials == {"x_handle": "typesafeai", "github_user": "typesafe-ai"}
272 assert "could not be fetched" not in stderr.getvalue()
273 assert failures == []
274
275
276 def test_official_site_whose_both_forms_drop_the_connection_logs_one_line():
277 stderr = io.StringIO()
278 opener = _dropped_or(HOMEPAGE, dropped_hosts={"typesafe.ai", "www.typesafe.ai"})
279 with mock.patch.object(resolve.http, "_open_request", side_effect=opener), \
280 mock.patch.object(resolve.http.time, "sleep"), \
281 resolve.http.capture_failures() as failures, redirect_stderr(stderr):
282 socials = resolve.official_site_socials("typesafe.ai")
283 assert socials == {"x_handle": "", "github_user": ""}
284 assert stderr.getvalue().count("could not be fetched") == 1
285 assert len(failures) == 1
286
286 lines PYTHON