Files
ssw-mvp/docs/e2e/runner.mjs
T
admin 4585d15d5f chore: snapshot source work — e2e fixes, backend/web, docs
- e2e: fix 9 failing cases (contract/hosting/delivery/usage/security);
  add dsl.createSandboxTask() self-provision helper; cli/runner now
  default headless, --ob opens visible browser
- backend: tdc/tds controller adjustments (delivery, hosting, contract,
  chain-evidence, catalog, product, policy-conflict, etc.)
- web: ssw views/components adjustments (contract, product, hosting, connector)
- docs: AGENTS.md, e2e README; .gitignore; project memory update

Excludes docs/e2e/results artifacts (screenshots + results.json).
2026-08-06 14:02:07 +08:00

211 lines
7.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import http from 'node:http'
import fs from 'node:fs'
import path from 'node:path'
import { DOCS_DIR, RUNNER_PORT, SHOTS_DIR, RESULTS_FILE, E2E_DIR } from './lib/config.mjs'
import { loadCases, loadResults, mergeResult, runCase, saveResults } from './lib/exec.mjs'
import { probe, startBackend, startFrontend } from './lib/env.mjs'
import { closeBrowser } from './lib/browser.mjs'
import { selfTest } from './lib/cipher.mjs'
/**
* 测试执行服务 —— 核对页面的后台。
*
* 页面本身是个静态 HTML,用 file:// 打开时既起不了进程也调不动浏览器,
* 所以由这个进程把它托管起来(同源,省掉 CORS),并对外提供:
* GET / 核对页面(就是 docs/尚数网测评_测试用例核对.html)
* GET /api/status 环境探测 + 用例清单 + 上次结果
* POST /api/env/start 按需拉起后端 30000 / 前端 5173
* GET /api/run?tc=A,B 执行用例,SSE 实时回传日志与结果
* POST /api/stop 中断当前批次
* GET /api/results 历史结果
* POST /api/results/clear 清空历史
* GET /shots/xxx.png 失败/关键步骤截图
*/
const HTML_FILE = path.join(E2E_DIR, 'index.html')
let running = false
let abort = false
function json(res, code, data) {
const body = JSON.stringify(data)
res.writeHead(code, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
'Access-Control-Allow-Origin': '*'
})
res.end(body)
}
function readBody(req) {
return new Promise((resolve) => {
let b = ''
req.on('data', (c) => (b += c))
req.on('end', () => {
try {
resolve(JSON.parse(b || '{}'))
} catch {
resolve({})
}
})
})
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://localhost:${RUNNER_PORT}`)
const p = url.pathname
if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST',
'Access-Control-Allow-Headers': 'Content-Type'
})
return res.end()
}
// ---- 核对页面 ----
if (p === '/' || p === '/index.html') {
if (!fs.existsSync(HTML_FILE)) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
return res.end('找不到核对页面:' + HTML_FILE)
}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })
return res.end(fs.readFileSync(HTML_FILE))
}
// ---- 截图 ----
if (p.startsWith('/shots/')) {
const f = path.join(SHOTS_DIR, path.basename(decodeURIComponent(p.slice(7))))
if (!fs.existsSync(f)) {
res.writeHead(404)
return res.end()
}
const ext = path.extname(f).toLowerCase()
res.writeHead(200, { 'Content-Type': ext === '.webm' ? 'video/webm' : 'image/png' })
return res.end(fs.readFileSync(f))
}
// ---- 状态 ----
if (p === '/api/status') {
const [env, cases] = await Promise.all([probe(), loadCases()])
return json(res, 200, {
ok: true,
running,
env,
results: loadResults(),
cases: cases.map(({ _run, ...m }) => m)
})
}
if (p === '/api/results') return json(res, 200, loadResults())
if (p === '/api/results/clear' && req.method === 'POST') {
saveResults({ updatedAt: new Date().toISOString(), cases: {} })
return json(res, 200, { ok: true })
}
// ---- 拉起服务 ----
if (p === '/api/env/start' && req.method === 'POST') {
const { be = true, fe = true } = await readBody(req)
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'Access-Control-Allow-Origin': '*'
})
const send = (event, data) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
const log = (m) => send('log', { msg: m })
try {
if (fe) await startFrontend(log)
if (be) await startBackend(log)
send('done', { ok: true, env: await probe() })
} catch (e) {
send('done', { ok: false, error: e.message, env: await probe() })
}
return res.end()
}
if (p === '/api/stop' && req.method === 'POST') {
abort = true
return json(res, 200, { ok: true })
}
// ---- 执行用例 ----
if (p === '/api/run') {
if (running) return json(res, 409, { ok: false, error: '已有批次在执行中' })
const want = (url.searchParams.get('tc') || '').split(',').map((s) => s.trim()).filter(Boolean)
// 默认无头(不打扰);ob=1 开可见浏览器;headless=0 兼容旧用法(显式可见)
const ob = url.searchParams.get('ob') === '1'
const explicitHeadless = url.searchParams.get('headless')
const headless = ob ? false : (explicitHeadless !== null ? explicitHeadless === '1' : true)
const all = await loadCases()
const byTc = new Map(all.map((c) => [c.tc, c]))
const queue = want.length ? want.map((tc) => byTc.get(tc) || { tc, broken: '没有对应的脚本文件' }) : all
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'Access-Control-Allow-Origin': '*'
})
const send = (event, data) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
running = true
abort = false
send('start', { total: queue.length })
const summary = { pass: 0, fail: 0, skip: 0, manual: 0, error: 0 }
try {
for (let i = 0; i < queue.length; i++) {
if (abort) {
send('aborted', { done: i, total: queue.length })
break
}
const c = queue[i]
send('case-start', { tc: c.tc, index: i, total: queue.length, title: c.title || '' })
const rec = await runCase(c, {
headless,
onLog: (msg) => send('log', { tc: c.tc, msg })
})
summary[rec.status] = (summary[rec.status] || 0) + 1
mergeResult(rec)
send('case-done', rec)
}
send('done', { summary, aborted: abort })
} catch (e) {
send('done', { summary, error: e.message })
} finally {
running = false
abort = false
await closeBrowser()
}
return res.end()
}
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
res.end('not found')
})
selfTest()
server.listen(RUNNER_PORT, () => {
const cases = fs.existsSync(path.join(E2E_DIR, 'cases'))
? fs.readdirSync(path.join(E2E_DIR, 'cases')).filter((f) => f.endsWith('.mjs')).length
: 0
console.log('')
console.log(' 尚数网测评 · 测试用例执行台')
console.log(' ────────────────────────────────────────')
console.log(` 控制台 http://localhost:${RUNNER_PORT}/`)
console.log(` 用例脚本 ${cases} 个(docs/e2e/cases/)`)
console.log(` 结果存档 ${path.relative(process.cwd(), RESULTS_FILE)}`)
console.log(' ────────────────────────────────────────')
console.log(' Ctrl+C 退出')
console.log('')
})
process.on('SIGINT', async () => {
await closeBrowser()
process.exit(0)
})