Files
zyt/admin/tests/mobile-recording-media.test.cjs
2026-11-09 11:56:28 +08:00

208 lines
17 KiB
JavaScript

'use strict'
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const { createRequire } = require('node:module')
const root = path.resolve(process.env.MOBILE_RECORDING_ADMIN_ROOT || path.join(__dirname, '..'))
const sourceRoot = path.resolve(process.env.MOBILE_RECORDING_SOURCE_ROOT || root)
const requireAdmin = createRequire(path.join(root, 'package.json'))
const vue = requireAdmin('vue')
const ts = requireAdmin('typescript')
const sfc = requireAdmin('@vue/compiler-sfc')
const apiSource = fs.readFileSync(path.join(sourceRoot, 'src/api/mobileRecording.ts'), 'utf8')
const filename = path.join(sourceRoot, 'src/views/tcm/diagnosis/components/MobileRecordingPanel.vue')
const parsed = sfc.parse(fs.readFileSync(filename, 'utf8'), { filename })
assert.deepEqual(parsed.errors, [])
const script = sfc.compileScript(parsed.descriptor, { id: 'mobile-media-test' })
const template = sfc.compileTemplate({ source: parsed.descriptor.template.content, filename, id: 'mobile-media-test', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
for (const style of parsed.descriptor.styles) assert.deepEqual(sfc.compileStyle({ source: style.content, filename, id: 'mobile-media-test', scoped: true }).errors, [])
function execute(source, dependencies, globals = {}) {
const output = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', ...Object.keys(globals), output)(dependencies, module, module.exports, ...Object.values(globals))
return module.exports
}
function apiWith(get) { return execute(apiSource, name => { assert.equal(name, '@/utils/request'); return { default: { get } } }) }
const apiTypes = apiWith(() => { throw new Error('Unexpected live API call') })
const deferred = () => { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
const flush = async () => { for (let i = 0; i < 12; i++) { await Promise.resolve(); await vue.nextTick() } }
const row = (id = 1, diagnosisId = 101, extra = {}) => ({ id, diagnosis_id: diagnosisId, source_platform: 'android_bcr', recorded_at: 1700000000000, duration_ms: 12000, bound_by: '合成账号', playback_location: 'original_device', created_at: 1, updated_at: 1, ...extra })
const page = (lists, total = lists.length) => ({ lists, count: total, page_no: 1, page_size: 20 })
function fixture(overrides = {}, options = {}) {
const calls = [], created = [], revoked = [], roots = [], hooks = {}
const deps = {
...apiTypes,
mobileRecordingPatientLists: async (params, signal) => { calls.push(['list', params, signal]); return page([row(1, params.diagnosis_id, { audio_available: true, transcript_available: true, upload_state: 'complete' })]) },
mobileRecordingAudio: async (id, diagnosisId, signal, progress) => { calls.push(['audio', id, diagnosisId, signal]); progress(8, 8); return new Blob(['synthetic'], { type: 'audio/wav' }) },
mobileRecordingTranscript: async (id, diagnosisId, signal) => { calls.push(['text', id, diagnosisId, signal]); return { text: '合成转写', sha256: 'a'.repeat(64), size_bytes: 12 } },
...overrides
}
const component = execute(script.content, name => {
if (name === 'vue') return { ...vue, onDeactivated: callback => { hooks.deactivate = callback }, onActivated: callback => { hooks.activate = callback } }
if (name === '@/api/mobileRecording') return deps
throw new Error('Unexpected dependency: ' + name)
}, { URL: { createObjectURL: blob => { const url = `blob:synthetic-${created.length}`; created.push({ url, blob }); return url }, revokeObjectURL: url => revoked.push(url) } }).default
component.render = options.render ? execute(template.code, name => { assert.equal(name, 'vue'); return vue }).render : () => null
const renderer = vue.createRenderer({
createElement: tag => ({ tag, children: [], props: {}, pause() { this.paused = true }, removeAttribute(name) { delete this.props[name] }, load() { this.reloaded = true } }),
createText: text => ({ text }), createComment: text => ({ comment: text }),
setText: (node, text) => { node.text = text }, setElementText: (node, text) => { node.text = text; node.children = [] },
patchProp: (node, name, prev, next) => { node.props[name] = next },
parentNode: node => node.parent || null, nextSibling: () => null,
insert(node, parent) { node.parent = parent; (parent.children ||= []).push(node) },
remove(node) { if (node.parent) node.parent.children = node.parent.children.filter(child => child !== node) }
})
const props = vue.reactive({ diagnosisId: 101 })
const app = renderer.createApp({ setup: () => () => vue.h(component, props) })
const slotComponent = vue.defineComponent({ setup: (_, { slots }) => () => vue.h('div', slots.default?.()) })
for (const name of ['ElButton', 'ElAlert', 'ElProgress', 'ElEmpty', 'ElTag', 'ElPagination', 'ElTableColumn']) app.component(name, slotComponent)
app.component('ElTable', { render: () => null })
app.component('ElDrawer', { props: ['modelValue'], setup: (p, { slots }) => () => p.modelValue ? vue.h('section', slots.default?.()) : null })
app.directive('loading', {})
const rootNode = { tag: 'root', children: [] }; roots.push(rootNode); app.mount(rootNode)
return { state: app._instance.subTree.component.setupState, props, calls, created, revoked, roots, hooks, dispose: () => app.unmount() }
}
function findNodes(node, tag, found = []) { if (node.tag === tag) found.push(node); for (const child of node.children || []) findNodes(child, tag, found); return found }
test('audio uses existing authenticated request, fixed endpoint, diagnosis anchor, cancellable blob and long timeout', async () => {
const calls = []; const controller = new AbortController(); const progress = []
const api = apiWith(async (config, options) => { calls.push([config, options]); config.onDownloadProgress({ loaded: 6, total: 12 }); return new Blob(['audio'], { type: 'audio/wav' }) })
const blob = await api.mobileRecordingAudio(7, 101, controller.signal, (...values) => progress.push(values))
assert.equal(blob.type, 'audio/wav'); assert.deepEqual(progress, [[6, 12]])
const [config, options] = calls[0]
assert.equal(config.url, '/tcm.mobileRecordingMedia/audio'); assert.deepEqual(config.params, { binding_id: 7, diagnosis_id: 101 })
assert.equal(config.responseType, 'blob'); assert.equal(config.signal, controller.signal); assert.equal(config.timeout, 300000)
assert.equal(options.withToken, true); assert.equal(options.isOpenRetry, false); assert.equal(options.isTransformResponse, false)
assert.equal(config.url.includes('token'), false); assert.equal('token' in config.params, false)
})
test('HTTP 200 JSON denial or non-audio payload never becomes a playable blob', async () => {
for (const code of [0, -1, 10]) {
const api = apiWith(async () => new Blob([JSON.stringify({ code, msg: '合成权限拒绝', data: [] })], { type: 'application/json' }))
await assert.rejects(api.mobileRecordingAudio(1, 101), error => error instanceof api.MobileRecordingMediaError && error.code === code)
}
for (const blob of [new Blob(['<html>login</html>'], { type: 'text/html' }), new Blob([], { type: 'audio/wav' }), new Blob(['{}'], { type: 'application/json' })]) {
const api = apiWith(async () => blob); await assert.rejects(api.mobileRecordingAudio(1, 101), api.MobileRecordingMediaError)
}
})
test('aborted audio is rejected even when the request resolves late; no request starts with an aborted signal', async () => {
let calls = 0; const wait = deferred(); const controller = new AbortController()
const api = apiWith(async () => { calls++; return wait.promise })
const pending = api.mobileRecordingAudio(1, 101, controller.signal); controller.abort(); wait.resolve(new Blob(['audio'], { type: 'audio/wav' }))
await assert.rejects(pending, error => error.name === 'AbortError')
await assert.rejects(api.mobileRecordingAudio(1, 101, controller.signal), error => error.name === 'AbortError')
assert.equal(calls, 1)
})
test('transcript reads envelope, keeps plain text including empty, rejects permission and malformed success', async () => {
const text = '<img src=x onerror=alert(1)>\n纯文本'
for (const value of [text, '']) {
const api = apiWith(async (config, options) => { assert.deepEqual(config.params, { binding_id: 1, diagnosis_id: 101 }); assert.equal(options.withToken, true); return { code: 1, data: { text: value, sha256: 'a'.repeat(64), size_bytes: value.length } } })
assert.equal((await api.mobileRecordingTranscript(1, 101)).text, value)
}
for (const response of [{ code: 0, msg: '无权读取', data: [] }, { code: 1, data: {} }, { code: 1, data: { text: 'x', size_bytes: 9 * 1024 * 1024 } }]) {
const api = apiWith(async () => response); await assert.rejects(api.mobileRecordingTranscript(1, 101), api.MobileRecordingMediaError)
}
})
test('download names only use validated identifiers and allowed extensions', () => {
assert.equal(apiTypes.mobileRecordingDownloadName(7, 'audio', 'audio/mpeg'), 'recording-7.mp3')
assert.equal(apiTypes.mobileRecordingDownloadName(7, 'transcript'), 'transcript-7.txt')
assert.equal(apiTypes.mobileRecordingDownloadName('../private', 'audio', '../../secret'), 'recording-0.audio')
})
test('legacy metadata remains not uploaded; four upload states and media availability stay explicit', async () => {
const f = fixture({ mobileRecordingPatientLists: async () => page([row()]) }); await flush()
assert.equal(f.state.uploadStatus(row()).label, '未上传')
for (const [state, label] of [['not_uploaded', '未上传'], ['uploading', '上传中'], ['partial', '部分已上传'], ['complete', '上传完成']]) assert.equal(f.state.uploadStatus(row(1, 101, { upload_state: state })).label, label)
f.state.openMedia(f.state.rows[0], 'audio'); await flush(); assert.equal(f.state.mediaVisible, false); assert.equal(f.created.length, 0)
f.dispose()
})
test('successful audio loads progress, uses only a blob URL, and closes with revoke and player stop', async () => {
const f = fixture({}, { render: true }); await flush(); f.state.openMedia(f.state.rows[0], 'audio'); await flush()
assert.equal(f.state.mediaReady, true); assert.equal(f.state.mediaLoading, false); assert.equal(f.state.downloadPercent, 100)
assert.equal(f.state.mediaUrl, 'blob:synthetic-0'); assert.equal(f.state.mediaFilename, 'recording-1.wav')
const player = f.state.audioElement; assert.ok(player)
f.state.closeMedia(); await flush()
assert.equal(player.paused, true); assert.equal(player.reloaded, true); assert.deepEqual(f.revoked, ['blob:synthetic-0'])
assert.equal(f.state.mediaUrl, ''); assert.equal(f.state.mediaRow, null); f.dispose()
})
test('permission errors clear media content and explicit retry can recover', async () => {
let attempt = 0
const f = fixture({ mobileRecordingAudio: async () => { if (++attempt === 1) throw new apiTypes.MobileRecordingMediaError('患者不存在或无权操作', 0); return new Blob(['synthetic'], { type: 'audio/wav' }) } })
await flush(); f.state.openMedia(f.state.rows[0], 'audio'); await flush()
assert.match(f.state.mediaError, /无权/); assert.equal(f.created.length, 0); assert.equal(f.state.mediaReady, false)
await f.state.loadMedia(); assert.equal(attempt, 2); assert.equal(f.state.mediaError, ''); assert.equal(f.state.mediaReady, true)
f.dispose(); assert.equal(f.revoked.length, 1)
})
test('diagnosis switch aborts media and late audio or progress never becomes new-patient content', async () => {
const wait = deferred(); let signal, progress
const f = fixture({ mobileRecordingAudio: async (_id, diagnosis, s, p) => { assert.equal(diagnosis, 101); signal = s; progress = p; return wait.promise } })
await flush(); f.state.openMedia(f.state.rows[0], 'audio'); await flush(); assert.equal(f.state.mediaLoading, true)
f.props.diagnosisId = 202; await flush(); assert.equal(signal.aborted, true); assert.equal(f.state.mediaVisible, false)
progress(99, 100); wait.resolve(new Blob(['old'], { type: 'audio/wav' })); await flush()
assert.equal(f.created.length, 0); assert.equal(f.state.downloadLoaded, 0); assert.equal(f.state.rows[0].diagnosis_id, 202); f.dispose()
})
test('old transcript cannot overwrite a new selection and text renders as text nodes, never markup', async () => {
const wait = deferred(); let firstSignal
const raw = '<img src=x onerror=alert(1)>\n<script>unsafe()</script>'
const f = fixture({
mobileRecordingPatientLists: async () => page([row(1, 101, { transcript_available: true }), row(2, 101, { transcript_available: true })]),
mobileRecordingTranscript: async (id, _diagnosis, signal) => { if (id === 1) { firstSignal = signal; return wait.promise }; return { text: raw, size_bytes: raw.length, sha256: 'a'.repeat(64) } }
}, { render: true })
await flush(); f.state.openMedia(f.state.rows[0], 'transcript'); await flush(); f.state.openMedia(f.state.rows[1], 'transcript'); await flush()
assert.equal(firstSignal.aborted, true); assert.equal(f.state.transcriptText, raw)
const pre = findNodes(f.roots[0], 'pre'); assert.equal(pre.length, 1); assert.equal(pre[0].text, raw)
assert.equal(findNodes(f.roots[0], 'img').length, 0); assert.equal(findNodes(f.roots[0], 'script').length, 0)
wait.resolve({ text: '旧患者文字', size_bytes: 12, sha256: 'a'.repeat(64) }); await flush()
assert.equal(f.state.transcriptText, raw); assert.equal(f.created.length, 1); assert.equal(f.state.mediaFilename, 'transcript-2.txt')
f.dispose(); assert.deepEqual(f.revoked, ['blob:synthetic-0']); assert.equal(f.state.transcriptText, '')
})
test('closing during download and unmount abort requests without retaining stale blobs or text', async () => {
for (const finish of ['close', 'unmount']) {
const wait = deferred(); let signal
const f = fixture({ mobileRecordingTranscript: async (_id, _diagnosis, s) => { signal = s; return wait.promise } })
await flush(); f.state.openMedia(f.state.rows[0], 'transcript'); await flush()
if (finish === 'close') f.state.closeMedia(); else f.dispose()
assert.equal(signal.aborted, true); wait.resolve({ text: 'late', size_bytes: 4, sha256: 'a'.repeat(64) }); await flush()
assert.equal(f.created.length, 0); assert.equal(f.state.transcriptText, ''); if (finish === 'close') f.dispose()
}
})
test('deactivation revokes loaded media and activation reloads only the current diagnosis', async () => {
const f = fixture(); await flush(); f.state.openMedia(f.state.rows[0], 'audio'); await flush()
f.hooks.deactivate(); assert.deepEqual(f.revoked, ['blob:synthetic-0']); assert.equal(f.state.rows.length, 0)
f.props.diagnosisId = 303; await flush(); assert.equal(f.state.rows.length, 0)
f.hooks.activate(); await flush(); assert.equal(f.state.rows[0].diagnosis_id, 303); f.dispose()
})
test('list generation cancels old requests and preserves the repaired out-of-range pagination', async () => {
let count = 21; const pages = [], signals = []
const f = fixture({ mobileRecordingPatientLists: async (params, signal) => {
pages.push(params.page_no); signals.push(signal)
const start = (params.page_no - 1) * 20
return page(Array.from({ length: Math.max(0, Math.min(20, count - start)) }, (_, i) => row(start + i + 1, params.diagnosis_id)), count)
} })
await flush(); f.state.page = 2; await f.state.load(); assert.equal(f.state.rows.length, 1)
count = 20; await f.state.load(); assert.equal(f.state.page, 1); assert.equal(f.state.rows.length, 20); assert.equal(f.state.total, 20)
assert.deepEqual(pages, [1, 2, 2, 1]); assert.ok(signals.slice(0, -1).every(signal => signal.aborted))
f.dispose(); assert.equal(signals.at(-1).aborted, true)
})
test('late list response after patient switch cannot restore old rows or trigger a correction fetch', async () => {
const requests = []
const f = fixture({ mobileRecordingPatientLists: (params, signal) => { const wait = deferred(); requests.push({ params, signal, ...wait }); return wait.promise } })
assert.equal(requests.length, 1); f.props.diagnosisId = 202; await flush(); assert.equal(requests[0].signal.aborted, true)
requests[1].resolve(page([row(2, 202)])); await flush(); requests[0].resolve(page([row(1, 101)])); await flush()
assert.equal(f.state.rows[0].diagnosis_id, 202); assert.equal(requests.length, 2); f.dispose()
})