返回 last30days-skill
test_html_publish.py
根目录 / tests / test_html_publish.py
1 """Tests for optional hosted HTML publishing."""
2
3 from __future__ import annotations
4
5 import io
6 import json
7 import os
8 import sys
9 import tempfile
10 import unittest
11 from contextlib import redirect_stderr, redirect_stdout
12 from pathlib import Path
13 from unittest import mock
14 from urllib.error import HTTPError
15
16 import last30days as cli
17 from lib import html_publish, schema
18
19
20 def _report(topic: str = "OpenClaw") -> schema.Report:
21 return schema.Report(
22 topic=topic,
23 range_from="2026-05-01",
24 range_to="2026-05-31",
25 generated_at="2026-05-31T00:00:00+00:00",
26 provider_runtime=schema.ProviderRuntime(
27 reasoning_provider="local",
28 planner_model="mock-planner",
29 rerank_model="mock-rerank",
30 ),
31 query_plan=schema.QueryPlan(
32 intent="concept",
33 freshness_mode="balanced_recent",
34 cluster_mode="none",
35 raw_topic=topic,
36 subqueries=[
37 schema.SubQuery(
38 label="primary",
39 search_query=topic,
40 ranking_query=topic,
41 sources=["grounding"],
42 )
43 ],
44 source_weights={"grounding": 1.0},
45 ),
46 clusters=[],
47 ranked_candidates=[],
48 items_by_source={"grounding": []},
49 errors_by_source={},
50 )
51
52
53 def _diag() -> dict[str, object]:
54 return {
55 "available_sources": ["grounding"],
56 "providers": {"google": True, "openai": False, "xai": False},
57 "x_backend": None,
58 "bird_installed": True,
59 "bird_authenticated": False,
60 "bird_username": None,
61 "native_web_backend": "brave",
62 }
63
64
65 class _FakeResponse:
66 def __init__(self, payload: object):
67 self.payload = payload
68
69 def __enter__(self):
70 return self
71
72 def __exit__(self, *_args):
73 return False
74
75 def read(self) -> bytes:
76 return json.dumps(self.payload).encode("utf-8")
77
78
79 class HtmlPublishModuleTests(unittest.TestCase):
80 def test_publish_posts_html_and_password(self):
81 captured = {}
82
83 def opener(request, timeout):
84 captured["timeout"] = timeout
85 captured["url"] = request.full_url
86 captured["headers"] = dict(request.header_items())
87 captured["body"] = json.loads(request.data.decode("utf-8"))
88 return _FakeResponse(
89 {
90 "url": "https://example.ht-ml.app",
91 "site_id": "site_123",
92 "status": "active",
93 "update_key": "secret-update-key",
94 }
95 )
96
97 result = html_publish.publish_html(
98 "<html>ok</html>",
99 password="share-pass",
100 opener=opener,
101 )
102
103 self.assertEqual("https://api.ht-ml.app/v1/sites", captured["url"])
104 self.assertEqual({"html_content": "<html>ok</html>", "password": "share-pass"}, captured["body"])
105 self.assertEqual("https://example.ht-ml.app", result["url"])
106 self.assertEqual("secret-update-key", result["update_key"])
107
108 def test_publish_rejects_http_error_with_message(self):
109 def opener(_request, timeout):
110 raise HTTPError(
111 "https://api.ht-ml.app/v1/sites",
112 400,
113 "Bad Request",
114 {},
115 io.BytesIO(b'{"message":"HTML content is required"}'),
116 )
117
118 with self.assertRaisesRegex(html_publish.HtmlPublishError, "HTML content is required"):
119 html_publish.publish_html("<html></html>", opener=opener)
120
121 def test_publish_rejects_json_response_that_is_not_an_object(self):
122 def opener(_request, timeout):
123 return _FakeResponse(["https://site.ht-ml.app"])
124
125 with self.assertRaisesRegex(html_publish.HtmlPublishError, "unexpected JSON response"):
126 html_publish.publish_html("<html></html>", opener=opener)
127
128 def test_publish_html_documents_publishes_each_named_document(self):
129 with mock.patch.object(
130 html_publish,
131 "publish_html",
132 side_effect=[{"url": "https://one.ht-ml.app"}, {"url": "https://two.ht-ml.app"}],
133 ) as publish:
134 results = html_publish.publish_html_documents(
135 {"one": "<html>one</html>", "two": "<html>two</html>"},
136 password="shared",
137 )
138
139 self.assertEqual(
140 {"one": {"url": "https://one.ht-ml.app"}, "two": {"url": "https://two.ht-ml.app"}},
141 results,
142 )
143 self.assertEqual(
144 [
145 mock.call(
146 "<html>one</html>", password="shared",
147 endpoint=html_publish.DEFAULT_ENDPOINT, opener=None, timeout=30,
148 ),
149 mock.call(
150 "<html>two</html>", password="shared",
151 endpoint=html_publish.DEFAULT_ENDPOINT, opener=None, timeout=30,
152 ),
153 ],
154 publish.call_args_list,
155 )
156
157
158 class HtmlPublishCliTests(unittest.TestCase):
159 def test_publish_requires_html_emit(self):
160 with mock.patch.object(sys, "argv", [
161 "last30days.py",
162 "OpenClaw",
163 "--emit=md",
164 "--publish-html",
165 ]), mock.patch.object(cli.env, "get_config", return_value={}):
166 stderr = io.StringIO()
167 with redirect_stderr(stderr):
168 rc = cli.main()
169 self.assertEqual(2, rc)
170 self.assertIn("--publish-html requires --emit=html", stderr.getvalue())
171
172 def test_publish_writes_url_metadata_without_update_key(self):
173 with tempfile.TemporaryDirectory() as tmp:
174 output_path = Path(tmp) / "brief.html"
175 with mock.patch.object(cli.env, "get_config", return_value={}), \
176 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \
177 mock.patch.object(cli.pipeline, "run", return_value=_report()), \
178 mock.patch.object(cli, "emit_output", return_value="<html>brief</html>"), \
179 mock.patch.object(cli, "publish_rendered_html", wraps=cli.publish_rendered_html) as publish_wrapper, \
180 mock.patch("lib.html_publish.publish_html", return_value={
181 "url": "https://site.ht-ml.app",
182 "site_id": "site_123",
183 "status": "active",
184 "update_key": "secret-update-key",
185 }), \
186 mock.patch.object(sys, "argv", [
187 "last30days.py",
188 "OpenClaw",
189 "--emit=html",
190 "--output",
191 str(output_path),
192 "--publish-html",
193 ]), \
194 mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"}, clear=False):
195 stdout = io.StringIO()
196 stderr = io.StringIO()
197 with redirect_stdout(stdout), redirect_stderr(stderr):
198 rc = cli.main()
199
200 self.assertEqual(0, rc)
201 publish_wrapper.assert_called_once()
202 self.assertEqual("<html>brief</html>", output_path.read_text(encoding="utf-8"))
203 self.assertIn("Published HTML to https://site.ht-ml.app", stderr.getvalue())
204 self.assertNotIn("secret-update-key", stdout.getvalue())
205 self.assertNotIn("secret-update-key", stderr.getvalue())
206 metadata = json.loads((Path(str(output_path) + ".publish.json")).read_text(encoding="utf-8"))
207 self.assertEqual("https://site.ht-ml.app", metadata["url"])
208 self.assertNotIn("update_key", metadata)
209
210 def test_publish_uses_password_from_environment(self):
211 with tempfile.TemporaryDirectory() as tmp:
212 output_path = Path(tmp) / "brief.html"
213 with mock.patch.object(cli.env, "get_config", return_value={}), \
214 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \
215 mock.patch.object(cli.pipeline, "run", return_value=_report()), \
216 mock.patch.object(cli, "emit_output", return_value="<html>brief</html>"), \
217 mock.patch("lib.html_publish.publish_html", return_value={
218 "url": "https://site.ht-ml.app",
219 }) as publish_mock, \
220 mock.patch.object(sys, "argv", [
221 "last30days.py",
222 "OpenClaw",
223 "--emit=html",
224 "--output",
225 str(output_path),
226 "--publish-html",
227 ]), \
228 mock.patch.dict(os.environ, {
229 "LAST30DAYS_SKIP_PREFLIGHT": "1",
230 "LAST30DAYS_PUBLISH_PASSWORD": "share-pass",
231 }, clear=False):
232 stdout = io.StringIO()
233 stderr = io.StringIO()
234 with redirect_stdout(stdout), redirect_stderr(stderr):
235 rc = cli.main()
236
237 self.assertEqual(0, rc)
238 self.assertEqual("share-pass", publish_mock.call_args.kwargs["password"])
239
240 def test_publish_metadata_failure_still_reports_url(self):
241 with tempfile.TemporaryDirectory() as tmp:
242 output_path = Path(tmp) / "brief.html"
243 with mock.patch.object(cli.env, "get_config", return_value={}), \
244 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \
245 mock.patch.object(cli.pipeline, "run", return_value=_report()), \
246 mock.patch.object(cli, "emit_output", return_value="<html>brief</html>"), \
247 mock.patch("lib.html_publish.publish_html", return_value={
248 "url": "https://site.ht-ml.app",
249 "site_id": "site_123",
250 }), \
251 mock.patch.object(cli, "_write_publish_metadata", side_effect=PermissionError("denied")), \
252 mock.patch.object(sys, "argv", [
253 "last30days.py",
254 "OpenClaw",
255 "--emit=html",
256 "--output",
257 str(output_path),
258 "--publish-html",
259 ]), \
260 mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"}, clear=False):
261 stdout = io.StringIO()
262 stderr = io.StringIO()
263 with redirect_stdout(stdout), redirect_stderr(stderr):
264 rc = cli.main()
265
266 self.assertEqual(0, rc)
267 self.assertIn("Published HTML to https://site.ht-ml.app", stderr.getvalue())
268 self.assertIn("Publish metadata warning", stderr.getvalue())
269
270 def test_publish_failure_preserves_local_output(self):
271 with tempfile.TemporaryDirectory() as tmp:
272 output_path = Path(tmp) / "brief.html"
273 with mock.patch.object(cli.env, "get_config", return_value={}), \
274 mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \
275 mock.patch.object(cli.pipeline, "run", return_value=_report()), \
276 mock.patch.object(cli, "emit_output", return_value="<html>brief</html>"), \
277 mock.patch("lib.html_publish.publish_html", side_effect=html_publish.HtmlPublishError("timeout")), \
278 mock.patch.object(sys, "argv", [
279 "last30days.py",
280 "OpenClaw",
281 "--emit=html",
282 "--output",
283 str(output_path),
284 "--publish-html",
285 ]), \
286 mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"}, clear=False):
287 stdout = io.StringIO()
288 stderr = io.StringIO()
289 with redirect_stdout(stdout), redirect_stderr(stderr):
290 rc = cli.main()
291
292 self.assertEqual(0, rc)
293 self.assertEqual("<html>brief</html>", output_path.read_text(encoding="utf-8"))
294 self.assertIn("HTML publish failed: timeout", stderr.getvalue())
295
296
297 if __name__ == "__main__":
298 unittest.main()
299
299 lines PYTHON