| 1 | import sau_commands.instagram |
| 2 | """Instagram 的业务响应、账号边界和实际 DOM/事件回归。""" |
| 3 | import asyncio |
| 4 | import contextlib |
| 5 | import io |
| 6 | import json |
| 7 | import tempfile |
| 8 | import unittest |
| 9 | from pathlib import Path |
| 10 | from unittest.mock import AsyncMock, patch |
| 11 | |
| 12 | from patchright.async_api import async_playwright |
| 13 | |
| 14 | import sau_cli |
| 15 | from uploader.meta_uploader.insgraph_uploader.main import ( |
| 16 | InstagramUploader, _is_instagram_logged_out, instagram_created_media, instagram_response_payload, |
| 17 | _dismiss_optional_prompt, |
| 18 | ) |
| 19 | from uploader.meta_uploader.insgraph_uploader.posts import instagram_post_id, find_instagram_post |
| 20 | |
| 21 | |
| 22 | class InstagramContractTests(unittest.TestCase): |
| 23 | def test_final_response_requires_matching_owner_caption_and_id(self): |
| 24 | media = {'id': '123_42', 'pk': '123', 'code': 'ABC', 'user': {'pk': '42'}, 'caption': {'text': 'caption'}} |
| 25 | payload = {'status': 'ok', 'media': media} |
| 26 | self.assertEqual(instagram_created_media(payload, owner_id='42', caption='caption'), media) |
| 27 | self.assertEqual(instagram_response_payload('for (;;);{"payload":{"did_delete":true}}')['payload']['did_delete'], True) |
| 28 | for bad in ({'payload': {'statusCode': 202}}, {'status': 'ok'}, {'status': 'fail', 'media': media}): |
| 29 | with self.subTest(bad=bad), self.assertRaises(RuntimeError): |
| 30 | instagram_created_media(bad, owner_id='42', caption='caption') |
| 31 | for owner, caption in [('99', 'caption'), ('42', 'another')]: |
| 32 | with self.assertRaises(RuntimeError): |
| 33 | instagram_created_media(payload, owner_id=owner, caption=caption) |
| 34 | |
| 35 | def test_real_url_shapes_and_external_url_rejection(self): |
| 36 | for path in ('p/ABC', 'reel/ABC/', 'creator/p/ABC/', 'creator/reel/ABC/?hl=en'): |
| 37 | self.assertEqual(instagram_post_id('https://www.instagram.com/' + path), 'ABC') |
| 38 | for url in ('https://instagram.com.evil/p/ABC/', 'http://instagram.com/p/ABC/', |
| 39 | 'https://instagram.com/creator/', 'https://bad@instagram.com/p/ABC/', |
| 40 | 'https://instagram.com:8443/p/ABC/'): |
| 41 | with self.subTest(url=url), self.assertRaises(ValueError): |
| 42 | instagram_post_id(url) |
| 43 | |
| 44 | def test_caption_limit_and_mutually_exclusive_media(self): |
| 45 | with self.assertRaises(ValueError): |
| 46 | InstagramUploader('unused.json', title='x' * 2201, image_files=['image.png']) |
| 47 | with self.assertRaises(ValueError): |
| 48 | InstagramUploader('unused.json', title='title', image_files=['image.png'], video_file='video.mp4') |
| 49 | |
| 50 | def test_verify_and_delete_are_reachable_from_cli(self): |
| 51 | for action in ('verify', 'delete'): |
| 52 | args = sau_cli.build_parser().parse_args(['instagram', action, '--account', 'creator', |
| 53 | '--post-url', 'https://www.instagram.com/p/ABC/', '--expected-text', 'caption']) |
| 54 | operation = AsyncMock(return_value={'status': 'deleted' if action == 'delete' else 'published'}) |
| 55 | with patch('sau_commands.instagram.instagram_post_action', operation), contextlib.redirect_stdout(io.StringIO()): |
| 56 | self.assertEqual(asyncio.run(sau_cli.dispatch(args)), 0) |
| 57 | self.assertEqual(operation.await_args.kwargs['delete'], action == 'delete') |
| 58 | |
| 59 | def test_cover_cli_reaches_uploader_and_invalid_cover_stops_before_browser(self): |
| 60 | with tempfile.TemporaryDirectory() as folder: |
| 61 | video, cover = Path(folder)/'video.mp4', Path(folder)/'cover.PNG' |
| 62 | video.touch() |
| 63 | cover.touch() |
| 64 | args = sau_cli.build_parser().parse_args(['instagram', 'upload-video', '--account', 'creator', |
| 65 | '--file', str(video), '--thumbnail', str(cover), '--title', 'caption']) |
| 66 | uploader = AsyncMock(return_value={'status': 'published'}) |
| 67 | with patch.object(InstagramUploader, 'upload', uploader), contextlib.redirect_stdout(io.StringIO()): |
| 68 | self.assertEqual(asyncio.run(sau_cli.dispatch(args)), 0) |
| 69 | # 单独核对请求到构造函数的传递,避免只测 parser 丢失后续接线。 |
| 70 | request = sau_commands.instagram.InstagramUploadRequest('creator', 'caption', '', [], video_file=video, thumbnail=cover) |
| 71 | with patch('sau_commands.instagram.InstagramUploader') as constructor: |
| 72 | constructor.return_value.upload = AsyncMock(return_value={}) |
| 73 | asyncio.run(sau_commands.instagram.upload_instagram_content(request)) |
| 74 | self.assertEqual(constructor.call_args.kwargs['thumbnail'], cover) |
| 75 | with self.assertRaisesRegex(ValueError, '仅用于视频'): |
| 76 | InstagramUploader('unused', title='caption', image_files=[cover], thumbnail=cover) |
| 77 | for invalid in (Path(folder)/'missing.png', Path(folder)/'cover.gif'): |
| 78 | if invalid.suffix == '.gif': |
| 79 | invalid.touch() |
| 80 | app = InstagramUploader('unused', title='caption', video_file=video, thumbnail=invalid) |
| 81 | with patch('uploader.meta_uploader.insgraph_uploader.main._open_instagram_page', AsyncMock()) as launch: |
| 82 | with self.assertRaises((FileNotFoundError, ValueError)): |
| 83 | asyncio.run(app.upload()) |
| 84 | launch.assert_not_called() |
| 85 | |
| 86 | |
| 87 | class InstagramBrowserRegressionTests(unittest.TestCase): |
| 88 | def test_optional_prompts_present_absent_and_failed_dismissal(self): |
| 89 | """按实际图标与按钮层级构造 DOM;覆盖延迟提示、缺席及点击未关闭的异常。""" |
| 90 | async def scenario(): |
| 91 | async with async_playwright() as p: |
| 92 | browser = await p.chromium.launch(channel='chrome', headless=True) |
| 93 | page = await browser.new_page() |
| 94 | try: |
| 95 | # 只保留真实页面的业务结构;不同语言按钮不参与生产定位。 |
| 96 | html = '''<script> |
| 97 | function notification(){document.body.insertAdjacentHTML('beforeend', |
| 98 | `<div role="dialog" id="notifications"> |
| 99 | <img src="/images/instagram/xig/ico/xxhdpi_launcher.png?test"> |
| 100 | <div class="_a9-z"><button onclick="throw Error('wrong action')">Enable</button> |
| 101 | <button onclick="this.closest('[role=dialog]').remove()">後で</button></div></div>`);} |
| 102 | function create(){document.body.insertAdjacentHTML('beforeend', |
| 103 | `<div role="dialog"><input type="file" accept="image/jpeg,video/mp4" onchange="upload()"></div>`);} |
| 104 | function upload(){setTimeout(()=>{ |
| 105 | document.querySelector('[role=dialog]').insertAdjacentHTML('beforeend', |
| 106 | '<div class="_ac76"><div role="button">Next</div></div>'); |
| 107 | if(document.body.dataset.prompts==='true') document.body.insertAdjacentHTML('beforeend', |
| 108 | `<div role="dialog"><img src="/images/instagram/clips/reels_nux_icon.png?test"> |
| 109 | <div class="_a9-z"><div><div><span><button onclick="throw Error('wrong action')">詳しく見る</button></span></div> |
| 110 | <div><button onclick="this.closest('[role=dialog]').remove()">OK</button></div></div></div></div>`); |
| 111 | },250);} |
| 112 | if(document.body.dataset.prompts==='true') setTimeout(notification,250); |
| 113 | </script>''' |
| 114 | for prompts in (True, False): |
| 115 | navigation = ''.join( |
| 116 | '<a class="_a6hd" href="#" ' + ('onclick="create()"' if i == 1 else '') |
| 117 | + '><span aria-selected="false">Navigation</span></a>' for i in range(4)) |
| 118 | await page.set_content(f'<body data-prompts="{str(prompts).lower()}">{navigation}{html}</body>') |
| 119 | with tempfile.TemporaryDirectory() as folder: |
| 120 | video = Path(folder)/'video.mp4' |
| 121 | video.touch() |
| 122 | app = InstagramUploader('unused', title='caption', video_file=video) |
| 123 | await app._upload_files(page) |
| 124 | self.assertEqual(await page.get_by_role('dialog').count(), 1) |
| 125 | self.assertEqual(await page.locator('._ac76 [role=button]').count(), 1) |
| 126 | await page.set_content('<div role="dialog"><button>Unrelated dialog</button></div>') |
| 127 | known = page.get_by_role('dialog').filter(has=page.locator('img[src*="reels_nux_icon"]')) |
| 128 | self.assertFalse(await _dismiss_optional_prompt(known, known.get_by_role('button'))) |
| 129 | self.assertEqual(await page.get_by_role('dialog').count(), 1) |
| 130 | # 已出现的已知提示若点击后未消失,必须保留异常,不能当作缺席吞掉。 |
| 131 | await page.set_content('<div role="dialog"><button>Cannot close</button></div>') |
| 132 | page.set_default_timeout(300) |
| 133 | from patchright.async_api import TimeoutError as BrowserTimeoutError |
| 134 | with self.assertRaises(BrowserTimeoutError): |
| 135 | await _dismiss_optional_prompt(page.get_by_role('dialog'), page.get_by_role('button')) |
| 136 | finally: |
| 137 | await browser.close() |
| 138 | asyncio.run(scenario()) |
| 139 | |
| 140 | def test_cover_waits_for_actual_preview_and_rejects_wrong_image(self): |
| 141 | """真实 Chrome 中延迟替换预览,核对原图字节;错误预览必须停在编辑页。""" |
| 142 | async def scenario(): |
| 143 | import base64 |
| 144 | import struct |
| 145 | import zlib |
| 146 | # 构造带正确 CRC 的 1×1 RGB PNG,避免依赖额外图像库或损坏的压缩样例。 |
| 147 | def chunk(kind, data): |
| 148 | return struct.pack('!I', len(data)) + kind + data + struct.pack('!I', zlib.crc32(kind + data)) |
| 149 | png = (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!2I5B', 1, 1, 8, 2, 0, 0, 0)) |
| 150 | + chunk(b'IDAT', zlib.compress(b'\x00\xff\x00\x00')) + chunk(b'IEND', b'')) |
| 151 | async with async_playwright() as p: |
| 152 | browser = await p.chromium.launch(channel='chrome', headless=True) |
| 153 | page = await browser.new_page() |
| 154 | try: |
| 155 | html = '''<input type="file" accept="image/jpeg,image/png" id="outside"> |
| 156 | <div role="dialog"><div class="_ac76"><div role="heading">crop</div> |
| 157 | <button role="button" onclick="advance()">任意语言</button></div><section id="media"></section></div> |
| 158 | <script>let step=0;function advance(){step++; |
| 159 | const h=document.querySelector('[role=heading]'); |
| 160 | if(step===1){h.textContent='edit'; document.querySelector('#media').innerHTML= |
| 161 | `<input type="file" accept="image/jpeg,image/png" onchange="coverChanged(this)"> |
| 162 | <video></video><div style="background-image:url(old)"></div>`; |
| 163 | }else{h.textContent='compose';document.querySelector('#media').innerHTML+= |
| 164 | '<div contenteditable="true" role="textbox" data-lexical-editor="true"></div>';}} |
| 165 | function coverChanged(input){setTimeout(()=>{const blob=document.body.dataset.wrong ? |
| 166 | new Blob([Uint8Array.from(atob('PNG_BASE64'), c=>c.charCodeAt(0))],{type:'image/png'}) : input.files[0]; |
| 167 | document.querySelector('video + div').style.backgroundImage=`url("${URL.createObjectURL(blob)}")`; |
| 168 | },250);}</script>''' |
| 169 | html = html.replace('PNG_BASE64', base64.b64encode(png).decode()) |
| 170 | await page.route('https://www.instagram.com/**', lambda route: route.fulfill(body=html, content_type='text/html')) |
| 171 | with tempfile.TemporaryDirectory() as folder: |
| 172 | cover = Path(folder)/'cover.png' |
| 173 | cover.write_bytes(png) |
| 174 | app = InstagramUploader('unused', title='caption', video_file='video.mp4', thumbnail=cover) |
| 175 | await page.goto('https://www.instagram.com/') |
| 176 | await app._advance_media_editor(page) |
| 177 | self.assertEqual(await page.locator('[role=heading]').inner_text(), 'compose') |
| 178 | self.assertEqual(await page.locator('#outside').evaluate('e=>e.files.length'), 0) |
| 179 | await page.reload() |
| 180 | # 可解码但非指定文件的预览同样不能通过(本次改用不同有效 PNG 文件字节)。 |
| 181 | cover.write_bytes(png + b'other image bytes') |
| 182 | await page.locator('body').evaluate("e=>e.dataset.wrong='true'") |
| 183 | with self.assertRaisesRegex(RuntimeError, '预览与指定图片不匹配'): |
| 184 | await app._advance_media_editor(page) |
| 185 | self.assertEqual(await page.locator('[role=heading]').inner_text(), 'edit') |
| 186 | finally: |
| 187 | await browser.close() |
| 188 | asyncio.run(scenario()) |
| 189 | |
| 190 | def test_delayed_login_foreign_owner_and_async_reel_creation(self): |
| 191 | """用真实 Chrome DOM 和网络事件验证:延迟页面不能误判、同配文不能跨作者、202 必须等正式作品。""" |
| 192 | async def scenario(): |
| 193 | async with async_playwright() as p: |
| 194 | browser = await p.chromium.launch(channel='chrome', headless=True) |
| 195 | page = await browser.new_page() |
| 196 | try: |
| 197 | await page.set_content('''<script>setTimeout(() => { |
| 198 | document.body.innerHTML = '<a href="/direct/inbox/?hl=ja">Inbox</a>'; |
| 199 | }, 250)</script>''') |
| 200 | self.assertFalse(await _is_instagram_logged_out(page)) |
| 201 | foreign = '''<meta property="og:url" content="https://www.instagram.com/p/ABC/"> |
| 202 | <meta property="instapp:owner_user_id" content="99"><main>same caption</main>''' |
| 203 | await page.route('https://www.instagram.com/p/ABC/', lambda r: r.fulfill(body=foreign, content_type='text/html')) |
| 204 | with self.assertRaisesRegex(RuntimeError, '作者'): |
| 205 | await find_instagram_post(page, post_url='https://www.instagram.com/p/ABC/', expected_text='same caption', owner_id='42') |
| 206 | await page.unroute_all() |
| 207 | own = foreign.replace('content="99"', 'content="42"') + '<meta name="description" content="different caption"><meta property="al:ios:url" content="instagram://media?id=123">' |
| 208 | await page.route('https://www.instagram.com/p/ABC/', lambda r: r.fulfill(body=own, content_type='text/html')) |
| 209 | with self.assertRaisesRegex(RuntimeError, '配文元数据'): |
| 210 | await find_instagram_post(page, post_url='https://www.instagram.com/p/ABC/', expected_text='same caption', owner_id='42') |
| 211 | await page.unroute_all() |
| 212 | own = own.replace('different caption', 'same caption') |
| 213 | await page.route('https://www.instagram.com/p/ABC/', lambda r: r.fulfill(body=own, content_type='text/html')) |
| 214 | verified = await find_instagram_post(page, post_url='https://www.instagram.com/p/ABC/', expected_text='same caption', owner_id='42') |
| 215 | self.assertEqual(verified['content_id'], '123_42') |
| 216 | await page.unroute_all() |
| 217 | html = '''<div role="dialog"><div class="_ac76"> |
| 218 | <div role="button" onclick="document.body.dataset.clicks=String(Number(document.body.dataset.clicks||0)+1); submitPost()">任意语言</div> |
| 219 | </div><div role="textbox" contenteditable="true" data-lexical-editor="true"></div></div> |
| 220 | <script>async function submitPost() { |
| 221 | await fetch('/api/v1/media/configure_to_clips/', {method:'POST'}); |
| 222 | document.body.dataset.processing='true'; |
| 223 | setTimeout(() => fetch('/api/v1/media/configure_to_clips/', {method:'POST'}), 350); |
| 224 | }</script>''' |
| 225 | calls = 0 |
| 226 | async def route(request): |
| 227 | nonlocal calls |
| 228 | if '/configure_to_clips/' not in request.request.url: |
| 229 | await request.fulfill(body=html, content_type='text/html') |
| 230 | return |
| 231 | calls += 1 |
| 232 | if calls == 1: |
| 233 | payload = {'payload': {'statusCode': 202}} |
| 234 | else: |
| 235 | payload = {'payload': {'media': {'id': '123_42', 'code': 'ABC', 'user': {'pk': '42'}, 'caption': {'text': 'caption'}}}} |
| 236 | await request.fulfill(body='for (;;);' + json.dumps(payload), content_type='application/json') |
| 237 | await page.route('https://www.instagram.com/**', route) |
| 238 | await page.goto('https://www.instagram.com/') |
| 239 | with tempfile.TemporaryDirectory() as folder: |
| 240 | target = Path(folder)/'result.json' |
| 241 | app = InstagramUploader('unused.json', title='caption', video_file='video.mp4', result_file=target) |
| 242 | task = asyncio.create_task(app._publish(page, {'user_id': '42', 'username': 'creator'})) |
| 243 | await page.locator('body[data-processing="true"]').wait_for() |
| 244 | self.assertFalse(task.done(), '202 后仍必须等待最终创建响应') |
| 245 | self.assertNotEqual(app.result['status'], 'published') |
| 246 | await task |
| 247 | self.assertEqual(app.result['status'], 'published') |
| 248 | self.assertEqual(app.result['content_id'], '123_42') |
| 249 | self.assertEqual(await page.locator('body').get_attribute('data-clicks'), '1') |
| 250 | self.assertEqual(calls, 2) |
| 251 | finally: |
| 252 | await browser.close() |
| 253 | asyncio.run(scenario()) |
| 254 |