| 1 | """原稿解析与本地浏览器内容核对;线上发表验收另有真实 CLI 结果记录。""" |
| 2 | import asyncio |
| 3 | import json |
| 4 | import tempfile |
| 5 | import unittest |
| 6 | from pathlib import Path |
| 7 | from unittest.mock import AsyncMock, MagicMock, Mock, patch |
| 8 | |
| 9 | from patchright.async_api import async_playwright |
| 10 | |
| 11 | from conf import LOCAL_CHROME_PATH |
| 12 | from sau_cli import build_parser, resolve_account_file |
| 13 | from uploader.xueqiu_uploader.article import XueqiuArticle |
| 14 | from uploader.xueqiu_uploader.content import load_xueqiu_article |
| 15 | from uploader.xueqiu_uploader.verification import check_xueqiu_article_content, query_xueqiu_article, verify_xueqiu_result |
| 16 | |
| 17 | |
| 18 | class XueqiuInputTests(unittest.TestCase): |
| 19 | def test_cli_uses_article_file_instead_of_appending_images(self): |
| 20 | args = build_parser().parse_args([ |
| 21 | 'xueqiu', 'upload-article', '--account', 'test', '--title', '标题', |
| 22 | '--content-file', str(Path(__file__)), '--visibility', '私人', |
| 23 | '--declaration', '本文包含AI生成内容', |
| 24 | ]) |
| 25 | self.assertFalse(args.prepare_only) |
| 26 | self.assertFalse(args.headless) |
| 27 | self.assertFalse(hasattr(args, 'images')) |
| 28 | self.assertEqual(resolve_account_file('xueqiu', 'test').name, 'xueqiu_test.json') |
| 29 | |
| 30 | def test_relative_images_stay_between_original_paragraphs(self): |
| 31 | with tempfile.TemporaryDirectory() as folder: |
| 32 | root = Path(folder) |
| 33 | (root / 'image.png').write_bytes(b'test') |
| 34 | source = root / 'article.html' |
| 35 | source.write_text('<h1 style="color:red">标题</h1><p>前文</p><img src="image.png"><h2>次标题</h2><p>后文</p>', encoding='utf-8') |
| 36 | document = load_xueqiu_article(source) |
| 37 | self.assertEqual(document.images, [root / 'image.png']) |
| 38 | self.assertEqual(document.sequence, ['标题', '前文', '\x00IMG\x00', '次标题', '后文']) |
| 39 | self.assertEqual(document.tags['h4'], 2) |
| 40 | self.assertNotIn('style=', document.content_html) |
| 41 | self.assertIn('自定义样式使用雪球原生样式', document.normalizations) |
| 42 | |
| 43 | def test_markdown_keeps_heading_and_image_position(self): |
| 44 | with tempfile.TemporaryDirectory() as folder: |
| 45 | root = Path(folder) |
| 46 | (root / 'image.png').write_bytes(b'test') |
| 47 | source = root / 'article.md' |
| 48 | source.write_text('# 标题\n\n**前文**\n\n\n\n## 小标题\n\n后文', encoding='utf-8') |
| 49 | document = load_xueqiu_article(source) |
| 50 | self.assertEqual(document.source_format, 'markdown') |
| 51 | self.assertEqual(document.tags['h4'], 2) |
| 52 | self.assertEqual(document.tags['strong'], 1) |
| 53 | self.assertEqual(document.images, [root / 'image.png']) |
| 54 | self.assertLess(document.sequence.index('前文'), document.sequence.index('\x00IMG\x00')) |
| 55 | self.assertGreater(document.sequence.index('后文'), document.sequence.index('\x00IMG\x00')) |
| 56 | |
| 57 | def test_numbered_lists_keep_visible_numbers(self): |
| 58 | with tempfile.TemporaryDirectory() as folder: |
| 59 | source = Path(folder) / 'article.html' |
| 60 | source.write_text('<ol start="3"><li>甲</li><li>乙</li></ol>', encoding='utf-8') |
| 61 | document = load_xueqiu_article(source) |
| 62 | self.assertIn('3. 甲', ''.join(document.text)) |
| 63 | self.assertIn('4. 乙', ''.join(document.text)) |
| 64 | |
| 65 | def test_unsupported_structure_fails_before_browser(self): |
| 66 | with tempfile.TemporaryDirectory() as folder: |
| 67 | source = Path(folder) / 'article.html' |
| 68 | source.write_text('<table><tr><td>表格</td></tr></table>', encoding='utf-8') |
| 69 | with self.assertRaisesRegex(ValueError, 'table'): |
| 70 | XueqiuArticle('标题', source, Path(folder) / 'account.json').validate_upload_args() |
| 71 | |
| 72 | |
| 73 | class XueqiuContentTests(unittest.IsolatedAsyncioTestCase): |
| 74 | async def asyncSetUp(self): |
| 75 | self.folder = tempfile.TemporaryDirectory() |
| 76 | root = Path(self.folder.name) |
| 77 | (root / 'image.png').write_bytes(b'test') |
| 78 | source = root / 'article.html' |
| 79 | source.write_text('<h2>小标题</h2><p><strong>前文</strong><a href="https://xueqiu.com/">链接</a></p><img src="image.png"><p>后文</p>', encoding='utf-8') |
| 80 | self.document = load_xueqiu_article(source) |
| 81 | self.playwright = await async_playwright().start() |
| 82 | self.browser = await self.playwright.chromium.launch(executable_path=LOCAL_CHROME_PATH or None, channel='chrome', headless=True) |
| 83 | self.page = await self.browser.new_page() |
| 84 | |
| 85 | async def asyncTearDown(self): |
| 86 | await self.browser.close() |
| 87 | await self.playwright.stop() |
| 88 | self.folder.cleanup() |
| 89 | |
| 90 | async def test_native_bold_and_heading_are_accepted(self): |
| 91 | await self.page.set_content('<h4>小标题</h4><p><b>前文</b><a href="https://xueqiu.com/">链接</a></p><img><p>后文</p>') |
| 92 | await check_xueqiu_article_content(self.page.locator('body'), self.document) |
| 93 | |
| 94 | async def test_moving_image_to_end_is_rejected_with_same_image_count(self): |
| 95 | await self.page.set_content('<h4>小标题</h4><p><b>前文</b><a href="https://xueqiu.com/">链接</a></p><p>后文</p><img>') |
| 96 | with self.assertRaisesRegex(RuntimeError, '段间图片位置'): |
| 97 | await check_xueqiu_article_content(self.page.locator('body'), self.document) |
| 98 | |
| 99 | async def test_lost_heading_structure_is_rejected(self): |
| 100 | await self.page.set_content('<p>小标题</p><p><b>前文</b><a href="https://xueqiu.com/">链接</a></p><img><p>后文</p>') |
| 101 | with self.assertRaisesRegex(RuntimeError, '结构不一致'): |
| 102 | await check_xueqiu_article_content(self.page.locator('body'), self.document) |
| 103 | |
| 104 | async def test_changed_link_target_is_rejected(self): |
| 105 | await self.page.set_content('<h4>小标题</h4><p><b>前文</b><a href="https://example.com/">链接</a></p><img><p>后文</p>') |
| 106 | with self.assertRaisesRegex(RuntimeError, '链接文字或目标'): |
| 107 | await check_xueqiu_article_content(self.page.locator('body'), self.document) |
| 108 | |
| 109 | async def test_wrong_image_is_rejected_even_at_correct_position(self): |
| 110 | await self.page.set_content('<h4>小标题</h4><p><b>前文</b><a href="https://xueqiu.com/">链接</a></p><img src="//xqimg.imedao.com/wrong.png"><p>后文</p>') |
| 111 | with self.assertRaisesRegex(RuntimeError, '图片内容或顺序'): |
| 112 | await check_xueqiu_article_content(self.page.locator('body'), self.document, |
| 113 | ['https://xqimg.imedao.com/expected.png']) |
| 114 | |
| 115 | async def test_protocol_relative_uploaded_image_is_accepted(self): |
| 116 | await self.page.set_content('<h4>小标题</h4><p><b>前文</b><a href="https://xueqiu.com/">链接</a></p><img src="//xqimg.imedao.com/expected.png"><p>后文</p>') |
| 117 | await check_xueqiu_article_content(self.page.locator('body'), self.document, |
| 118 | ['https://xqimg.imedao.com/expected.png']) |
| 119 | |
| 120 | async def test_verify_rejects_changed_source_before_opening_browser(self): |
| 121 | root = Path(self.folder.name) |
| 122 | account = root / 'account.json' |
| 123 | account.with_suffix('.identity.json').write_text(json.dumps({'uid': '123', 'name': '测试'}), encoding='utf-8') |
| 124 | result = root / 'result.json' |
| 125 | result.write_text(json.dumps({'identity': {'uid': '123'}, 'content_id': '789', |
| 126 | 'content_file': str(root / 'article.html'), |
| 127 | 'manifest': {'structure_sha256': 'original'}}), encoding='utf-8') |
| 128 | with self.assertRaisesRegex(ValueError, '原稿与发表时'): |
| 129 | await verify_xueqiu_result(account, result) |
| 130 | |
| 131 | async def test_old_result_with_content_error_is_not_reported_as_success(self): |
| 132 | root = Path(self.folder.name) |
| 133 | account = root / 'account.json' |
| 134 | account.with_suffix('.identity.json').write_text(json.dumps({'uid': '123', 'name': '测试'}), encoding='utf-8') |
| 135 | result = root / 'result.json' |
| 136 | result.write_text(json.dumps({'identity': {'uid': '123'}, 'content_id': '789', |
| 137 | 'error': '正文核对失败'}), encoding='utf-8') |
| 138 | with self.assertRaisesRegex(ValueError, '保留核对错误'): |
| 139 | await verify_xueqiu_result(account, result) |
| 140 | |
| 141 | async def test_verify_rejects_wrong_account_before_opening_browser(self): |
| 142 | root = Path(self.folder.name) |
| 143 | account = root / 'account.json' |
| 144 | account.with_suffix('.identity.json').write_text(json.dumps({'uid': '123', 'name': '测试'}), encoding='utf-8') |
| 145 | result = root / 'result.json' |
| 146 | result.write_text(json.dumps({'identity': {'uid': '456'}, 'content_id': '789'}), encoding='utf-8') |
| 147 | with self.assertRaisesRegex(ValueError, '账号不一致'): |
| 148 | await verify_xueqiu_result(account, result) |
| 149 | |
| 150 | |
| 151 | class XueqiuQueryTests(unittest.IsolatedAsyncioTestCase): |
| 152 | """模拟分页响应,保证原作品查询不会退化为重发或无限翻页。""" |
| 153 | |
| 154 | async def test_original_id_can_be_found_on_later_page(self): |
| 155 | first = Mock(ok=True, status=200) |
| 156 | first.url = 'https://mp.xueqiu.com/xq/query/v1/search/long?type=success&page=1&count=10' |
| 157 | first.json = AsyncMock(return_value={'page': 1, 'maxPage': 2, 'list': [{'id': 111}]}) |
| 158 | first.request.all_headers = AsyncMock(return_value={'x-test': 'test-header'}) |
| 159 | record = {'id': 789, 'user_id': 123, 'title': '原作品', 'is_private': True} |
| 160 | second = Mock(ok=True, status=200) |
| 161 | second.json = AsyncMock(return_value={'page': 2, 'maxPage': 2, 'list': [record]}) |
| 162 | page = Mock() |
| 163 | page.goto = AsyncMock() |
| 164 | page.get_by_role.return_value.click = AsyncMock() |
| 165 | page.context.request.get = AsyncMock(return_value=second) |
| 166 | page.expect_response.return_value = MagicMock() |
| 167 | page.expect_response.return_value.__aenter__ = AsyncMock() |
| 168 | page.expect_response.return_value.__aexit__ = AsyncMock(return_value=False) |
| 169 | future = asyncio.get_running_loop().create_future() |
| 170 | future.set_result(first) |
| 171 | page.expect_response.return_value.__aenter__.return_value.value = future |
| 172 | with patch('uploader.xueqiu_uploader.verification.read_xueqiu_identity', AsyncMock(return_value={'uid': '123'})): |
| 173 | actual = await query_xueqiu_article(page, {'uid': '123'}, '789', '原作品', '私人') |
| 174 | self.assertEqual(actual, record) |
| 175 | self.assertIn('page=2', page.context.request.get.call_args.args[0]) |
| 176 | self.assertEqual(page.context.request.get.call_args.kwargs['headers'], {'x-test': 'test-header'}) |
| 177 | page.context.request.post.assert_not_called() |
| 178 | |
| 179 | async def test_repeated_page_stops_without_republishing(self): |
| 180 | response = Mock(ok=True, status=200) |
| 181 | response.url = 'https://mp.xueqiu.com/xq/query/v1/search/long?type=success&page=1&count=10' |
| 182 | response.json = AsyncMock(return_value={'page': 1, 'maxPage': 3, 'list': []}) |
| 183 | response.request.all_headers = AsyncMock(return_value={}) |
| 184 | page = Mock() |
| 185 | page.goto = AsyncMock() |
| 186 | page.get_by_role.return_value.click = AsyncMock() |
| 187 | page.context.request.get = AsyncMock(return_value=response) |
| 188 | page.expect_response.return_value = MagicMock() |
| 189 | page.expect_response.return_value.__aenter__ = AsyncMock() |
| 190 | page.expect_response.return_value.__aexit__ = AsyncMock(return_value=False) |
| 191 | future = asyncio.get_running_loop().create_future() |
| 192 | future.set_result(response) |
| 193 | page.expect_response.return_value.__aenter__.return_value.value = future |
| 194 | with patch('uploader.xueqiu_uploader.verification.read_xueqiu_identity', AsyncMock(return_value={'uid': '123'})): |
| 195 | with self.assertRaisesRegex(RuntimeError, '重复返回同一页'): |
| 196 | await query_xueqiu_article(page, {'uid': '123'}, '789') |
| 197 | page.context.request.get.assert_awaited_once() |
| 198 | page.context.request.post.assert_not_called() |
| 199 | |
| 200 | |
| 201 | if __name__ == '__main__': |
| 202 | unittest.main() |
| 203 |