Files
WebTools/tests/signatureVerificationFile.test.ts
T

55 lines
2.7 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { parseSignatureFile } from '../src/lib/signatureVerificationFile'
const intelHex = ':020000040001F9\n:040000001122334452\n:02001000AABB89\n:00000001FF\n'
function testFile(name: string, bytes: Uint8Array): File {
return {
name,
size: bytes.length,
arrayBuffer: async () => bytes.slice().buffer,
text: async () => new TextDecoder().decode(bytes),
} as File
}
describe('signature verification file semantics', () => {
it('keeps every byte in raw-file mode, including an empty file', async () => {
const bytes = new TextEncoder().encode(intelHex)
const raw = await parseSignatureFile(testFile('firmware.hex', bytes), 'raw-file')
const empty = await parseSignatureFile(testFile('empty.bin', new Uint8Array()), 'raw-file')
expect(raw.data).toEqual(bytes)
expect(raw.blockCount).toBeUndefined()
expect(empty.dataBytes).toBe(0)
})
it('parses and concatenates only Intel HEX effective data without gap filling', async () => {
const parsed = await parseSignatureFile(testFile('firmware.hex', new TextEncoder().encode(intelHex)), 'intel-hex')
expect(parsed.blockCount).toBe(2)
expect(parsed.dataBytes).toBe(6)
expect([...parsed.data]).toEqual([0x11, 0x22, 0x33, 0x44, 0xAA, 0xBB])
expect(parsed).toMatchObject({ effectiveDataBytes: 6, headerBytes: 0 })
})
it('prepends an 8-byte address and length header to every block', async () => {
const file = testFile('firmware.hex', new TextEncoder().encode(intelHex))
const bigEndian = await parseSignatureFile(file, 'intel-hex-block-header', 'big-endian')
const littleEndian = await parseSignatureFile(file, 'intel-hex-block-header', 'little-endian')
expect(bigEndian).toMatchObject({ dataBytes: 22, effectiveDataBytes: 6, headerBytes: 16, blockCount: 2 })
expect([...bigEndian.data]).toEqual([
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x11, 0x22, 0x33, 0x44,
0x00, 0x01, 0x00, 0x10, 0x00, 0x00, 0x00, 0x02, 0xAA, 0xBB,
])
expect([...littleEndian.data]).toEqual([
0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44,
0x10, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0xAA, 0xBB,
])
})
it('rejects invalid modes and malformed Intel HEX', async () => {
await expect(parseSignatureFile(testFile('bad.hex', new TextEncoder().encode(':00000001FE\n')), 'intel-hex')).rejects.toThrow()
await expect(parseSignatureFile(testFile('data.bin', Uint8Array.from([1])), 'automatic' as never)).rejects.toThrow('文件数据模式无效')
await expect(parseSignatureFile(testFile('firmware.hex', new TextEncoder().encode(intelHex)), 'intel-hex-block-header', 'middle-endian' as never)).rejects.toThrow('字节序')
})
})