返回 Social Auto Upload
test_zhihu_uploader.py
根目录 / tests / test_zhihu_uploader.py
1 """知乎的原稿完整性与命令契约;本地页面不冒充知乎实际上传验收。"""
2 import asyncio
3 import contextlib
4 import io
5 import tempfile
6 import unittest
7 from pathlib import Path
8 from unittest.mock import patch
9
10 from patchright.async_api import async_playwright
11
12 from conf import LOCAL_CHROME_PATH
13 from sau_cli import build_parser
14 from uploader.zhihu_uploader.article import ZhihuArticle
15 from uploader.zhihu_uploader.video import ZhihuVideo
16 from utils.article_render import load_article
17
18
19 class ZhihuCLITests(unittest.TestCase):
20 def test_video_at_or_below_100kb_is_rejected_before_browser_launch(self):
21 with tempfile.TemporaryDirectory() as folder:
22 video = Path(folder) / "video.mp4"
23 for size in (84693, 102400):
24 with self.subTest(size=size):
25 video.write_bytes(b"\0" * size)
26 app = ZhihuVideo("视频标题示例", video, "account.json", "", None, [], None, "original")
27 with self.assertRaisesRegex(ValueError, "必须大于 100KB"):
28 app.validate_upload_args()
29
30 def test_video_can_preview_runtime_choices_without_guessing_category(self):
31 with tempfile.TemporaryDirectory() as folder:
32 video = Path(folder) / "video.mp4"
33 video.touch()
34 args = build_parser().parse_args([
35 "zhihu", "upload-video", "--account", "creator", "--file", str(video),
36 "--title", "视频标题示例", "--originality", "original", "--show-options",
37 ])
38 self.assertTrue(args.show_options)
39 self.assertIsNone(args.category)
40 self.assertFalse(hasattr(args, "topics"))
41 self.assertFalse(hasattr(args, "category_second"))
42
43 def test_unknown_menu_value_returns_all_legal_choices(self):
44 app = ZhihuVideo("标题", "video.mp4", "account.json", "", None, [], None, "original")
45 with self.assertRaisesRegex(ValueError, "科学、生活"):
46 asyncio.run(app.select_option("所属领域", "不存在", ["科学", "生活"]))
47
48 def test_cli_rejects_unknown_category_and_video_mark(self):
49 with tempfile.TemporaryDirectory() as folder:
50 video = Path(folder) / "video.mp4"
51 video.touch()
52 command = ["zhihu", "upload-video", "--account", "creator", "--file", str(video),
53 "--title", "视频标题示例", "--originality", "original"]
54 parser = build_parser()
55 args = parser.parse_args(command + ["--category", "教育", "--video-mark", "含 AI 生成内容"])
56 self.assertEqual(args.category, "教育")
57 for flag in ("--category", "--video-mark"):
58 with self.subTest(flag=flag), contextlib.redirect_stderr(io.StringIO()):
59 with self.assertRaises(SystemExit) as error:
60 parser.parse_args(command + [flag, "不存在"])
61 self.assertEqual(error.exception.code, 2)
62
63 def test_interactive_menu_accepts_index_and_shows_all_choices(self):
64 app = ZhihuVideo("标题", "video.mp4", "account.json", "", None, [], None, "original")
65 output = io.StringIO()
66 with patch("sys.stdin.isatty", return_value=True), patch("builtins.input", return_value="2"), contextlib.redirect_stderr(output):
67 value = asyncio.run(app.select_option("所属领域", None, ["科学", "生活"]))
68 self.assertEqual(value, "生活")
69 self.assertIn("1. 科学", output.getvalue())
70 self.assertIn("2. 生活", output.getvalue())
71
72
73 class ZhihuArticleContentTests(unittest.IsolatedAsyncioTestCase):
74 async def test_original_order_is_required_and_format_loss_is_detected(self):
75 with tempfile.TemporaryDirectory() as folder:
76 root = Path(folder)
77 (root / "one.png").write_bytes(b"local resource")
78 source = root / "article.html"
79 source.write_text('<h2>标题</h2><p>第一段<strong>重点</strong></p>'
80 '<img src="one.png"><p>第二段<a href="https://example.com/">链接</a></p>', encoding="utf-8")
81 app = ZhihuArticle("文章", source, root / "account.json")
82 app.document = load_article(source)
83 original = app.document.content_html
84 async with async_playwright() as playwright:
85 browser = await playwright.chromium.launch(executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=True)
86 try:
87 page = await browser.new_page()
88 await page.set_content(original)
89 await app.check_article_body(page.locator("body"))
90 # 真实知乎 DraftJS 使用 styled span,并在链接文字前插入零宽字符。
91 await page.set_content(original.replace('<strong>', '<span style="font-weight: bold">')
92 .replace('</strong>', '</span>')
93 .replace('>链接</a>', '>\u200b链接</a>'))
94 await app.check_article_body(page.locator("body"))
95 # 图片数量相同,但移到文末必须失败,防止再次退回统一追加图片。
96 await page.set_content('<h2>标题</h2><p>第一段<strong>重点</strong></p>'
97 '<p>第二段<a href="https://example.com/">链接</a></p><img src="one.png">')
98 with self.assertRaisesRegex(RuntimeError, "图片位置"):
99 await app.check_article_body(page.locator("body"))
100 await page.set_content(original.replace("<strong>", "<span>").replace("</strong>", "</span>"))
101 with self.assertRaisesRegex(RuntimeError, "格式不一致"):
102 await app.check_article_body(page.locator("body"))
103 await page.set_content(original.replace("https://example.com/", "https://example.org/"))
104 with self.assertRaisesRegex(RuntimeError, "链接"):
105 await app.check_article_body(page.locator("body"))
106 finally:
107 await browser.close()
108
108 lines PYTHON