| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207 |
- """Browser-check the local authentic-dialogue display, not business facts."""
- from pathlib import Path
- import base64
- import functools
- import hashlib
- import http.server
- import json
- import subprocess
- import tempfile
- import threading
- import time
- from urllib.parse import quote
- from urllib.request import urlopen
- import websocket
- WORK = Path(__file__).resolve().parent
- OUT = WORK / 'browser'
- OUT.mkdir(exist_ok=True)
- class Handler(http.server.SimpleHTTPRequestHandler):
- def log_message(self, *args):
- pass
- def list_directory(self, path):
- self.send_error(404)
- return None
- server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), functools.partial(Handler, directory=str(WORK)))
- threading.Thread(target=server.serve_forever, daemon=True).start()
- base = 'http://127.0.0.1:' + str(server.server_port)
- profile = Path(tempfile.mkdtemp(prefix='ksf-live-case-browser-'))
- edge = 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
- proc = subprocess.Popen([edge, '--headless=new', '--disable-gpu', '--remote-debugging-port=0', '--disable-background-networking', '--disable-component-update', '--disable-sync', '--disable-extensions', '--no-first-run', '--no-default-browser-check', '--user-data-dir=' + str(profile), 'about:blank'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
- seq = 0
- ws = None
- errors, requests, checks = [], [], []
- try:
- deadline = time.monotonic() + 20
- while not (profile / 'DevToolsActivePort').exists():
- assert time.monotonic() < deadline and proc.poll() is None
- time.sleep(.1)
- port = (profile / 'DevToolsActivePort').read_text().splitlines()[0]
- page = next(p for p in json.load(urlopen('http://127.0.0.1:' + port + '/json/list', timeout=5)) if p['type'] == 'page')
- ws = websocket.create_connection(page['webSocketDebuggerUrl'], timeout=20, suppress_origin=True, http_no_proxy=['127.0.0.1', 'localhost'])
- def call(method, params=None):
- global seq
- seq += 1
- rid = seq
- ws.send(json.dumps({'id': rid, 'method': method, 'params': params or {}}))
- while True:
- msg = json.loads(ws.recv())
- if msg.get('id') == rid:
- assert 'error' not in msg, msg
- return msg.get('result', {})
- if msg.get('method') == 'Runtime.exceptionThrown':
- errors.append(msg['params'])
- if msg.get('method') == 'Network.requestWillBeSent':
- requests.append(msg['params']['request']['url'])
- def ev(code, promise=False):
- result = call('Runtime.evaluate', {'expression': code, 'returnByValue': True, 'awaitPromise': promise})
- assert 'exceptionDetails' not in result, result
- return result['result'].get('value')
- def settle():
- ev('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))', True)
- call('Page.enable')
- call('Runtime.enable')
- call('Network.enable')
- call('Network.setBlockedURLs', {'urls': ['https://*']})
- call('Page.navigate', {'url': base + '/' + quote('案例样板演示.html')})
- ev('new Promise((resolve,reject)=>{const end=Date.now()+12000;const poll=()=>{if(document.querySelectorAll("[data-view]").length===15)return resolve(true);if(Date.now()>end)return reject(Error("load timeout"));setTimeout(poll,50)};poll()})', True)
- expected = {
- 'prompt': (WORK / 'rounds/R01/prompt-r6-short.txt').read_text(encoding='utf-8'),
- 'reply': (WORK / 'rounds/R01/reply-display.md').read_text(encoding='utf-8'),
- 'followup': (WORK / 'rounds/R02/prompt-display.txt').read_text(encoding='utf-8'),
- 'supplement': (WORK / 'rounds/R02/reply-display.md').read_text(encoding='utf-8'),
- 'verification': (WORK / 'rounds/R03/prompt-display.txt').read_text(encoding='utf-8'),
- 'reviewed': (WORK / 'rounds/R03/reply-display.md').read_text(encoding='utf-8'),
- 'comparison-request': (WORK / 'rounds/R04/prompt-display.txt').read_text(encoding='utf-8'),
- 'comparison': (WORK / 'rounds/R04/reply-display.md').read_text(encoding='utf-8'),
- 'specifications-request': (WORK / 'rounds/R05/prompt-current.txt').read_text(encoding='utf-8'),
- 'specifications': (WORK / 'rounds/R05/reply-display.md').read_text(encoding='utf-8'),
- 'consumer-request': (WORK / 'rounds/R06/prompt-verbatim.txt').read_text(encoding='utf-8'),
- 'consumer': (WORK / 'rounds/R06/reply-display.md').read_text(encoding='utf-8'),
- 'checklist-request': (WORK / 'rounds/R07/prompt-verbatim.txt').read_text(encoding='utf-8'),
- 'checklist': (WORK / 'rounds/R07/reply-display.md').read_text(encoding='utf-8'),
- }
- assert ev('JSON.parse(document.querySelector("#dialogue-data").textContent)') == expected
- assert ev('document.querySelectorAll(".raw pre").length') == 0
- ev('window.screeningContent=document.documentElement.innerHTML.replace(/data:image\\/[^;]+;base64,[A-Za-z0-9+/=]+/g,"[embedded image]")')
- assert not ev('/D[12]-(?:\\d\\d|N)|课表|skill|r6|待转发|王刚001|我们的审阅/i.test(window.screeningContent)')
- assert not ev('/本轮不付费|未付费测试|零费用|新增费用|免费公开|paidCalls/.test(window.screeningContent)')
- for version, round_id in [('v1', 'R02'), ('v2', 'R03')]:
- assert ev('document.querySelector(' + json.dumps('[data-atlas="' + version + '"]') + ').srcdoc') == (WORK / f'rounds/{round_id}/artifacts/atlas-display.html').read_text(encoding='utf-8')
- assert ev('document.querySelector("[data-atlas=products]").srcdoc') == (WORK / 'rounds/R04/artifacts/comparison-display.html').read_text(encoding='utf-8')
- assert ev('document.querySelector("[data-atlas=four-products]").srcdoc') == (WORK / 'rounds/R05/artifacts/four-products-display.html').read_text(encoding='utf-8')
- assert ev('document.querySelector("[data-atlas=consumer]").srcdoc') == (WORK / 'rounds/R06/artifacts/consumer-research-display.html').read_text(encoding='utf-8')
- assert ev('document.querySelector("[data-atlas=checklist]").srcdoc') == (WORK / 'rounds/R07/artifacts/checklist-display.html').read_text(encoding='utf-8')
- # Check original archive hashes, not just consistency of the display copies.
- edits = json.loads((WORK / 'presentation-edits.json').read_bytes())
- for path, digest in edits['originalFileSha256'].items():
- assert hashlib.sha256((WORK / path).read_bytes()).hexdigest() == digest, path
- assert edits['originalFileSha256']['rounds/R01/reply-verbatim.md'] == '9be5a3ca2bf65a93eb324d871cecb5dc30c2d5b145e87cb578c7fe6abc3e7465'
- assert edits['originalFileSha256']['rounds/R02/artifacts/atlas-received.html'] == '3e1266bd89be7319a4a3a60f926944f81634964219d68c16410cc36d66cff1f4'
- assert edits['originalFileSha256']['rounds/R03/artifacts/atlas-received.html'] == '4d74feea33f265dbad084c1f344adc7e533103505cd37a84b317a62df4a12cdb'
- assert edits['originalFileSha256']['rounds/R04/artifacts/comparison-received.html'] == '31ad9ca3f6cedfcc33f69c3dbff41f7c43ce584048a5edacf0b76156fbb8dc9f'
- assert edits['originalFileSha256']['rounds/R05/artifacts/four-products-received.html'] == '949bdc8db4423e66128e6afd48c7fd10e5df445f54ec6c60b65b52cefe609ac9'
- assert edits['originalFileSha256']['rounds/R06/artifacts/consumer-research-received.html'] == '8b20c8d1efe03e7c09ad64e3108e6dde2646a34f814799f3cec136987beda2e6'
- assert edits['originalFileSha256']['rounds/R07/artifacts/checklist-received.html'] == '1606d541fdd2712511c365d68bae6a886b04527f1c799514adeeaf182f2cdbdb'
- assert (WORK / 'rounds/R08/prompt-verbatim.txt').read_text(encoding='utf-8').strip() not in (WORK / '案例样板演示.html').read_text(encoding='utf-8')
- ev('new Promise((resolve,reject)=>{const end=Date.now()+10000;const poll=()=>{if([...document.querySelectorAll("iframe")].every(f=>f.contentDocument?.querySelector("h1")))return resolve(true);if(Date.now()>end)return reject(Error("artifact load timeout"));setTimeout(poll,50)};poll()})', True)
- for width, height, name in [(1440, 1000, 'desktop'), (390, 844, 'mobile'), (360, 800, 'narrow')]:
- call('Emulation.setDeviceMetricsOverride', {'width': width, 'height': height, 'deviceScaleFactor': 1, 'mobile': width < 500})
- for key in [*expected, 'atlas']:
- ev('document.querySelector(' + json.dumps('[data-view="' + key + '"]') + ').click()')
- settle()
- result = ev('''(()=>{const panel=[...document.querySelectorAll('.panel')].find(p=>!p.hidden);return {width:innerWidth,scroll:document.documentElement.scrollWidth,panel:panel.id,visiblePanels:document.querySelectorAll('.panel:not([hidden])').length,minFont:Math.min(...[...panel.querySelectorAll('p,td,th')].map(e=>parseFloat(getComputedStyle(e).fontSize))),tables:panel.querySelectorAll('table').length};})()''')
- assert result['scroll'] <= width and result['visiblePanels'] == 1 and result['minFont'] >= 15, result
- assert result['panel'] == 'panel-' + key
- if key == 'reply':
- assert result['tables'] == 2
- assert ev('document.querySelector("#panel-reply").innerText.includes("白象火鸡类 61 条对康师傅 31 条")')
- if key == 'supplement':
- assert ev('document.querySelector("#panel-supplement").innerText.includes("口味酱体矩阵")')
- assert ev('document.querySelector("#panel-supplement").innerText.includes("不用洗碗")')
- assert not ev('document.querySelector("#panel-supplement").innerText.includes("ownerName")')
- if key == 'reviewed':
- assert result['tables'] == 5
- assert ev('document.querySelector("#panel-reviewed").innerText.includes("去重后只有 1 条")')
- assert not ev('document.querySelector("#panel-reviewed").innerText.includes("VALIDATION_FAILED")')
- if key == 'comparison':
- assert result['tables'] == 7
- assert ev('document.querySelector("#panel-comparison").innerText.includes("三养火鸡 140g")')
- assert not ev('document.querySelector("#panel-comparison").innerText.includes("owner 用户8108")')
- if key == 'specifications':
- assert result['tables'] == 1
- assert ev('document.querySelector("#panel-specifications").innerText.includes("棕榈油")')
- assert ev('document.querySelector("#panel-specifications").innerText.includes("四款全部 0 条")')
- assert not ev('document.querySelector("#panel-specifications").innerText.includes("HTTP 200")')
- if key == 'consumer':
- assert result['tables'] == 2
- assert ev('document.querySelector("#panel-consumer").innerText.includes("愿意接受的代价")')
- assert ev('document.querySelector("#panel-consumer").innerText.includes("四款的同款评价:全部 0 条")')
- assert not ev('document.querySelector("#panel-consumer").innerText.includes("HTTP 200")')
- if key == 'checklist':
- assert result['tables'] == 1
- assert ev('document.querySelector("#panel-checklist").innerText.includes("他最后还是买了要煮的袋装面")')
- assert ev('document.querySelector("#panel-checklist").innerText.includes("访谈提纲(草稿·未执行)")')
- assert not ev('document.querySelector("#panel-checklist").innerText.includes("HTTP 200")')
- if key == 'atlas':
- result['artifacts'] = []
- for version, tables, cards in [('checklist', 2, 10), ('consumer', 3, 3), ('four-products', 3, 2), ('products', 5, 8), ('v2', 4, 4), ('v1', 2, 4)]:
- ev('document.querySelector(' + json.dumps('[data-artifact="' + version + '"]') + ').click()')
- settle()
- atlas_check = ev('''(()=>{const d=document.querySelector('iframe:not([hidden])').contentDocument,w=d.defaultView;return {width:w.innerWidth,scroll:d.documentElement.scrollWidth,cards:d.querySelectorAll(d.querySelector('.qs-item')?'.q':'.card,.hyp,.ex').length,minFont:Math.min(...[...d.querySelectorAll('p,td,th,li,.row,.val,.src')].map(e=>parseFloat(w.getComputedStyle(e).fontSize))),tables:d.querySelectorAll('.table-scroll,.tw,.tscroll,.sc').length,sourceLinks:d.querySelectorAll('a[href]').length,images:d.querySelectorAll('img').length};})()''')
- assert atlas_check['scroll'] <= atlas_check['width'] and atlas_check['cards'] == cards and atlas_check['minFont'] >= 15 and atlas_check['tables'] == tables, atlas_check
- assert ev('document.querySelectorAll("iframe:not([hidden])").length') == 1
- if version == 'checklist':
- assert atlas_check['sourceLinks'] == 37
- assert ev('(()=>{const f=document.querySelector("iframe:not([hidden])");return f.sandbox.contains("allow-popups")&&f.sandbox.contains("allow-popups-to-escape-sandbox")&&[...f.contentDocument.querySelectorAll("a[href]")].every(a=>a.target==="_blank"&&a.href.startsWith("https://"))})()')
- result['artifacts'].append(atlas_check | {'version': version})
- ev('selectArtifact("checklist")')
- checks.append(result | {'viewport': name, 'view': key})
- if name in ('desktop', 'mobile') and key in ('checklist', 'atlas'):
- ev('scrollTo(0,0)')
- settle()
- if key == 'atlas':
- ev('document.querySelector("iframe:not([hidden])").scrollIntoView({block:"start"})')
- settle()
- screenshot = call('Page.captureScreenshot', {'format': 'png', 'captureBeyondViewport': False})
- (OUT / (name + '-' + key + '.png')).write_bytes(base64.b64decode(screenshot['data']))
- if key == 'atlas':
- ev('(()=>{const d=document.querySelector("iframe:not([hidden])").contentDocument;d.defaultView.scrollTo(0,d.querySelector(".q").offsetTop)})()')
- settle()
- screenshot = call('Page.captureScreenshot', {'format': 'png', 'captureBeyondViewport': False})
- (OUT / (name + '-artifact-quotes.png')).write_bytes(base64.b64decode(screenshot['data']))
- # Keyboard navigation reaches the business dialogue and the actual artifact.
- ev('selectView("prompt");document.querySelector("#tab-prompt").focus();document.querySelector("#tab-prompt").dispatchEvent(new KeyboardEvent("keydown",{key:"End",bubbles:true}))')
- assert ev('document.activeElement.id') == 'tab-atlas'
- assert ev('document.querySelector("#panel-atlas").hidden') is False
- assert not errors, errors
- external = [url for url in requests if not url.startswith(base + '/') and not url.startswith('data:')]
- assert not external, external
- receipt = {'ok': True, 'scope': 'local HTML display; not research validation or production board',
- 'browser': 'Edge headless', 'renderChecks': len(checks), 'checks': checks,
- 'presentationTextsMatch': True, 'rawArchiveKeptSeparately': True,
- 'courseAndOperationalTracesRemoved': True, 'viewports': [1440, 390, 360], 'pageHorizontalOverflow': False,
- 'runtimeErrors': errors, 'externalPageRequests': external, 'screenshotsManuallyReviewed': False,
- 'originalHashesPreserved': True, 'keyboardNavigationPassed': True,
- 'receivedArtifactEmbedded': True, 'pendingEighthPromptNotPresentedAsDialogue': True,
- 'sourceAnchorsRetained': 37, 'explicitSourcePopupsPermitted': True,
- 'externalSourceAccessibilityVerifiedByBrowser': False,
- 'latestReplyComplete': True, 'receivedArtifacts': 6}
- (WORK / 'browser-checks.json').write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
- print(json.dumps({k: v for k, v in receipt.items() if k != 'checks'}, ensure_ascii=False))
- finally:
- if ws:
- ws.close()
- proc.terminate()
- proc.wait(timeout=10)
- server.shutdown()
- server.server_close()
|