| 1 | """验证文件正文、样式边界、图文顺序及只提交一次的实际浏览器行为。""" |
| 2 | import json |
| 3 | import tempfile |
| 4 | import unittest |
| 5 | from pathlib import Path |
| 6 | from types import SimpleNamespace |
| 7 | from unittest.mock import AsyncMock, patch |
| 8 | |
| 9 | from patchright.async_api import async_playwright |
| 10 | |
| 11 | from conf import BASE_DIR, LOCAL_CHROME_PATH |
| 12 | from uploader.dayu_uploader.article import DayuArticle |
| 13 | from uploader.dayu_uploader.article_content import load_dayu_article |
| 14 | from uploader.dayu_uploader.article_style import render_dayu_compatible_html |
| 15 | from uploader.dayu_uploader.publication import submit_dayu_publication |
| 16 | from uploader.dayu_uploader.verification import check_dayu_article_content, verify_dayu_article |
| 17 | |
| 18 | |
| 19 | class DayuArticleFileTests(unittest.TestCase): |
| 20 | def test_html_file_resolves_images_and_preserves_supported_formats(self): |
| 21 | document = load_dayu_article(BASE_DIR / "examples/dayu_article.html") |
| 22 | self.assertEqual(document.images, [(BASE_DIR / "videos/demo1.png").resolve()]) |
| 23 | self.assertEqual(document.formats["h1"], 3) |
| 24 | self.assertEqual(document.formats["strong"], 1) |
| 25 | self.assertEqual(document.manifest["image_count"], 1) |
| 26 | self.assertNotEqual(document.manifest["text_sha256"], document.manifest["structure_sha256"]) |
| 27 | |
| 28 | def test_large_plain_text_file_is_read_without_command_line_body(self): |
| 29 | with tempfile.TemporaryDirectory() as folder: |
| 30 | path = Path(folder) / "长文章.txt" |
| 31 | path.write_text("正文<&>\n" * 2800, encoding="utf-8-sig") |
| 32 | document = load_dayu_article(path) |
| 33 | self.assertEqual("".join(document.text).count("正文<&>"), 2800) |
| 34 | self.assertIn("<&>", "".join(document.parts)) |
| 35 | path.write_text("字" * 20001, encoding="utf-8") |
| 36 | with self.assertRaisesRegex(ValueError, "20000"): |
| 37 | load_dayu_article(path) |
| 38 | |
| 39 | def test_unsupported_formats_and_malformed_html_are_explicit_errors(self): |
| 40 | with tempfile.TemporaryDirectory() as folder: |
| 41 | path = Path(folder) / "article.html" |
| 42 | for html in ('<p><em>正文</em></p>', |
| 43 | '<script>alert(1)</script>', '<p>正文', '<p><strong>正文</p></strong>', |
| 44 | '<p>正文</p><img src="https://example.com/a.jpg">'): |
| 45 | with self.subTest(html=html): |
| 46 | path.write_text(html, encoding="utf-8") |
| 47 | with self.assertRaises(ValueError): |
| 48 | load_dayu_article(path) |
| 49 | |
| 50 | def test_image_order_changes_structure_digest(self): |
| 51 | with tempfile.TemporaryDirectory() as folder: |
| 52 | path = Path(folder) / "article.html" |
| 53 | image = (BASE_DIR / "videos/demo1.png").as_posix() |
| 54 | path.write_text(f'<p>前文</p><img src="{image}"><p>后文</p>', encoding="utf-8") |
| 55 | first = load_dayu_article(path).manifest |
| 56 | path.write_text(f'<p>前文</p><p>后文</p><img src="{image}">', encoding="utf-8") |
| 57 | second = load_dayu_article(path).manifest |
| 58 | self.assertEqual(first["text_sha256"], second["text_sha256"]) |
| 59 | self.assertNotEqual(first["structure_sha256"], second["structure_sha256"]) |
| 60 | |
| 61 | def test_chinese_image_path_is_decoded(self): |
| 62 | with tempfile.TemporaryDirectory() as folder: |
| 63 | image = Path(folder) / "中文图片.png" |
| 64 | image.write_bytes((BASE_DIR / "videos/demo1.png").read_bytes()) |
| 65 | path = Path(folder) / "正文.html" |
| 66 | path.write_text('<p>中文路径图片</p><img src="中文图片.png">', encoding="utf-8") |
| 67 | self.assertEqual(load_dayu_article(path).images, [image.resolve()]) |
| 68 | |
| 69 | def test_source_and_cover_conditions_are_checked_before_browser_launch(self): |
| 70 | with tempfile.TemporaryDirectory() as folder: |
| 71 | account = Path(folder) / "account.json" |
| 72 | account.write_text("{}", encoding="utf-8") |
| 73 | account.with_suffix(".identity.json").write_text( |
| 74 | json.dumps({"wmid": "a" * 32, "name": "测试账号"}), encoding="utf-8") |
| 75 | for source, link, indices, message in ( |
| 76 | ("转载", "", [], "原文链接"), |
| 77 | ("无需标注", "https://example.com", [], "仅信息来源"), |
| 78 | ("无需标注", "", [2], "超出"), |
| 79 | ("无需标注", "", [1, 1], "1 个或 3 个"), |
| 80 | ("无需标注", "", [1, 1, 1], "不同"), |
| 81 | ): |
| 82 | with self.subTest(source=source, indices=indices): |
| 83 | app = DayuArticle("图文条件检查标题", BASE_DIR / "examples/dayu_article.html", |
| 84 | account, source, source_url=link, cover_indices=indices) |
| 85 | with self.assertRaisesRegex(ValueError, message): |
| 86 | app.validate_upload_args() |
| 87 | |
| 88 | |
| 89 | class DayuArticleBrowserTests(unittest.IsolatedAsyncioTestCase): |
| 90 | async def asyncSetUp(self): |
| 91 | self.playwright = await async_playwright().start() |
| 92 | self.browser = await self.playwright.chromium.launch( |
| 93 | executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=True) |
| 94 | self.identity = {"wmid": "a" * 32, "name": "测试账号"} |
| 95 | self.record = {"content_id": "123", "origin_id": "b" * 32, |
| 96 | "title": "图文发布检查标题", "status": 1, "audit_status": 4} |
| 97 | |
| 98 | async def asyncTearDown(self): |
| 99 | await self.browser.close() |
| 100 | await self.playwright.stop() |
| 101 | |
| 102 | async def make_public_context(self): |
| 103 | context = await self.browser.new_context() |
| 104 | await context.route("https://mparticle.uc.cn/article.html?**", lambda route: route.fulfill( |
| 105 | content_type="text/html", body=self.public_html)) |
| 106 | await context.route("https://image.uc.cn/test.png", lambda route: route.fulfill( |
| 107 | content_type="image/png", path=str(BASE_DIR / "videos/demo1.png"))) |
| 108 | return context |
| 109 | |
| 110 | async def verify_article(self, manifest): |
| 111 | request = SimpleNamespace(get=AsyncMock(return_value=SimpleNamespace( |
| 112 | ok=True, json=AsyncMock(return_value={"dataList": {"data": [self.record], "totalPage": 1}})))) |
| 113 | return await verify_dayu_article( |
| 114 | SimpleNamespace(request=request), SimpleNamespace(new_context=self.make_public_context), |
| 115 | self.identity, content_id="123", title=self.record["title"], timeout=5, manifest=manifest, public=True) |
| 116 | |
| 117 | async def test_anonymous_article_checks_text_styles_images_and_order(self): |
| 118 | document = load_dayu_article(BASE_DIR / "examples/dayu_article.html") |
| 119 | html = "".join('<img src="https://image.uc.cn/test.png">' if isinstance(p, Path) else p |
| 120 | for p in document.parts) |
| 121 | self.public_html = f'''<meta charset="utf-8"><div class="index-articleContainer-test"> |
| 122 | <h1>{self.record['title']}</h1> |
| 123 | <div class="article-userInfoName-test">测试账号</div> |
| 124 | <div class="index-articleSummary-test">{html}</div></div>''' |
| 125 | result = await self.verify_article(document.manifest) |
| 126 | self.assertTrue(result["success"]) |
| 127 | self.assertTrue(result["public_article"]["content_checked"]) |
| 128 | self.assertEqual(result["public_article"]["image_count"], 1) |
| 129 | # 文字和图数相同,但图片被移到末尾,必须拒绝成功。 |
| 130 | image = '<img src="https://image.uc.cn/test.png">' |
| 131 | self.public_html = self.public_html.replace(image, "").replace('</div></div>', image + '</div></div>') |
| 132 | with self.assertRaisesRegex(RuntimeError, "顺序"): |
| 133 | await self.verify_article(document.manifest) |
| 134 | |
| 135 | @patch("uploader.dayu_uploader.publication.read_dayu_schedule", new_callable=AsyncMock, return_value={}) |
| 136 | async def test_submission_saves_ids_and_never_confirms_twice(self, read_schedule): |
| 137 | page = await self.browser.new_page() |
| 138 | await page.route("https://mp.dayu.com/dashboard/save-draft", lambda route: route.fulfill( |
| 139 | json={"data": {"_id": "b" * 32}})) |
| 140 | await page.route("https://mp.dayu.com/dashboard/submit-article", lambda route: route.fulfill( |
| 141 | json={"data": {"content_id": "123", "_id": "internal-id"}})) |
| 142 | html = '''<meta charset="utf-8"> |
| 143 | <button id="preview">发表</button><button id="confirm" hidden>确认发表</button> |
| 144 | <script> |
| 145 | document.body.dataset.confirmCount = '0'; |
| 146 | document.querySelector('#preview').onclick = async () => { |
| 147 | await fetch('/dashboard/save-draft', {method:'POST'}); |
| 148 | document.querySelector('#confirm').hidden = false; |
| 149 | }; |
| 150 | document.querySelector('#confirm').onclick = () => { |
| 151 | document.body.dataset.confirmCount = String(Number(document.body.dataset.confirmCount) + 1); |
| 152 | fetch('/dashboard/submit-article', {method:'POST'}); |
| 153 | }; |
| 154 | </script>''' |
| 155 | await page.route("https://mp.dayu.com/test-page", lambda route: route.fulfill( |
| 156 | content_type="text/html", body=html)) |
| 157 | await page.goto("https://mp.dayu.com/test-page") |
| 158 | with tempfile.TemporaryDirectory() as folder: |
| 159 | result = {"success": False} |
| 160 | path = Path(folder) / "result.json" |
| 161 | await submit_dayu_publication(page, result, path) |
| 162 | self.assertEqual(await page.locator("body").get_attribute("data-confirm-count"), "1") |
| 163 | self.assertEqual(result["status"], "submitted") |
| 164 | self.assertEqual(result["origin_id"], "b" * 32) |
| 165 | self.assertEqual(json.loads(path.read_text(encoding="utf-8"))["content_id"], "123") |
| 166 | self.assertTrue(result["success"]) |
| 167 | self.assertTrue(json.loads(path.read_text(encoding="utf-8"))["success"]) |
| 168 | # HTTP 成功但没有最终作品 ID,不能沿用草稿 ID 误报发表成功。 |
| 169 | await page.unroute("https://mp.dayu.com/dashboard/submit-article") |
| 170 | await page.route("https://mp.dayu.com/dashboard/submit-article", lambda route: route.fulfill( |
| 171 | json={"error": "submission rejected"})) |
| 172 | await page.goto("https://mp.dayu.com/test-page") |
| 173 | rejected = {"success": False} |
| 174 | with self.assertRaisesRegex(RuntimeError, "未返回 content_id"): |
| 175 | await submit_dayu_publication(page, rejected, path) |
| 176 | self.assertFalse(rejected["success"]) |
| 177 | self.assertEqual(rejected["status"], "submission_unknown") |
| 178 | await page.unroute("https://mp.dayu.com/dashboard/submit-article") |
| 179 | await page.route("https://mp.dayu.com/dashboard/submit-article", lambda route: route.fulfill( |
| 180 | json={"data": {"content_id": "123"}})) |
| 181 | # 定时先核对服务端保存值,再确认一次;列表查询超时只保留原 ID,不得重试确认。 |
| 182 | for scenario in ("scheduled", "wrong_time", "query_timeout"): |
| 183 | with self.subTest(scenario=scenario): |
| 184 | await page.goto("https://mp.dayu.com/test-page") |
| 185 | timed = {"success": False, "schedule": "2027-01-01T10:30:00+08:00"} |
| 186 | read_schedule.side_effect = RuntimeError("定时时间不一致") if scenario == "wrong_time" else None |
| 187 | with patch("uploader.dayu_uploader.publication.wait_dayu_publication", new_callable=AsyncMock) as query: |
| 188 | query.return_value = {"status": 5} |
| 189 | if scenario == "query_timeout": |
| 190 | query.side_effect = TimeoutError("查询超时") |
| 191 | if scenario == "scheduled": |
| 192 | await submit_dayu_publication(page, timed, path) |
| 193 | self.assertEqual(timed["status"], "scheduled") |
| 194 | self.assertTrue(timed["schedule_verified"]) |
| 195 | self.assertEqual(query.call_args.kwargs["schedule"], timed["schedule"]) |
| 196 | else: |
| 197 | with self.assertRaisesRegex((RuntimeError, TimeoutError), "不一致|查询超时"): |
| 198 | await submit_dayu_publication(page, timed, path) |
| 199 | self.assertFalse(timed["success"]) |
| 200 | count = "0" if scenario == "wrong_time" else "1" |
| 201 | self.assertEqual(await page.locator("body").get_attribute("data-confirm-count"), count) |
| 202 | saved = json.loads(path.read_text(encoding="utf8")) |
| 203 | self.assertEqual(saved["origin_id"], "b" * 32) |
| 204 | if scenario == "query_timeout": |
| 205 | self.assertEqual(saved["content_id"], "123") |
| 206 | self.assertEqual(saved["status"], "submission_unknown") |
| 207 | |
| 208 | async def test_theme_conversion_preserves_all_theme_content_images_and_colors(self): |
| 209 | page = await self.browser.new_page() |
| 210 | await page.route("https://image.uc.cn/test.png", lambda route: route.fulfill( |
| 211 | content_type="image/png", path=str(BASE_DIR / "videos/demo1.png"))) |
| 212 | for theme in ("default", "grace", "simple", "modern"): |
| 213 | with self.subTest(theme=theme): |
| 214 | document = load_dayu_article(BASE_DIR / "examples/article.md", theme) |
| 215 | image = '<img src="https://image.uc.cn/test.png" data-infoed="1" data-width="735">' |
| 216 | rendered = await render_dayu_compatible_html(page, document.content_html, [image]) |
| 217 | document.manifest["dayu_style"] = rendered["expectations"] |
| 218 | await page.set_content('<div id="body">' + rendered["html"] + '</div>') |
| 219 | body = page.locator("#body") |
| 220 | await check_dayu_article_content(body, document.manifest) |
| 221 | self.assertEqual(await body.locator("[style]").count(), 0) |
| 222 | self.assertEqual(await body.locator("img").get_attribute("data-width"), "735") |
| 223 | self.assertTrue(rendered["expectations"]["text_colors"]) |
| 224 | # 属性虽在,但被目标页 CSS 覆盖时必须拒绝,不能只检查 font[color] 存在。 |
| 225 | await page.add_style_tag(content="font { color: lime !important; }") |
| 226 | with self.assertRaisesRegex(RuntimeError, "主题"): |
| 227 | await check_dayu_article_content(body, document.manifest) |
| 228 | |
| 229 | async def test_transparent_colors_nested_emphasis_and_large_text(self): |
| 230 | page = await self.browser.new_page() |
| 231 | html = '<div style="background:#000;color:rgba(255,255,255,.5)"><p>前文<strong>重点</strong></p>' + '<p>正文</p>' * 5000 + '</div>' |
| 232 | rendered = await render_dayu_compatible_html(page, html, []) |
| 233 | self.assertEqual(rendered["expectations"]["text_colors"][0]["color"], "rgb(128, 128, 128)") |
| 234 | await page.set_content(rendered["html"]) |
| 235 | self.assertEqual(await page.locator("strong").inner_text(), "重点") |
| 236 | self.assertEqual(await page.locator("p").count(), 5001) |
| 237 | with self.assertRaisesRegex(Exception, "图片数量"): |
| 238 | await render_dayu_compatible_html(page, '<img src="local.png">', []) |
| 239 | |
| 240 | @patch("uploader.dayu_uploader.publication.read_dayu_schedule", new_callable=AsyncMock, return_value={}) |
| 241 | async def test_styled_submission_checks_server_preview_before_confirming(self, read_schedule): |
| 242 | context = await self.browser.new_context() |
| 243 | page = await context.new_page() |
| 244 | rendered = await render_dayu_compatible_html(page, '<p style="color:red">主题正文</p>', []) |
| 245 | from utils.article_content import ArticleDocument |
| 246 | document = ArticleDocument('<p>主题正文</p>', BASE_DIR) |
| 247 | document.manifest["dayu_style"] = rendered["expectations"] |
| 248 | saved_bodies = [] |
| 249 | async def save(route): |
| 250 | from urllib.parse import parse_qs |
| 251 | saved_bodies.append(parse_qs(route.request.post_data)) |
| 252 | await route.fulfill(json={"data": {"_id": "b" * 32, |
| 253 | "previewUrl": "https://mparticle.uc.cn/preview.html?wm_aid=" + "b" * 32}}) |
| 254 | # context 级路由模拟服务器,page 级路由仍由生产代码实际改写本次保存请求。 |
| 255 | await page.context.route("https://mp.dayu.com/dashboard/save-draft", save) |
| 256 | await page.route("https://mp.dayu.com/dashboard/submit-article", lambda route: route.fulfill( |
| 257 | json={"data": {"content_id": "123"}})) |
| 258 | preview_html = '<div class="article-content">' + rendered["html"] + '</div>' |
| 259 | await page.context.route("https://mparticle.uc.cn/preview.html?**", lambda route: route.fulfill( |
| 260 | content_type="text/html; charset=utf-8", body=preview_html)) |
| 261 | await page.route("https://mp.dayu.com/test", lambda route: route.fulfill(content_type="text/html", body=''' |
| 262 | <meta charset="utf-8"><button id="save">发表</button><button id="submit" hidden>确认发表</button> |
| 263 | <script>window.confirms=0; |
| 264 | save.onclick=async()=>{await fetch('/dashboard/save-draft',{method:'POST',body:new URLSearchParams({content:'被编辑器清理的正文',title:'测试标题',simpleMode:'true'})});submit.hidden=false}; |
| 265 | submit.onclick=()=>{window.confirms++;fetch('/dashboard/submit-article',{method:'POST'})};</script>''')) |
| 266 | with tempfile.TemporaryDirectory() as folder: |
| 267 | path = Path(folder) / "result.json" |
| 268 | for styled in (True, False): |
| 269 | await page.goto("https://mp.dayu.com/test") |
| 270 | result = {"success": False, "manifest": document.manifest, "style_check": {"preview_checked": False}} |
| 271 | if not styled: |
| 272 | preview_html = '<div class="article-content"><p>主题正文</p></div>' |
| 273 | with self.assertRaisesRegex(RuntimeError, "主题"): |
| 274 | await submit_dayu_publication(page, result, path, rendered["html"]) |
| 275 | self.assertEqual(await page.evaluate("window.confirms", isolated_context=False), 0) |
| 276 | self.assertEqual(result["status"], "preview_ready") |
| 277 | self.assertEqual(json.loads(path.read_text(encoding="utf8"))["origin_id"], "b" * 32) |
| 278 | else: |
| 279 | await submit_dayu_publication(page, result, path, rendered["html"]) |
| 280 | self.assertTrue(result["style_check"]["preview_checked"]) |
| 281 | self.assertEqual(await page.evaluate("window.confirms", isolated_context=False), 1) |
| 282 | self.assertEqual(saved_bodies[-1]["content"], [rendered["html"]]) |
| 283 | self.assertEqual(saved_bodies[-1]["simpleMode"], ["true"]) |
| 284 | self.assertEqual(saved_bodies[-1]["title"], ["测试标题"]) |
| 285 | |
| 286 | |
| 287 | if __name__ == "__main__": |
| 288 | unittest.main() |
| 289 |