117 lines
5.2 KiB
JavaScript
117 lines
5.2 KiB
JavaScript
'use strict'
|
||
|
||
// tests/storage-fallback-indexeddb.js 的单测(P2-10 收编:app.js 的 IDB 兜底实现 → src/)
|
||
// 重点固化它与 src/storage-runtime.js 的**有意差异**:写失败会「重置连接并重试一次」、返回原始值(非 Result 信封)。
|
||
// 说明:生产路径用 window.IWBStorageRuntime.indexedDb,本模块是兜底分支;真实 IDB 行为由 e2e(真浏览器)覆盖。
|
||
|
||
const assert = require('assert')
|
||
const fs = require('fs')
|
||
const path = require('path')
|
||
const vm = require('vm')
|
||
const root = path.resolve(__dirname, '..')
|
||
const source = fs.readFileSync(path.join(root, 'src', 'storage-fallback-indexeddb.js'), 'utf8')
|
||
|
||
// 可配置的假 indexedDB:firstWriteError=true 时,第一次 readwrite 事务触发 onerror(用于验证重试一次)
|
||
function createFakeIndexedDB(opts) {
|
||
const config = opts || {}
|
||
const data = { images: new Map(), logs: new Map(), kv: new Map() }
|
||
let pendingWriteError = !!config.firstWriteError
|
||
const makeRequest = (result) => {
|
||
const req = { result, onsuccess: null, onerror: null }
|
||
queueMicrotask(() => { if (req.onsuccess) req.onsuccess() })
|
||
return req
|
||
}
|
||
function objectStore(name) {
|
||
const map = data[name]
|
||
return {
|
||
put(value, key) { map.set(key, value); return makeRequest(undefined) },
|
||
get(key) { return makeRequest(map.get(key)) },
|
||
delete(key) { map.delete(key); return makeRequest(undefined) },
|
||
clear() { map.clear(); return makeRequest(undefined) },
|
||
getAllKeys() { return makeRequest(Array.from(map.keys())) },
|
||
getAll() { return makeRequest(Array.from(map.values())) },
|
||
openCursor() {
|
||
const entries = Array.from(map.entries())
|
||
let index = 0
|
||
const req = { result: null, onsuccess: null, onerror: null }
|
||
queueMicrotask(function next() {
|
||
const entry = entries[index++]
|
||
req.result = entry ? { key: entry[0], value: entry[1], continue: () => queueMicrotask(next) } : null
|
||
if (req.onsuccess) req.onsuccess()
|
||
})
|
||
return req
|
||
},
|
||
}
|
||
}
|
||
return {
|
||
open() {
|
||
const db = {
|
||
objectStoreNames: { contains: () => true },
|
||
transaction(name, mode) {
|
||
const tx = { objectStore: () => objectStore(name), oncomplete: null, onerror: null, onabort: null }
|
||
if (mode === 'readwrite' && pendingWriteError) {
|
||
pendingWriteError = false
|
||
queueMicrotask(() => { if (tx.onerror) tx.onerror() })
|
||
} else {
|
||
queueMicrotask(() => { if (tx.oncomplete) tx.oncomplete() })
|
||
}
|
||
return tx
|
||
},
|
||
onclose: null,
|
||
}
|
||
const req = { result: db, onupgradeneeded: null, onsuccess: null, onerror: null }
|
||
queueMicrotask(() => { if (req.onsuccess) req.onsuccess() })
|
||
return req
|
||
},
|
||
}
|
||
}
|
||
|
||
const load = (indexedDB) => {
|
||
const sandbox = { queueMicrotask }
|
||
if (indexedDB !== undefined) sandbox.indexedDB = indexedDB
|
||
vm.runInNewContext(source, sandbox)
|
||
return sandbox.IWBStorageFallbackIndexeddb
|
||
}
|
||
|
||
async function main() {
|
||
const M = load(createFakeIndexedDB())
|
||
assert.ok(M && typeof M.create === 'function', 'IWBStorageFallbackIndexeddb.create 应被导出')
|
||
const idb = M.create({ contract: { name: 'iwb_web', version: 3, stores: ['images', 'logs', 'kv'] } })
|
||
for (const m of ['put', 'get', 'del', 'keys', 'logPut', 'logAll', 'logClear', 'imagesAll', 'kvPut', 'kvGet']) {
|
||
assert.strictEqual(typeof idb[m], 'function', '缺少方法 ' + m)
|
||
}
|
||
// 原始值语义(非 Result 信封)
|
||
assert.strictEqual(await idb.put('img-1', { v: 1 }), true)
|
||
assert.strictEqual(JSON.stringify(await idb.get('img-1')), JSON.stringify({ v: 1 }))
|
||
assert.strictEqual(JSON.stringify(await idb.keys()), JSON.stringify(['img-1']))
|
||
assert.strictEqual(await idb.del('img-1'), true)
|
||
assert.strictEqual(await idb.get('img-1'), undefined)
|
||
assert.strictEqual(await idb.logPut({ id: 'l1', msg: 'ok' }), true)
|
||
assert.strictEqual((await idb.logAll()).length, 1)
|
||
assert.strictEqual(await idb.logClear(), true)
|
||
assert.strictEqual(await idb.kvPut('groups', { schemaVersion: 1 }), true)
|
||
assert.strictEqual((await idb.kvGet('groups')).schemaVersion, 1)
|
||
await idb.put('img-2', { v: 2 })
|
||
await idb.put('img-3', { v: 3 })
|
||
const all = await idb.imagesAll()
|
||
assert.strictEqual(all.length, 2, 'imagesAll 应遍历 images store')
|
||
assert.ok(all.every((e) => typeof e.key === 'string' && e.value && typeof e.value.v === 'number'))
|
||
|
||
// 有意差异:写事务失败 → 重置连接并重试一次(第二次成功)
|
||
const retryIdb = load(createFakeIndexedDB({ firstWriteError: true })).create({})
|
||
assert.strictEqual(await retryIdb.put('k', { v: 9 }), true, '首次写失败应重试一次并成功')
|
||
assert.strictEqual(JSON.stringify(await retryIdb.get('k')), JSON.stringify({ v: 9 }))
|
||
|
||
// 无 IndexedDB(Node / 单文件)→ 全部空返回、不抛错
|
||
const noIdb = load(undefined).create({})
|
||
assert.strictEqual(await noIdb.put('x', 1), false)
|
||
assert.strictEqual(await noIdb.get('x'), null)
|
||
assert.strictEqual(await noIdb.del('x'), true)
|
||
assert.strictEqual(JSON.stringify(await noIdb.keys()), '[]')
|
||
assert.strictEqual(JSON.stringify(await noIdb.imagesAll()), '[]')
|
||
|
||
console.log('storage fallback indexeddb checks passed')
|
||
}
|
||
|
||
main().catch((e) => { console.error(e); process.exit(1) })
|