Skip to content

Commit 4ce5c24

Browse files
committed
feat: validate input value for fromBuffer()
1 parent b7db14e commit 4ce5c24

2 files changed

Lines changed: 75 additions & 1 deletion

File tree

src/lib/browser.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,12 @@ export function fromBuffer(buf: ArrayBuffer | Uint8Array): string {
3636
else if (ArrayBuffer.isView(buf)) {
3737
input = buf
3838
}
39-
else {
39+
else if (buf instanceof ArrayBuffer) {
4040
input = new Uint8Array(buf)
4141
}
42+
else {
43+
throw new TypeError(ErrorMsg.fromArrayBufferInvalidParam)
44+
}
4245

4346
return fromUint8Array(input)
4447
}

test/20_browser.test.ts

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/// <reference types="mocha" />
2+
3+
import {
4+
basename,
5+
join,
6+
} from '@waiting/shared-core'
7+
import * as assert from 'power-assert'
8+
import rewire = require('rewire')
9+
import {
10+
TextDecoder as NodeTextDecoder,
11+
TextEncoder as NodeTextEncoder,
12+
} from 'util'
13+
14+
import { ErrorMsg } from '../src/index'
15+
import {
16+
fromBuffer,
17+
} from '../src/lib/browser'
18+
import { defaultConfig } from '../src/lib/config'
19+
20+
import { input44, input8, input9 } from './config'
21+
22+
23+
const filename = basename(__filename)
24+
const mods = rewire('../src/lib/helper')
25+
26+
describe(filename, () => {
27+
before(() => {
28+
defaultConfig.forceBrowser = true
29+
})
30+
after(() => {
31+
defaultConfig.forceBrowser = false
32+
})
33+
34+
describe('fromBuffer() works', () => {
35+
it('with ArrayBuffer input', () => {
36+
input8.forEach(row => {
37+
const u8arr = Uint8Array.from(row[0])
38+
const actual = fromBuffer(u8arr.buffer)
39+
const expected = row[1]
40+
assert(actual === expected, `Ensure that ${u8arr} serialise to ${expected}`)
41+
})
42+
})
43+
44+
it('with Uint8Array input', () => {
45+
input8.forEach(row => {
46+
const u8arr = Uint8Array.from(row[0])
47+
const actual = fromBuffer(u8arr)
48+
const expected = row[1]
49+
assert(actual === expected, `Ensure that ${u8arr} serialise to ${expected}`)
50+
})
51+
})
52+
53+
it('with invalid input', () => {
54+
input44.forEach(value => {
55+
try {
56+
// @ts-ignore
57+
fromBuffer(value)
58+
assert(false, 'Should throw error, but NOT')
59+
}
60+
catch (ex) {
61+
assert(
62+
ex.message && ex.message.includes(ErrorMsg.fromArrayBufferInvalidParam),
63+
ex.message,
64+
)
65+
}
66+
})
67+
})
68+
})
69+
70+
71+
})

0 commit comments

Comments
 (0)