190 lines
9.5 KiB
JavaScript
190 lines
9.5 KiB
JavaScript
// 预览产物生成器(src/image-preview-derive.js)行为测试 —— 独立文件,可异步
|
||
// 关键断言:解码阶段就传 resizeWidth/resizeHeight(绝不产全尺寸位图)、bitmap.close 无泄漏、
|
||
// revokeAll 幂等、跨域走 opts.viaUrl、失败只回 { ok:false } 不抛。
|
||
'use strict'
|
||
const fs = require('fs')
|
||
const path = require('path')
|
||
const root = path.join(__dirname, '..')
|
||
const src = fs.readFileSync(path.join(root, 'src/image-preview-derive.js'), 'utf8')
|
||
const box = {}
|
||
new Function('window', 'globalThis', src)(box, box) // 与 image-blob-store-test.js 相同的沙箱加载方式
|
||
const M = box.IWBImagePreviewDerive
|
||
let pass = 0, fail = 0
|
||
const ok = (name, cond) => { if (cond) { pass++; console.log(' ✅ ' + name) } else { fail++; console.log(' ❌ ' + name) } }
|
||
|
||
// ---- 构造带真实头部的假 PNG(只给头部,不需要可解码的像素数据)----
|
||
function pngHeaderBytes(w, h) {
|
||
const b = Buffer.alloc(33)
|
||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(b, 0)
|
||
b.writeUInt32BE(13, 8)
|
||
b.write('IHDR', 12, 'ascii')
|
||
b.writeUInt32BE(w, 16)
|
||
b.writeUInt32BE(h, 20)
|
||
b[24] = 8; b[25] = 6; b[26] = 0; b[27] = 0; b[28] = 0
|
||
return b
|
||
}
|
||
const pngDataUrl = (w, h) => 'data:image/png;base64,' + pngHeaderBytes(w, h).toString('base64')
|
||
|
||
// ---- 假解码 / 假 canvas(不产真图)----
|
||
const saved = {
|
||
cib: globalThis.createImageBitmap,
|
||
fetch: globalThis.fetch,
|
||
doc: globalThis.document,
|
||
oc: globalThis.OffscreenCanvas,
|
||
img: globalThis.Image,
|
||
revoke: URL.revokeObjectURL,
|
||
}
|
||
let cibCalls = []
|
||
let lastBitmap = null
|
||
let canvasCalls = []
|
||
let lastCanvas = null
|
||
let revokedUrls = []
|
||
|
||
function installFakeDecode() {
|
||
cibCalls = []
|
||
globalThis.createImageBitmap = async (blob, opts) => {
|
||
cibCalls.push({ blob: blob, opts: opts || null })
|
||
const w = (opts && Number(opts.resizeWidth)) || 4000
|
||
const h = (opts && Number(opts.resizeHeight)) || 6000
|
||
const bmp = { width: w, height: h, closed: false, close: function () { this.closed = true } }
|
||
lastBitmap = bmp
|
||
return bmp
|
||
}
|
||
}
|
||
function installFakeCanvas() {
|
||
canvasCalls = []
|
||
delete globalThis.OffscreenCanvas
|
||
const mk = () => {
|
||
const canvas = {
|
||
width: 0, height: 0, type: '', quality: 0,
|
||
getContext: () => ({ drawImage: () => { canvas.drawn = true } }),
|
||
toBlob: (cb, type, quality) => {
|
||
canvas.type = type; canvas.quality = quality
|
||
canvasCalls.push({ width: canvas.width, height: canvas.height, type: type, quality: quality })
|
||
cb(new Blob([new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])], { type: type }))
|
||
},
|
||
}
|
||
lastCanvas = canvas
|
||
return canvas
|
||
}
|
||
globalThis.document = { createElement: (tag) => (tag === 'canvas' ? mk() : {}) }
|
||
}
|
||
function restoreEnv() {
|
||
const put = (k, v) => { if (v === undefined) { try { delete globalThis[k] } catch (e) { globalThis[k] = undefined } } else globalThis[k] = v }
|
||
put('createImageBitmap', saved.cib)
|
||
put('fetch', saved.fetch)
|
||
put('document', saved.doc)
|
||
put('OffscreenCanvas', saved.oc)
|
||
put('Image', saved.img)
|
||
URL.revokeObjectURL = saved.revoke
|
||
}
|
||
|
||
const d = M.create({})
|
||
let r1 = null, rKeep = null, rUrl1 = null, rUrl2 = null, rBig = null
|
||
|
||
async function main() {
|
||
// 1) 模块加载 / 导出
|
||
ok('模块加载并导出 IWBImagePreviewDerive', !!M && typeof M === 'object')
|
||
ok('导出 { create }', typeof M.create === 'function')
|
||
const api = M.create({})
|
||
ok('create() 返回完整 API(derive/deriveUrl/revokeAll/stats)',
|
||
['derive', 'deriveUrl', 'revokeAll', 'stats'].every((k) => typeof api[k] === 'function'))
|
||
ok('初始 stats 为 {created:0,revoked:0,live:0,failed:0}',
|
||
api.stats().created === 0 && api.stats().revoked === 0 && api.stats().live === 0 && api.stats().failed === 0)
|
||
|
||
// 2) 解码即缩放:传入等比且长边 ≤ maxEdge 的 resizeWidth/resizeHeight
|
||
installFakeDecode(); installFakeCanvas()
|
||
r1 = await d.derive(pngDataUrl(4000, 6000), { maxEdge: 1024 })
|
||
const call = cibCalls[0]
|
||
ok('createImageBitmap 收到 resizeWidth/resizeHeight',
|
||
!!(call && call.opts && typeof call.opts.resizeWidth === 'number' && typeof call.opts.resizeHeight === 'number'))
|
||
ok('resizeQuality = high', !!(call && call.opts && call.opts.resizeQuality === 'high'))
|
||
const rw = call && call.opts ? call.opts.resizeWidth : 0
|
||
const rh = call && call.opts ? call.opts.resizeHeight : 0
|
||
ok('长边 ≤ maxEdge(' + rw + '×' + rh + ' ≤ 1024)', Math.max(rw, rh) <= 1024)
|
||
ok('等比缩放(4000:6000 比例保持)', Math.abs((rw / rh) - (4000 / 6000)) < 0.01)
|
||
ok('未按全尺寸解码(2160×3840 类全尺寸位图不会产生)', rw < 4000 && rh < 6000)
|
||
ok('derive 返回 ok + blob + width/height/bytes/ms',
|
||
r1.ok === true && !!r1.blob && r1.width === rw && r1.height === rh && r1.bytes > 0 && typeof r1.ms === 'number')
|
||
|
||
// 3) 无泄漏:bitmap.close 必须被调用
|
||
ok('bitmap.close() 被调用(解码位图已释放)', !!lastBitmap && lastBitmap.closed === true)
|
||
|
||
// 4) format='keep' + PNG 输入 ⇒ 输出 MIME 保持 image/png
|
||
rKeep = await d.derive(pngDataUrl(800, 600), { format: 'keep', maxEdge: 1024 })
|
||
ok("format='keep' 输出 blob MIME = image/png",
|
||
rKeep.ok === true && !!rKeep.blob && rKeep.blob.type === 'image/png')
|
||
ok('canvas.toBlob 收到 image/png', !!(lastCanvas && lastCanvas.type === 'image/png'))
|
||
ok('dataURL 前缀为 data:image/png', typeof rKeep.dataUrl === 'string' && rKeep.dataUrl.indexOf('data:image/png') === 0)
|
||
|
||
// 5) fetch 失败 ⇒ { ok:false, error },不抛
|
||
const failedBefore = d.stats().failed
|
||
globalThis.fetch = async () => { throw new Error('network down') }
|
||
let threw = false
|
||
let rFail = null
|
||
try { rFail = await d.derive('https://cdn.example.com/blocked.png', { maxEdge: 512 }) } catch (e) { threw = true }
|
||
ok('fetch 抛错 ⇒ 返回 { ok:false, error } 而非抛出', threw === false && !!rFail && rFail.ok === false && typeof rFail.error === 'string')
|
||
ok('失败计入 stats().failed', d.stats().failed === failedBefore + 1)
|
||
|
||
// 7) http URL 使用 opts.viaUrl(同源代理)
|
||
const fetched = []
|
||
globalThis.fetch = async (url) => {
|
||
fetched.push(url)
|
||
return { ok: true, status: 200, blob: async () => new Blob([pngHeaderBytes(1200, 900)], { type: 'image/png' }) }
|
||
}
|
||
const rVia = await d.derive('https://cdn.example.com/orig.png', { viaUrl: 'https://proxy.example.com/?u=orig.png', maxEdge: 600 })
|
||
ok('http 输入使用 opts.viaUrl 作为 fetch 目标',
|
||
fetched.length === 1 && fetched[0] === 'https://proxy.example.com/?u=orig.png')
|
||
ok('经代理派生结果长边 ≤ maxEdge', rVia.ok === true && Math.max(rVia.width, rVia.height) <= 600)
|
||
|
||
// 8) 超大图 4000×6000 派生结果 ≤ maxEdge
|
||
rBig = await d.derive(pngDataUrl(4000, 6000), { maxEdge: 1024, format: 'jpeg' })
|
||
ok('超大图(4000×6000)派生结果 width/height ≤ maxEdge',
|
||
rBig.ok === true && rBig.width <= 1024 && rBig.height <= 1024)
|
||
ok('超大图长边正好压到 maxEdge(height = 1024)', rBig.height === 1024)
|
||
ok('默认 format='+"'jpeg'"+' 时 canvas 收到 image/jpeg', !!(lastCanvas && lastCanvas.type === 'image/jpeg'))
|
||
|
||
// 6) deriveUrl + revokeAll 幂等
|
||
URL.revokeObjectURL = (u) => { revokedUrls.push(u) }
|
||
const dUrl = M.create({})
|
||
rUrl1 = await dUrl.deriveUrl(pngDataUrl(1000, 500), { maxEdge: 256 })
|
||
rUrl2 = await dUrl.deriveUrl(pngDataUrl(1000, 500), { maxEdge: 256 })
|
||
ok('deriveUrl 产出 blob: objectURL(含 revoke 句柄)',
|
||
rUrl1.ok === true && typeof rUrl1.url === 'string' && rUrl1.url.indexOf('blob:') === 0 && typeof rUrl1.revoke === 'function')
|
||
ok('objectURL 已登记(stats().live === 2)', dUrl.stats().live === 2 && dUrl.stats().created === 2)
|
||
let revokeThrew = false
|
||
try { dUrl.revokeAll(); dUrl.revokeAll() } catch (e) { revokeThrew = true }
|
||
ok('revokeAll() 幂等:连续两次不抛', revokeThrew === false)
|
||
ok('revokeAll() 后 stats().live === 0', dUrl.stats().live === 0)
|
||
ok('revoked 计数为 2(第二次不重复计数)', dUrl.stats().revoked === 2)
|
||
ok('URL.revokeObjectURL 真的被调用到两个 URL', revokedUrls.length === 2)
|
||
ok('单独 revoke() 幂等且不抛', rUrl1.revoke() === false && dUrl.stats().live === 0)
|
||
|
||
// 附加:无解码器/无 canvas 环境 ⇒ 只回失败,不抛
|
||
const dNo = M.create({})
|
||
delete globalThis.createImageBitmap
|
||
delete globalThis.document
|
||
delete globalThis.Image
|
||
delete globalThis.OffscreenCanvas
|
||
let noThrew = false
|
||
let rNo = null
|
||
try { rNo = await dNo.derive(pngDataUrl(4000, 6000), { maxEdge: 256 }) } catch (e) { noThrew = true }
|
||
ok('无解码器/无 canvas ⇒ { ok:false } 不抛', noThrew === false && !!rNo && rNo.ok === false && typeof rNo.error === 'string')
|
||
ok('失败计入该实例的 stats().failed', dNo.stats().failed === 1 && dNo.stats().live === 0)
|
||
|
||
// 附加:dataURL 非图片 / 非法输入 ⇒ 优雅失败
|
||
installFakeDecode(); installFakeCanvas()
|
||
const rBad = await d.derive('data:text/plain;base64,' + Buffer.from('hi').toString('base64'), {})
|
||
ok('非图片 dataURL ⇒ { ok:false, error }', rBad.ok === false && typeof rBad.error === 'string')
|
||
|
||
// 附加:Blob 输入形态
|
||
const rBlob = await d.derive(new Blob([pngHeaderBytes(2000, 1000)], { type: 'image/png' }), { maxEdge: 500, format: 'keep' })
|
||
ok('支持 Blob 输入(保持 MIME 且长边 ≤ maxEdge)',
|
||
rBlob.ok === true && rBlob.blob.type === 'image/png' && Math.max(rBlob.width, rBlob.height) === 500 && rBlob.width === 500)
|
||
|
||
restoreEnv()
|
||
console.log('\n===== image-preview-derive:' + pass + ' 通过 / ' + fail + ' 失败 =====')
|
||
process.exit(fail ? 1 : 0)
|
||
}
|
||
main().catch((e) => { console.error('❌ 测试异常:', e && e.stack || e); process.exit(1) })
|