#!/usr/bin/env python3 """Runs the window's page tests (tests/ui/*.js) in headless Chrome. Each test file runs in the real page (crates/kiri/src/ui/index.html, with its icons) after tests/ui/fixture.js, and calls report() with lines that start with PASS or FAIL. Exits non-zero if any test fails or a page errors. A test's first lines may say `// parity: macos windows linux` (run as each system and compare), `// lang: de` (the language it opens in), `// window: 760x480` (the window's size) or `// page: setup` (Windows' setup window, crates/kiri-win/src/setup.html, instead of the main window). python3 scripts/ui-test.py [tests/ui/switch.js ...] """ import html, json, os, re, subprocess, sys, tempfile ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CHROME = os.environ.get("CHROME", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome") UI = os.path.join(ROOT, "crates/kiri/src/ui") # The results, in the page; and to the page around it when a test runs in a # frame of a given size (`// window:`). REPORT = ('const report = (lines) => { if (window.parent !== window) parent.postMessage(lines.join("\\n"), "*");' ' document.body.insertAdjacentHTML("beforeend", `
${lines.join("\\n")}`); };')
CATCH = ('')
def strings():
"""lang/*.json packed as lang.rs packs them: the English keys once, each language its words in that order."""
d = os.path.join(UI, "lang")
files = {f[:-5]: json.load(open(os.path.join(d, f))) for f in sorted(os.listdir(d)) if f.endswith(".json")}
keys = sorted(set().union(*files.values()))
return {"en": keys, **{tag: [m.get(k) for k in keys] for tag, m in files.items()}}
def opening(pick, packed):
"""What assemble.rs splices in for `pick` on an en-US system: the keys and
the one language the page opens in (a file's tag, or English)."""
return {"en": packed["en"], **({pick: packed[pick]} if pick in packed and pick != "en" else {})}
def host(packed):
"""The host's half of langwords, after the fixture's recorder: it answers as
lang.rs's words_js does, calling kiriWords with that language's words, at
once (a real host answers a moment later). hostHold = true keeps the answers
until hostFlush(), for a test of the moment in between."""
words = {t: w for t, w in packed.items() if t != "en"}
return (f"const HOST_WORDS = {json.dumps(words, ensure_ascii=False)};\n"
"let hostHold = false; const hostHeld = [];\n"
"const hostFlush = () => hostHeld.splice(0).forEach((f) => f());\n"
"{ const post = window.webkit.messageHandlers.kiri.postMessage;\n"
" window.webkit.messageHandlers.kiri.postMessage = (m) => { post(m); const o = JSON.parse(m);\n"
" if (o.cmd !== \"langwords\" || !HOST_WORDS[o.name]) return;\n"
" const answer = () => window.kiriWords && kiriWords({ [o.name]: HOST_WORDS[o.name] });\n"
" if (hostHold) hostHeld.push(answer); else answer(); }; }\n")
def header(test, name, default=None):
"""`// name: value` in one of a test's first lines."""
for line in open(test).readlines()[:4]:
if line.startswith(f"// {name}:"):
return line.split(":", 1)[1].strip()
return default
def lang_of(test):
"""A test runs in English, as a system set to US English would, unless
one of its first lines says `// lang: zh-Hans`."""
return header(test, "lang", "system")
def setup_page(test):
"""kiri-win's setup window (crates/kiri-win/src/setup.html), for a test whose
first lines say `// page: setup`: as assemble.rs's words() builds it, with
the language step and the words for the language it opens in. `sent`
records what the page asks the host; host() answers langwords."""
packed, pick = strings(), lang_of(test)
src = (open(os.path.join(ROOT, "crates/kiri-win/src/setup.html")).read()
.replace("/*LANGSTEP*/", open(os.path.join(UI, "langstep.js")).read(), 1)
.replace("/*LANG*/", f"window.KIRI_LANG = {json.dumps({'os': ['en-US'], 'pick': pick})};", 1)
.replace("/*STRINGS*/{}", json.dumps(opening(pick, packed), ensure_ascii=False), 1))
# The page draws a host state on the next frame; headless Chrome's frames
# don't keep pace with --virtual-time-budget (the dump can come first), so
# a frame here is a task.
fixture = ('window.requestAnimationFrame = (f) => setTimeout(() => f(performance.now()), 0);\n'
'const sent = [];\n'
'window.webkit = { messageHandlers: { kiri: { postMessage: (m) => { const o = JSON.parse(m); sent.push({ type: o.cmd, ...o }); } } } };\n')
i = src.index("