Repository navigation
Expand file tree
/
Copy pathtest_app.py
More file actions
341 lines (313 loc) · 15.5 KB
/
Copy pathtest_app.py
File metadata and controls
341 lines (313 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import json
import os
import tempfile
import unittest
from pathlib import Path
from unittest.mock import Mock, patch
import app
RSS = """<?xml version="1.0"?>
<rss version="2.0"><channel><item>
<title>New AI agent model released</title>
<link>https://example.com/news/agent-model?utm_source=test</link>
<description>A new model for useful applications and benchmark research.</description>
<pubDate>Wed, 16 Sep 2026 09:00:00 GMT</pubDate>
</item></channel></rss>"""
INDEX = """<html><body><article><h2>
<a href="/news/agent-model">New AI agent model released</a>
</h2></article></body></html>"""
ARTICLE = """<html><head><title>New AI agent model released</title></head>
<body><main><p>This artificial intelligence model introduces a new agent architecture.</p>
<p>The research includes training, inference, open source weights, and benchmark results.</p></main></body></html>"""
class AppTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.env = patch.dict(os.environ, {"WECHAT_AUTO_SHARE_DATA_DIR": self.temp.name})
self.env.start()
app.init_db()
def tearDown(self):
self.env.stop()
self.temp.cleanup()
def create_two_source_candidates(self):
with app.connect() as conn:
sources = {
row["name"]: row
for row in conn.execute(
"SELECT * FROM sources WHERE name IN ('OpenAI News', 'Google DeepMind')"
)
}
app.store_candidate(
sources["OpenAI News"],
{"title": "OpenAI agent model released", "url": "https://example.com/openai-agent"},
app.extract_article(ARTICLE)[1],
)
app.store_candidate(
sources["Google DeepMind"],
{"title": "DeepMind agent research released", "url": "https://example.com/deepmind-agent"},
app.extract_article(ARTICLE)[1],
)
with app.connect() as conn:
return [row[0] for row in conn.execute("SELECT id FROM candidates ORDER BY id")]
def test_rss_parse_and_normalize(self):
items = app.parse_rss(RSS, "https://example.com/feed.xml")
self.assertEqual(len(items), 1)
self.assertEqual(app.normalize_url(items[0]["url"]), "https://example.com/news/agent-model")
def test_html_index_and_article_extract(self):
items = app.parse_html_index(INDEX, "https://example.com/news")
self.assertEqual(items[0]["url"], "https://example.com/news/agent-model")
title, content = app.extract_article(ARTICLE)
self.assertIn("agent model", title)
self.assertIn("benchmark", content)
def test_store_candidate_is_idempotent(self):
with app.connect() as conn:
source = conn.execute("SELECT * FROM sources WHERE kind = 'manual'").fetchone()
item = {"title": "New AI agent model released", "url": "https://example.com/news/agent-model"}
self.assertTrue(app.store_candidate(source, item, app.extract_article(ARTICLE)[1]))
self.assertFalse(app.store_candidate(source, item, app.extract_article(ARTICLE)[1]))
with app.connect() as conn:
row = conn.execute(
"SELECT general_copy, hardcore_copy FROM candidates"
).fetchone()
count = conn.execute("SELECT COUNT(*) FROM candidates").fetchone()[0]
self.assertEqual(count, 1)
self.assertIn("AI", row["general_copy"])
self.assertIn("技术", row["hardcore_copy"])
def test_scan_falls_back_to_feed_summary(self):
with app.connect() as conn:
source = conn.execute("SELECT * FROM sources WHERE name = 'OpenAI News'").fetchone()
with patch("app.fetch_text", side_effect=[RSS, ValueError("article blocked")]):
result = app.scan_source(source, 1)
self.assertEqual(result["added"], 1)
self.assertIn("已使用摘要", result["error"])
def test_local_page_renders_candidate(self):
with app.connect() as conn:
source = conn.execute("SELECT * FROM sources WHERE kind = 'manual'").fetchone()
app.store_candidate(
source,
{"title": "New AI agent model released", "url": "https://example.com/news/agent-model"},
app.extract_article(ARTICLE)[1],
)
client = app.create_web_app().test_client()
response = client.get("/")
self.assertEqual(response.status_code, 200)
page = response.get_data(as_text=True)
self.assertIn("New AI agent model released", page)
self.assertIn("保存 AI 配置", page)
self.assertIn("退出程序", page)
def test_qr_route_returns_png(self):
with app.connect() as conn:
source = conn.execute("SELECT * FROM sources WHERE kind = 'manual'").fetchone()
app.store_candidate(
source,
{"title": "New AI agent model released", "url": "https://example.com/news/agent-model"},
app.extract_article(ARTICLE)[1],
)
with app.connect() as conn:
candidate_id = conn.execute("SELECT id FROM candidates").fetchone()[0]
response = app.create_web_app().test_client().get(f"/candidate/{candidate_id}/qr.png")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.mimetype, "image/png")
self.assertTrue(response.data.startswith(b"\x89PNG\r\n\x1a\n"))
def test_candidate_status_requires_csrf_and_hides_candidate(self):
with app.connect() as conn:
source = conn.execute("SELECT * FROM sources WHERE kind = 'manual'").fetchone()
app.store_candidate(
source,
{"title": "New AI agent model released", "url": "https://example.com/news/agent-model"},
app.extract_article(ARTICLE)[1],
)
with app.connect() as conn:
candidate_id = conn.execute("SELECT id FROM candidates").fetchone()[0]
client = app.create_web_app().test_client()
self.assertEqual(
client.post(f"/candidate/{candidate_id}/status", data={"status": "published"}).status_code,
403,
)
response = client.post(
f"/candidate/{candidate_id}/status",
data={"status": "published", "csrf": app.get_setting("csrf_token")},
follow_redirects=True,
)
self.assertEqual(response.status_code, 200)
self.assertNotIn("New AI agent model released", response.get_data(as_text=True))
with app.connect() as conn:
status = conn.execute("SELECT status FROM candidates WHERE id = ?", (candidate_id,)).fetchone()[0]
self.assertEqual(status, "published")
def test_scheduled_action_runs_bounded_scan(self):
action = app.scheduled_action()
self.assertIn("scan --max-items 3", action)
self.assertIn("app.py", action)
def test_wecom_payload_requires_bounded_sender_scope(self):
with app.connect() as conn:
source = conn.execute("SELECT * FROM sources WHERE kind = 'manual'").fetchone()
app.store_candidate(
source,
{"title": "New AI agent model released", "url": "https://example.com/news/agent-model"},
app.extract_article(ARTICLE)[1],
)
with app.connect() as conn:
candidate = conn.execute(
"SELECT c.*, a.title, a.url FROM candidates c JOIN articles a ON a.id = c.article_id"
).fetchone()
with self.assertRaisesRegex(ValueError, "至少填写"):
app.build_wecom_moment_payload(candidate, "general", "", "", "")
payload = app.build_wecom_moment_payload(
candidate, "hardcore", "alice, bob", "2", "et-one"
)
self.assertEqual(payload["visible_range"]["sender_list"]["user_list"], ["alice", "bob"])
self.assertEqual(payload["visible_range"]["sender_list"]["department_list"], [2])
self.assertEqual(payload["visible_range"]["external_contact_list"]["tag_list"], ["et-one"])
self.assertEqual(payload["attachments"][0]["link"]["url"], "https://example.com/news/agent-model")
def test_wecom_submit_is_idempotent(self):
with app.connect() as conn:
source = conn.execute("SELECT * FROM sources WHERE kind = 'manual'").fetchone()
app.store_candidate(
source,
{"title": "New AI agent model released", "url": "https://example.com/news/agent-model"},
app.extract_article(ARTICLE)[1],
)
with app.connect() as conn:
candidate_id = conn.execute("SELECT id FROM candidates").fetchone()[0]
response = Mock()
response.raise_for_status.return_value = None
response.json.return_value = {"errcode": 0, "errmsg": "ok", "jobid": "job-123"}
with patch("app.wecom_access_token", return_value="token"), patch(
"app.httpx.post", return_value=response
) as post:
first = app.submit_wecom_moment(candidate_id, "general", "alice", "", "")
second = app.submit_wecom_moment(candidate_id, "general", "alice", "", "")
self.assertFalse(first["duplicate"])
self.assertTrue(second["duplicate"])
self.assertEqual(second["jobid"], "job-123")
self.assertEqual(post.call_count, 1)
with app.connect() as conn:
job = conn.execute("SELECT * FROM delivery_jobs").fetchone()
self.assertEqual(job["status"], "submitted")
self.assertEqual(job["external_id"], "job-123")
self.assertNotIn("token", job["request_json"])
def test_wecom_route_requires_explicit_confirmation(self):
with app.connect() as conn:
source = conn.execute("SELECT * FROM sources WHERE kind = 'manual'").fetchone()
app.store_candidate(
source,
{"title": "New AI agent model released", "url": "https://example.com/news/agent-model"},
app.extract_article(ARTICLE)[1],
)
with app.connect() as conn:
candidate_id = conn.execute("SELECT id FROM candidates").fetchone()[0]
response = app.create_web_app().test_client().post(
f"/candidate/{candidate_id}/wecom",
data={"csrf": app.get_setting("csrf_token"), "audience": "general", "user_list": "alice"},
)
self.assertEqual(response.status_code, 400)
def test_official_draft_preview_edit_and_exports(self):
candidate_ids = self.create_two_source_candidates()
draft_id = app.create_official_draft(candidate_ids, "general")
with app.connect() as conn:
draft = conn.execute("SELECT * FROM drafts WHERE id = ?", (draft_id,)).fetchone()
self.assertEqual(len(json.loads(draft["sources_json"])), 2)
self.assertIn("参考来源", draft["html"])
self.assertNotIn("<script>", app.markdown_body_html("<script>alert(1)</script>"))
client = app.create_web_app().test_client()
page = client.get(f"/draft/{draft_id}")
self.assertEqual(page.status_code, 200)
response = client.post(
f"/draft/{draft_id}",
data={
"csrf": app.get_setting("csrf_token"),
"title": "Edited topic",
"summary": "Edited summary",
"body": "## Findings\n\nA checked fact [1].",
},
follow_redirects=True,
)
self.assertEqual(response.status_code, 200)
self.assertIn("Edited topic", response.get_data(as_text=True))
for kind, mimetype in (("md", "text/markdown"), ("html", "text/html")):
export = client.get(f"/draft/{draft_id}/export/{kind}")
self.assertEqual(export.status_code, 200)
self.assertEqual(export.mimetype, mimetype)
self.assertIn(b"Edited topic", export.data)
cover = client.get(f"/draft/{draft_id}/cover.svg")
self.assertEqual(cover.status_code, 200)
self.assertEqual(cover.mimetype, "image/svg+xml")
def test_official_draft_requires_distinct_sources(self):
with app.connect() as conn:
source = conn.execute("SELECT * FROM sources WHERE name = 'OpenAI News'").fetchone()
for index in (1, 2):
app.store_candidate(
source,
{
"title": f"OpenAI model release {index}",
"url": f"https://example.com/openai-{index}",
},
app.extract_article(ARTICLE)[1],
)
with app.connect() as conn:
candidate_ids = [row[0] for row in conn.execute("SELECT id FROM candidates ORDER BY id")]
with self.assertRaisesRegex(ValueError, "两个不同来源"):
app.create_official_draft(candidate_ids, "hardcore")
def test_ai_official_draft_keeps_all_source_markers(self):
self.create_two_source_candidates()
with app.connect() as conn:
rows = conn.execute(
"""
SELECT a.title, a.url, a.content, s.name AS source_name
FROM candidates c JOIN articles a ON a.id = c.article_id
JOIN sources s ON s.id = a.source_id ORDER BY c.id
"""
).fetchall()
response = Mock()
response.raise_for_status.return_value = None
response.json.return_value = {
"choices": [
{
"message": {
"content": json.dumps(
{
"title": "Two-source AI update",
"summary": "A checked summary",
"introduction": "First report [1], second report [2].",
"sections": [{"heading": "What changed", "body": "Compared evidence [1][2]."}],
"conclusion": "More verification is still needed [1][2].",
}
)
}
}
]
}
with patch("app.ai_config", return_value=("https://api.example/v1", "model", "key")), patch(
"app.httpx.post", return_value=response
):
result = app.generate_draft_content(rows, "hardcore")
self.assertEqual(result["title"], "Two-source AI update")
self.assertIn("[1]", result["body"])
self.assertIn("[2]", result["body"])
def test_web_ai_config_uses_keyring(self):
client = app.create_web_app().test_client()
with patch("app.validate_public_url", return_value="https://api.example/v1"), patch(
"app.keyring.set_password"
) as save_secret:
response = client.post(
"/ai/config",
data={
"csrf": app.get_setting("csrf_token"),
"base_url": "https://api.example/v1",
"model": "model-name",
"api_key": "secret-key",
},
)
self.assertEqual(response.status_code, 302)
self.assertEqual(app.get_setting("ai_model"), "model-name")
save_secret.assert_called_once_with(app.KEYRING_SERVICE, "ai-api-key", "secret-key")
def test_schedule_changes_only_after_valid_post(self):
client = app.create_web_app().test_client()
self.assertEqual(client.post("/schedule", data={"action": "install"}).status_code, 403)
with patch("app.install_schedule") as install:
response = client.post(
"/schedule",
data={"csrf": app.get_setting("csrf_token"), "action": "install"},
)
self.assertEqual(response.status_code, 302)
install.assert_called_once_with()
if __name__ == "__main__":
unittest.main()