test: add a CDP-based pre-release UI smoke harness
The DSH sandbox blocks named pipes, so Chromium/WebView2 cannot start inside it (window renders white, msedgewebview2 exits immediately; Edge headless fails with a Mojo platform-channel access-denied fatal). UI verification therefore moves to a script the user runs from a normal desktop shell. - agent/tests/ui-smoke.ps1: launches the built exe with an isolated config and --remote-debugging-port, waits for the port, runs the driver, closes. - agent/tests/ui-smoke.mjs: connects over CDP, snapshots the page (preview content, headings, fold toggles, highlighted code, window.ipc bridge), saves a screenshot and a JSON report for the agent to read. - The driver was validated against a mock CDP server; the real end-to-end run needs a desktop shell (sandbox cannot host WebView2).
This commit is contained in:
206
agent/tests/ui-smoke.mjs
Normal file
206
agent/tests/ui-smoke.mjs
Normal file
@@ -0,0 +1,206 @@
|
||||
#!/usr/bin/env node
|
||||
// Pre-release UI check for MD Preview.
|
||||
//
|
||||
// The DSH sandbox blocks named pipes, so Chromium/WebView2 cannot start inside
|
||||
// it. Run this from a normal desktop shell via ui-smoke.ps1: it talks to the
|
||||
// already-running app over the DevTools protocol and writes a JSON report plus
|
||||
// a screenshot under --out.
|
||||
//
|
||||
// Usage: node ui-smoke.mjs --port 9333 --out target/ui-test [--expect home|doc]
|
||||
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { argv, exit } from "node:process";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
function parseArgs(list) {
|
||||
const args = {};
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const item = list[i];
|
||||
if (!item.startsWith("--")) continue;
|
||||
const key = item.slice(2);
|
||||
const next = list[i + 1];
|
||||
if (next === undefined || next.startsWith("--")) args[key] = true;
|
||||
else { args[key] = next; i++; }
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); }
|
||||
|
||||
async function findPageTarget(port, timeoutMs) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let lastError = "no targets";
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(2000) });
|
||||
const targets = await response.json();
|
||||
const page = targets.find((t) => t.type === "page" && t.webSocketDebuggerUrl);
|
||||
if (page) return page;
|
||||
lastError = `${targets.length} target(s), none is a page`;
|
||||
} catch (error) {
|
||||
lastError = String(error && error.message ? error.message : error);
|
||||
}
|
||||
await sleep(250);
|
||||
}
|
||||
throw new Error(`no page target on port ${port}: ${lastError}`);
|
||||
}
|
||||
|
||||
class Cdp {
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
this.nextId = 1;
|
||||
this.pending = new Map();
|
||||
this.socket = null;
|
||||
}
|
||||
|
||||
async connect(timeoutMs) {
|
||||
const socket = new WebSocket(this.url);
|
||||
this.socket = socket;
|
||||
socket.addEventListener("message", (event) => {
|
||||
let message;
|
||||
try { message = JSON.parse(String(event.data)); } catch { return; }
|
||||
if (message.id && this.pending.has(message.id)) {
|
||||
const { resolve, reject } = this.pending.get(message.id);
|
||||
this.pending.delete(message.id);
|
||||
if (message.error) reject(new Error(`${message.error.code}: ${message.error.message}`));
|
||||
else resolve(message.result);
|
||||
}
|
||||
});
|
||||
await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error("CDP connect timed out")), timeoutMs);
|
||||
socket.addEventListener("open", () => { clearTimeout(timer); resolve(); });
|
||||
socket.addEventListener("error", () => { clearTimeout(timer); reject(new Error("CDP socket error")); });
|
||||
});
|
||||
}
|
||||
|
||||
send(method, params = {}, timeoutMs = 10000) {
|
||||
const id = this.nextId++;
|
||||
const payload = JSON.stringify({ id, method, params });
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`CDP timeout: ${method}`));
|
||||
}, timeoutMs);
|
||||
this.pending.set(id, {
|
||||
resolve: (value) => { clearTimeout(timer); resolve(value); },
|
||||
reject: (error) => { clearTimeout(timer); reject(error); },
|
||||
});
|
||||
this.socket.send(payload);
|
||||
});
|
||||
}
|
||||
|
||||
async evaluate(expression, timeoutMs = 10000) {
|
||||
const result = await this.send("Runtime.evaluate", {
|
||||
expression,
|
||||
returnByValue: true,
|
||||
awaitPromise: true,
|
||||
userGesture: true,
|
||||
}, timeoutMs);
|
||||
if (result.exceptionDetails) {
|
||||
throw new Error(`page exception: ${result.exceptionDetails.text || "unknown"}`);
|
||||
}
|
||||
return result.result ? result.result.value : undefined;
|
||||
}
|
||||
|
||||
close() {
|
||||
try { this.socket.close(); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
const SNAPSHOT = `(() => {
|
||||
const preview = document.getElementById('preview');
|
||||
const style = getComputedStyle(document.documentElement);
|
||||
return {
|
||||
readyState: document.readyState,
|
||||
bodyClass: document.body.className,
|
||||
previewChildren: preview ? preview.children.length : -1,
|
||||
previewTextLength: preview ? preview.innerText.length : -1,
|
||||
firstHeading: (document.querySelector('#preview h1, #preview h2, #preview h3') || {}).textContent || '',
|
||||
headings: document.querySelectorAll('#preview h1, #preview h2, #preview h3, #preview h4, #preview h5, #preview h6').length,
|
||||
foldToggles: document.querySelectorAll('.mdp-fold-toggle').length,
|
||||
codeBlocks: document.querySelectorAll('#preview pre code').length,
|
||||
highlighted: document.querySelectorAll('#preview pre code.hljs').length,
|
||||
hasIpc: !!(window.ipc && typeof window.ipc.postMessage === 'function'),
|
||||
hasApi: ['__setContent', '__setTabs', '__setPreview', '__setEmptyPreview', '__markSaved']
|
||||
.every((name) => typeof window[name] === 'function'),
|
||||
zoom: style.getPropertyValue('--content-scale').trim(),
|
||||
tabs: document.querySelectorAll('#tabs .tab').length,
|
||||
tabBarVisible: document.body.classList.contains('has-tabs'),
|
||||
findApi: typeof window.__mdPreviewShowFind === 'function',
|
||||
};
|
||||
})()`;
|
||||
|
||||
export async function run(options) {
|
||||
const { port, outDir, expect } = options;
|
||||
const report = {
|
||||
startedAt: new Date().toISOString(),
|
||||
port,
|
||||
expect,
|
||||
checks: [],
|
||||
errors: [],
|
||||
screenshot: null,
|
||||
snapshot: null,
|
||||
};
|
||||
const check = (name, pass, detail) => report.checks.push({ name, pass: !!pass, detail });
|
||||
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
|
||||
let cdp;
|
||||
try {
|
||||
const target = await findPageTarget(port, options.waitMs ?? 15000);
|
||||
report.targetUrl = target.url;
|
||||
cdp = new Cdp(target.webSocketDebuggerUrl);
|
||||
await cdp.connect(5000);
|
||||
await cdp.send("Runtime.enable");
|
||||
await cdp.send("Page.enable");
|
||||
|
||||
// Let hljs / katex / mermaid / folding settle after the first paint.
|
||||
await sleep(900);
|
||||
const snapshot = await cdp.evaluate(SNAPSHOT);
|
||||
report.snapshot = snapshot;
|
||||
|
||||
check("page loaded", snapshot && snapshot.readyState === "complete", snapshot && snapshot.readyState);
|
||||
check("preview has content", snapshot && snapshot.previewChildren > 0, snapshot && `${snapshot.previewChildren} child nodes`);
|
||||
check("webview IPC bridge", snapshot && snapshot.hasIpc, "window.ipc.postMessage");
|
||||
check("page API installed", snapshot && snapshot.hasApi, "setContent/setTabs/setPreview");
|
||||
|
||||
if (expect === "doc") {
|
||||
check("headings rendered", snapshot && snapshot.headings > 0, snapshot && `${snapshot.headings} headings`);
|
||||
check("heading fold toggles", snapshot && snapshot.foldToggles > 0, snapshot && `${snapshot.foldToggles} toggles`);
|
||||
check("code blocks highlighted", snapshot && snapshot.codeBlocks > 0 && snapshot.highlighted > 0, snapshot && `${snapshot.highlighted}/${snapshot.codeBlocks} highlighted`);
|
||||
check("preview text is not empty", snapshot && snapshot.previewTextLength > 20, snapshot && `${snapshot.previewTextLength} chars`);
|
||||
} else {
|
||||
check("home page body", snapshot && snapshot.bodyClass.includes("home"), snapshot && snapshot.bodyClass);
|
||||
}
|
||||
|
||||
const shot = await cdp.send("Page.captureScreenshot", { format: "png" }, 15000);
|
||||
if (shot && shot.data) {
|
||||
const file = `${outDir}/ui-smoke.png`;
|
||||
writeFileSync(file, Buffer.from(shot.data, "base64"));
|
||||
report.screenshot = file;
|
||||
} else {
|
||||
report.errors.push("captureScreenshot returned no data");
|
||||
}
|
||||
} catch (error) {
|
||||
report.errors.push(String(error && error.message ? error.message : error));
|
||||
} finally {
|
||||
if (cdp) cdp.close();
|
||||
}
|
||||
|
||||
const failed = report.checks.filter((item) => !item.pass);
|
||||
const ok = failed.length === 0 && report.errors.length === 0;
|
||||
const reportPath = `${outDir}/ui-smoke.json`;
|
||||
writeFileSync(reportPath, JSON.stringify({ ...report, ok }, null, 2));
|
||||
console.log(JSON.stringify({ ok, failed: failed.length, errors: report.errors, report: reportPath, screenshot: report.screenshot }, null, 2));
|
||||
return { ok, report, reportPath };
|
||||
}
|
||||
|
||||
if (import.meta.url === pathToFileURL(argv[1] ?? "").href) {
|
||||
const args = parseArgs(argv.slice(2));
|
||||
const port = Number(args.port ?? 9333);
|
||||
const outDir = args.out ?? "target/ui-test";
|
||||
const expect = args.expect ?? "doc";
|
||||
run({ port, outDir, expect })
|
||||
.then(({ ok }) => exit(ok ? 0 : 1))
|
||||
.catch((error) => { console.error(error); exit(2); });
|
||||
}
|
||||
129
agent/tests/ui-smoke.ps1
Normal file
129
agent/tests/ui-smoke.ps1
Normal file
@@ -0,0 +1,129 @@
|
||||
<#
|
||||
MD Preview 发布前 UI 冒烟(需要普通桌面 PowerShell)
|
||||
- 通过 WebView2 的 CDP 端口检查页面是否真的渲染,并截图
|
||||
- 默认使用仓库里的开发构建(Low 完整性,启动时写不了 HKCU,安全)
|
||||
- 不要在 DSH 沙箱里跑:沙箱禁止命名管道,Chromium/WebView2 起不来
|
||||
#>
|
||||
#requires -Version 5.1
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Exe = '',
|
||||
[string]$Fixture = '',
|
||||
[int]$Port = 9333,
|
||||
[ValidateSet('doc', 'home')]
|
||||
[string]$Expect = 'doc',
|
||||
[string]$OutDir = '',
|
||||
[switch]$KeepOpen
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
Set-Location $repoRoot
|
||||
|
||||
if (-not $Exe) { $Exe = Join-Path $repoRoot 'target\release\md-preview.exe' }
|
||||
if (-not $Fixture) { $Fixture = Join-Path $repoRoot 'agent\tests\fixtures\code-samples.md' }
|
||||
if (-not $OutDir) { $OutDir = Join-Path $repoRoot 'target\ui-test' }
|
||||
|
||||
if (-not (Test-Path -LiteralPath $Exe)) { throw ('missing exe: ' + $Exe + '(先运行 agent\scripts\build.ps1)') }
|
||||
if (-not (Test-Path -LiteralPath $Fixture)) { throw ('missing fixture: ' + $Fixture) }
|
||||
$node = Get-Command node -ErrorAction SilentlyContinue
|
||||
if (-not $node) { $node = 'C:\Program Files\nodejs\node.exe' }
|
||||
if (-not (Test-Path -LiteralPath $node)) { throw 'Node.js 未找到(需要 Node 21+,用其内置 WebSocket)' }
|
||||
& $node -e "process.exit(('WebSocket' in globalThis) ? 0 : 1)" 2>$null
|
||||
if ($LASTEXITCODE -ne 0) { throw ('Node 版本太旧:需要 Node 21+ 的内置 WebSocket(当前 ' + (& $node --version) + ')') }
|
||||
|
||||
New-Item -ItemType Directory -Force $OutDir | Out-Null
|
||||
$configDir = Join-Path $OutDir 'config'
|
||||
$logOut = Join-Path $OutDir 'app.stdout.log'
|
||||
$logErr = Join-Path $OutDir 'app.stderr.log'
|
||||
$reportPath = Join-Path $OutDir 'ui-smoke.json'
|
||||
Remove-Item -Recurse -Force $configDir -ErrorAction SilentlyContinue
|
||||
Remove-Item -Force $logOut, $logErr, $reportPath, (Join-Path $OutDir 'ui-smoke.png') -ErrorAction SilentlyContinue
|
||||
|
||||
# 单实例:如果目标 exe 已经在跑,新的启动会被转发出去,CDP 端口就不会出现。
|
||||
$exePath = (Resolve-Path -LiteralPath $Exe).Path
|
||||
$running = @()
|
||||
foreach ($process in (Get-Process -ErrorAction SilentlyContinue)) {
|
||||
$path = $null
|
||||
try { $path = $process.Path } catch { }
|
||||
if ($path -and ($path -ieq $exePath)) { $running += [string]$process.Id }
|
||||
}
|
||||
if ($running.Count -gt 0) {
|
||||
throw ('目标 exe 已在运行(PID ' + ($running -join ', ') + '),请先关闭它;否则启动会被单实例转发。')
|
||||
}
|
||||
|
||||
# 端口探测:CDP 起来之前不要跑断言。
|
||||
function Test-Port([int]$port) {
|
||||
$client = New-Object System.Net.Sockets.TcpClient
|
||||
try {
|
||||
$task = $client.ConnectAsync('127.0.0.1', $port)
|
||||
if (-not $task.Wait(400)) { return $false }
|
||||
return $client.Connected
|
||||
} catch {
|
||||
return $false
|
||||
} finally {
|
||||
$client.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
$previousConfig = $env:MD_PREVIEW_CONFIG_DIR
|
||||
$previousArgs = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||
$proc = $null
|
||||
$exitCode = 1
|
||||
try {
|
||||
$env:MD_PREVIEW_CONFIG_DIR = $configDir
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = '--remote-debugging-port=' + $Port
|
||||
|
||||
Write-Host ('==> launching ' + $exePath) -ForegroundColor Cyan
|
||||
$proc = Start-Process -FilePath $exePath -ArgumentList @('"' + $Fixture + '"') -PassThru -RedirectStandardOutput $logOut -RedirectStandardError $logErr
|
||||
|
||||
$deadline = (Get-Date).AddSeconds(25)
|
||||
$up = $false
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if ($proc.HasExited) { break }
|
||||
if (Test-Port $Port) { $up = $true; break }
|
||||
Start-Sleep -Milliseconds 300
|
||||
}
|
||||
|
||||
if (-not $up) {
|
||||
Write-Host 'ERROR: CDP 端口没有起来。' -ForegroundColor Red
|
||||
Write-Host ' - 不要在 DSH 沙箱里运行本脚本:沙箱禁止命名管道,Chromium/WebView2 无法启动。'
|
||||
Write-Host ' - 确认没有其它 MD Preview 实例占用同一个配置目录。'
|
||||
if (Test-Path -LiteralPath $logErr) {
|
||||
$err = Get-Content -LiteralPath $logErr -ErrorAction SilentlyContinue | Select-Object -Last 10
|
||||
if ($err) { Write-Host ' app.stderr:'; $err | ForEach-Object { Write-Host (' ' + $_) } }
|
||||
}
|
||||
if ($proc.HasExited) { Write-Host (' app 已退出,exit code ' + $proc.ExitCode) }
|
||||
throw 'CDP port did not open'
|
||||
}
|
||||
|
||||
Write-Host ('==> node agent\tests\ui-smoke.mjs --port ' + $Port + ' --expect ' + $Expect) -ForegroundColor Cyan
|
||||
& $node (Join-Path $repoRoot 'agent\tests\ui-smoke.mjs') --port $Port --out $OutDir --expect $Expect
|
||||
$exitCode = $LASTEXITCODE
|
||||
|
||||
if (Test-Path -LiteralPath $reportPath) {
|
||||
$report = Get-Content -LiteralPath $reportPath -Raw | ConvertFrom-Json
|
||||
$failed = @($report.checks | Where-Object { -not $_.pass })
|
||||
if ($failed.Count -gt 0) {
|
||||
Write-Host 'FAILED checks:' -ForegroundColor Red
|
||||
$failed | ForEach-Object { Write-Host (' - ' + $_.name + ': ' + $_.detail) -ForegroundColor Red }
|
||||
} else {
|
||||
Write-Host ('OK: ' + @($report.checks).Count + ' checks') -ForegroundColor Green
|
||||
}
|
||||
if ($report.screenshot) { Write-Host ('screenshot: ' + $report.screenshot) }
|
||||
Write-Host ('report : ' + $reportPath)
|
||||
}
|
||||
} finally {
|
||||
if ($proc -and -not $KeepOpen) {
|
||||
try {
|
||||
if (-not $proc.HasExited) {
|
||||
$proc.CloseMainWindow() | Out-Null
|
||||
if (-not $proc.WaitForExit(5000)) { $proc.Kill() }
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
if ($null -eq $previousConfig) { Remove-Item Env:\MD_PREVIEW_CONFIG_DIR -ErrorAction SilentlyContinue } else { $env:MD_PREVIEW_CONFIG_DIR = $previousConfig }
|
||||
if ($null -eq $previousArgs) { Remove-Item Env:\WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS -ErrorAction SilentlyContinue } else { $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $previousArgs }
|
||||
}
|
||||
|
||||
exit $exitCode
|
||||
Reference in New Issue
Block a user