| 1 | """以真实浏览器 DOM 和受控作品响应验证大鱼号的关键成功/失败边界。""" |
| 2 | import copy |
| 3 | import unittest |
| 4 | from pathlib import Path |
| 5 | from types import SimpleNamespace |
| 6 | from unittest.mock import AsyncMock |
| 7 | |
| 8 | from patchright.async_api import async_playwright |
| 9 | |
| 10 | from conf import BASE_DIR, LOCAL_CHROME_PATH |
| 11 | from uploader.dayu_uploader.main import DayuVideo, wait_dayu_processing |
| 12 | from uploader.dayu_uploader.verification import verify_dayu_article, verify_dayu_video |
| 13 | |
| 14 | |
| 15 | class DayuBrowserTests(unittest.IsolatedAsyncioTestCase): |
| 16 | async def asyncSetUp(self): |
| 17 | self.playwright = await async_playwright().start() |
| 18 | self.browser = await self.playwright.chromium.launch( |
| 19 | executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=True, |
| 20 | ) |
| 21 | self.page = await self.browser.new_page() |
| 22 | self.identity = {"wmid": "a" * 32, "name": "测试账号"} |
| 23 | self.record = { |
| 24 | "content_id": "123456789012345678", "origin_id": "b" * 32, |
| 25 | "title": "大鱼号上传测试", "status": 1, "audit_status": 4, |
| 26 | "_app_extra": {"audit_remark": "内容质量不符合平台要求,可能无法获得平台推荐。"}, |
| 27 | "ucUrl": "https://mparticle.uc.cn/video.html?wm_id=" + "a" * 32 + "&wm_aid=" + "b" * 32, |
| 28 | } |
| 29 | |
| 30 | async def asyncTearDown(self): |
| 31 | await self.browser.close() |
| 32 | await self.playwright.stop() |
| 33 | |
| 34 | async def test_processing_waits_past_100_percent_and_processing(self): |
| 35 | await self.page.set_content(''' |
| 36 | <div class="article-write_video-container">文件大小不超过10G</div> |
| 37 | <script> |
| 38 | const box = document.querySelector('div'); |
| 39 | setTimeout(() => box.textContent = 'demo.mp4 正在上传中:100.0%', 30); |
| 40 | setTimeout(() => box.textContent = '视频上传成功,处理中... demo.mp4', 80); |
| 41 | setTimeout(() => box.innerHTML = '<div class="article-write_video-container-result-desc">' |
| 42 | + '<p>视频上传成功,处理完成</p><p><span>demo.mp4</span></p></div>', 550); |
| 43 | </script> |
| 44 | ''') |
| 45 | await wait_dayu_processing(self.page, "demo.mp4", timeout=3) |
| 46 | self.assertIn("处理完成", await self.page.locator("body").inner_text()) |
| 47 | |
| 48 | async def test_processing_error_overrides_success_text(self): |
| 49 | await self.page.set_content('''<div class="article-write_video-container"> |
| 50 | <p>视频上传成功,处理完成</p><p>视频时长小于5秒,请重新上传</p></div>''') |
| 51 | with self.assertRaisesRegex(RuntimeError, "小于5秒"): |
| 52 | await wait_dayu_processing(self.page, "demo.mp4", timeout=1) |
| 53 | |
| 54 | async def test_processing_has_a_deadline(self): |
| 55 | await self.page.set_content('<div class="article-write_video-container">正在上传中:100.0%</div>') |
| 56 | with self.assertRaises(TimeoutError): |
| 57 | await wait_dayu_processing(self.page, "demo.mp4", timeout=.05) |
| 58 | |
| 59 | async def make_public_context(self): |
| 60 | """公开页在本地路由中播放真实 demo,不借用任何登录状态或外网媒体。""" |
| 61 | context = await self.browser.new_context() |
| 62 | html = '''<meta charset="utf-8"><div class="pc-videoContent-test">大鱼号上传测试</div> |
| 63 | <div class="pc-userInfoContainer-test"><span>测试账号</span></div> |
| 64 | <video src="https://mparticle.uc.cn/test.mp4" preload="auto"></video>''' |
| 65 | await context.route("https://mparticle.uc.cn/video.html?**", |
| 66 | lambda route: route.fulfill(content_type="text/html", body=html)) |
| 67 | await context.route("https://mparticle.uc.cn/test.mp4", |
| 68 | lambda route: route.fulfill(content_type="video/mp4", path=str(BASE_DIR / "videos/demo.mp4"))) |
| 69 | return context |
| 70 | |
| 71 | async def test_verification_matches_id_across_pages_and_plays_without_login(self): |
| 72 | decoy = copy.deepcopy(self.record) |
| 73 | decoy.update(content_id="wrong-id", origin_id="c" * 32) |
| 74 | first = {"dataList": {"data": [decoy], "totalPage": 2}} |
| 75 | second = {"dataList": {"data": [self.record], "totalPage": 2}} |
| 76 | request = SimpleNamespace(get=AsyncMock(side_effect=[ |
| 77 | SimpleNamespace(ok=True, json=AsyncMock(return_value=first)), |
| 78 | SimpleNamespace(ok=True, json=AsyncMock(return_value=second)), |
| 79 | ])) |
| 80 | result = await verify_dayu_video( |
| 81 | SimpleNamespace(request=request), SimpleNamespace(new_context=self.make_public_context), |
| 82 | self.identity, content_id=self.record["content_id"], origin_id=self.record["origin_id"], |
| 83 | title=self.record["title"], timeout=5, public=True, |
| 84 | ) |
| 85 | self.assertTrue(result["success"]) |
| 86 | self.assertEqual(result["status"], "published") |
| 87 | self.assertEqual(result["audit_status"], 4) |
| 88 | self.assertIn("可能无法获得平台推荐", result["audit_remark"]) |
| 89 | self.assertGreater(result["public_playback"]["current_time"], .1) |
| 90 | self.assertEqual([call.kwargs["params"]["page"] for call in request.get.await_args_list], [1, 2]) |
| 91 | |
| 92 | async def test_http_200_without_business_data_is_not_success(self): |
| 93 | request = SimpleNamespace(get=AsyncMock(return_value=SimpleNamespace( |
| 94 | ok=True, json=AsyncMock(return_value={"error": "login required"}), |
| 95 | ))) |
| 96 | with self.assertRaisesRegex(RuntimeError, "dataList.data"): |
| 97 | await verify_dayu_video(SimpleNamespace(request=request), self.browser, |
| 98 | self.identity, content_id=self.record["content_id"], timeout=1, public=True) |
| 99 | |
| 100 | async def test_explicit_public_check_does_not_accept_draft(self): |
| 101 | pending = dict(self.record, status=0) |
| 102 | request = SimpleNamespace(get=AsyncMock(return_value=SimpleNamespace( |
| 103 | ok=True, json=AsyncMock(return_value={"dataList": {"data": [pending], "totalPage": 1}}), |
| 104 | ))) |
| 105 | with self.assertRaisesRegex(TimeoutError, "勿重新上传"): |
| 106 | await verify_dayu_video(SimpleNamespace(request=request), self.browser, |
| 107 | self.identity, content_id=self.record["content_id"], timeout=.05, public=True) |
| 108 | |
| 109 | async def test_default_verification_succeeds_during_review_without_public_browser(self): |
| 110 | # 审核中已经提交成功;公开 URL 即使缺失,也不应触发公开浏览器或等待审核。 |
| 111 | pending = dict(self.record, status=3, audit_status=0, ucUrl="") |
| 112 | for verify in (verify_dayu_video, verify_dayu_article): |
| 113 | with self.subTest(verify=verify.__name__): |
| 114 | request = SimpleNamespace(get=AsyncMock(return_value=SimpleNamespace( |
| 115 | ok=True, json=AsyncMock(return_value={"dataList": {"data": [pending], "totalPage": 1}})))) |
| 116 | browser = SimpleNamespace(new_context=AsyncMock(side_effect=AssertionError("不应访问公开页"))) |
| 117 | result = await verify(SimpleNamespace(request=request), browser, self.identity, |
| 118 | content_id=self.record["content_id"], timeout=1) |
| 119 | self.assertTrue(result["success"]) |
| 120 | self.assertEqual(result["status"], "submitted") |
| 121 | self.assertEqual(result["platform_status"], 3) |
| 122 | self.assertEqual(request.get.await_count, 1) |
| 123 | browser.new_context.assert_not_awaited() |
| 124 | |
| 125 | async def test_default_verification_does_not_treat_draft_as_submission(self): |
| 126 | draft = dict(self.record, status=0) |
| 127 | request = SimpleNamespace(get=AsyncMock(return_value=SimpleNamespace( |
| 128 | ok=True, json=AsyncMock(return_value={"dataList": {"data": [draft], "totalPage": 1}})))) |
| 129 | with self.assertRaisesRegex(TimeoutError, "提交发表确认"): |
| 130 | await verify_dayu_article(SimpleNamespace(request=request), self.browser, self.identity, |
| 131 | content_id=self.record["content_id"], timeout=.05) |
| 132 | |
| 133 | async def test_public_url_must_belong_to_expected_account_and_draft(self): |
| 134 | wrong_owner = dict(self.record, ucUrl=self.record["ucUrl"].replace("a" * 32, "c" * 32)) |
| 135 | request = SimpleNamespace(get=AsyncMock(return_value=SimpleNamespace( |
| 136 | ok=True, json=AsyncMock(return_value={"dataList": {"data": [wrong_owner], "totalPage": 1}}), |
| 137 | ))) |
| 138 | with self.assertRaisesRegex(RuntimeError, "主体或 origin_id 不匹配"): |
| 139 | await verify_dayu_video(SimpleNamespace(request=request), self.browser, |
| 140 | self.identity, content_id=self.record["content_id"], timeout=1, public=True) |
| 141 | |
| 142 | |
| 143 | class DayuMediaTests(unittest.TestCase): |
| 144 | def test_invalid_category_and_conditional_source_are_rejected_before_upload(self): |
| 145 | import tempfile |
| 146 | import json |
| 147 | with tempfile.TemporaryDirectory() as folder: |
| 148 | account_file = Path(folder) / "account.json" |
| 149 | account_file.write_text("{}", encoding="utf-8") |
| 150 | account_file.with_suffix(".identity.json").write_text( |
| 151 | json.dumps({"wmid": "a" * 32, "name": "测试账号"}), encoding="utf-8", |
| 152 | ) |
| 153 | for category, source, source_url, message in ( |
| 154 | ("不存在的分类", "无需标注", "", "视频分类必须为"), |
| 155 | ("科技", "转载", "", "原文链接"), |
| 156 | ("科技", "转载", "ftp://example.com/video", "原文链接"), |
| 157 | ("科技", "无需标注", "https://example.com/video", "仅信息来源为转载"), |
| 158 | ): |
| 159 | with self.subTest(category=category, source=source, source_url=source_url): |
| 160 | video = DayuVideo("大鱼号视频上传测试", BASE_DIR / "videos/demo.mp4", [], |
| 161 | account_file, BASE_DIR / "videos/demo.png", category, source, |
| 162 | source_url=source_url) |
| 163 | with self.assertRaisesRegex(ValueError, message): |
| 164 | video.validate_upload_args() |
| 165 | |
| 166 | def test_original_demo_is_rejected_before_upload(self): |
| 167 | import tempfile |
| 168 | import json |
| 169 | with tempfile.TemporaryDirectory() as folder: |
| 170 | account_file = Path(folder) / "account.json" |
| 171 | account_file.write_text("{}", encoding="utf-8") |
| 172 | account_file.with_suffix(".identity.json").write_text( |
| 173 | json.dumps({"wmid": "a" * 32, "name": "测试账号"}), encoding="utf-8", |
| 174 | ) |
| 175 | video = DayuVideo("大鱼号视频上传测试", BASE_DIR / "videos/demo.mp4", [], |
| 176 | account_file, BASE_DIR / "videos/demo.png", "其他", "无需标注") |
| 177 | with self.assertRaisesRegex(ValueError, "至少需要 5 秒"): |
| 178 | video.validate_upload_args() |
| 179 | |
| 180 | |
| 181 | if __name__ == "__main__": |
| 182 | unittest.main() |
| 183 |