test(refactor): [BASE-HARNESS-01] add isolated published API fixture

This commit is contained in:
Harvey Zhao committed 2026-09-10 18:44:08 +08:00
1 parent 1d705b3056
commit 3c759f14c2
9 files changed
+283 -7

No files matched your search

+83
View File
@@ -0,0 +1,83 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import http from 'node:http'
import path from 'node:path'
import { ensureArchive, readMember, refactorDir } from './releases.mjs'
const root = path.resolve(refactorDir, '..')
const baseline = JSON.parse(fs.readFileSync(path.join(refactorDir, 'baselines/releases.json'), 'utf8'))
const archives = new Map()
for (const release of baseline.releases) archives.set(release.name, await ensureArchive(release))
const mime = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json', '.mp4': 'video/mp4', '.webm': 'video/webm', '.vtt': 'text/vtt', '.png': 'image/png' }
let port = Number(process.env.ARTPLAYER_TEST_PORT || 8083)
assert(Number.isInteger(port) && port >= 0 && port < 65536, 'Invalid test port')
function sendBytes(req, res, bytes, filename) {
res.setHeader('Content-Type', mime[path.extname(filename)] || 'application/octet-stream')
res.setHeader('Cache-Control', 'no-store')
res.setHeader('Accept-Ranges', 'bytes')
const range = req.headers.range
if (range) {
const match = /^bytes=(\d+)-(\d*)$/.exec(range)
const start = match ? Number(match[1]) : -1
const end = match?.[2] ? Math.min(Number(match[2]), bytes.length - 1) : bytes.length - 1
if (start < 0 || start >= bytes.length || end < start) {
res.writeHead(416, { 'Content-Range': `bytes */${bytes.length}` })
res.end()
return
}
res.statusCode = 206
res.setHeader('Content-Range', `bytes ${start}-${end}/${bytes.length}`)
bytes = bytes.subarray(start, end + 1)
}
res.setHeader('Content-Length', bytes.length)
res.end(req.method === 'HEAD' ? undefined : bytes)
}
const server = http.createServer(async (req, res) => {
try {
const url = new URL(req.url, `http://127.0.0.1:${port}`)
if (req.method === 'POST' && url.pathname === '/reports/api') {
assert.equal(req.headers.origin, `http://127.0.0.1:${port}`, 'Unexpected report origin')
const chunks = []
let size = 0
for await (const chunk of req) {
size += chunk.length
assert(size <= 1024 * 1024, 'Report too large')
chunks.push(chunk)
}
const report = JSON.parse(Buffer.concat(chunks).toString('utf8'))
assert.equal(report.kind, 'public-api')
const output = path.join(refactorDir, '.cache/reports')
fs.mkdirSync(output, { recursive: true })
fs.writeFileSync(path.join(output, 'api.json'), `${JSON.stringify(report, null, 2)}\n`)
res.writeHead(204).end()
return
}
assert(['GET', 'HEAD'].includes(req.method), 'Unsupported method')
if (url.pathname.startsWith('/releases/')) {
const [, , name, ...parts] = url.pathname.split('/')
const release = baseline.releases.find(item => item.name === name)
const member = `package/${parts.join('/')}`
assert(release && Object.hasOwn(release.files, member), 'Unknown release member')
sendBytes(req, res, readMember(archives.get(name), member), member)
return
}
const prefix = url.pathname.startsWith('/assets/sample/') ? '/assets/sample/' : '/fixtures/'
assert(url.pathname.startsWith(prefix), 'Unknown test route')
const dir = prefix === '/fixtures/' ? path.join(refactorDir, 'fixtures') : path.join(root, 'docs/assets/sample')
const filename = path.resolve(dir, decodeURIComponent(url.pathname.slice(prefix.length)))
const relative = path.relative(dir, filename)
assert(relative && !relative.startsWith('..') && !path.isAbsolute(relative), 'Invalid fixture path')
sendBytes(req, res, fs.readFileSync(filename), filename)
}
catch (error) {
if (!res.headersSent) res.writeHead(400, { 'Content-Type': 'text/plain' })
res.end(error.message)
}
})
server.listen(port, '127.0.0.1', () => {
port = server.address().port
console.log(`Baseline browser server: http://127.0.0.1:${port}/fixtures/api.html`)
})
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => server.close())
+50
View File
@@ -0,0 +1,50 @@
import assert from 'node:assert/strict'
import { spawn } from 'node:child_process'
import { once } from 'node:events'
import fs from 'node:fs'
import path from 'node:path'
import { test } from 'node:test'
import { hash, refactorDir } from './releases.mjs'
test('baseline host serves exact release bytes, media ranges and isolated routes', { timeout: 15000 }, async () => {
const child = spawn(process.execPath, [path.join(refactorDir, 'scripts/browser-server.mjs')], {
env: { ...process.env, ARTPLAYER_TEST_PORT: '0' }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
})
let timer
try {
const origin = await new Promise((resolve, reject) => {
let output = ''
timer = setTimeout(() => reject(new Error('Host did not start')), 10000)
child.once('error', reject)
child.once('exit', code => reject(new Error(`Host exited: ${code}`)))
child.stdout.on('data', (chunk) => {
output += chunk
const match = output.match(/http:\/\/127\.0\.0\.1:\d+/)
if (match) { clearTimeout(timer); resolve(match[0]) }
})
})
const baseline = JSON.parse(fs.readFileSync(path.join(refactorDir, 'baselines/releases.json'), 'utf8'))
const response = await fetch(`${origin}/releases/artplayer/dist/artplayer.js`)
assert.equal(response.status, 200)
assert.equal(hash(Buffer.from(await response.arrayBuffer())), baseline.releases[0].files['package/dist/artplayer.js'])
const html = await fetch(`${origin}/fixtures/api.html`)
assert.equal(html.status, 200)
assert((await html.text()).includes('/releases/artplayer-plugin-chapter/'))
const media = fs.readFileSync(path.resolve(refactorDir, '../docs/assets/sample/video.mp4'))
const range = await fetch(`${origin}/assets/sample/video.mp4`, { headers: { Range: 'bytes=0-31' } })
assert.equal(range.status, 206)
assert.equal(range.headers.get('content-range'), `bytes 0-31/${media.length}`)
assert.deepEqual(Buffer.from(await range.arrayBuffer()), media.subarray(0, 32))
const invalid = await fetch(`${origin}/assets/sample/video.mp4`, { headers: { Range: `bytes=${media.length}-` } })
assert.equal(invalid.status, 416)
assert.equal((await fetch(`${origin}/fixtures/%2e%2e%2fbaselines/releases.json`)).status, 400)
assert.equal((await fetch(`${origin}/releases/artplayer/no-such-member.js`)).status, 400)
assert.equal((await fetch(`${origin}/reports/api`, { method: 'POST', headers: { Origin: 'https://example.com' }, body: '{}' })).status, 400)
}
finally {
clearTimeout(timer)
const exited = once(child, 'exit')
child.kill()
await exited
}
})