Skip to content

Commit

Permalink
feat: validate input value for fromBuffer()
Browse files Browse the repository at this point in the history
  • Loading branch information
waitingsong committed Jun 11, 2019
1 parent 4ce5c24 commit c5f8a72
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/lib/nodejs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,12 @@ export function fromBuffer(buf: ArrayBuffer | Uint8Array): string {
else if (ArrayBuffer.isView(buf)) {
inst = Buffer.from(buf)
}
else {
else if (buf instanceof ArrayBuffer) {
inst = Buffer.from(buf)
}
else {
throw new TypeError(ErrorMsg.fromArrayBufferInvalidParam)
}

const ret = inst.toString('base64')
return ret
Expand Down
64 changes: 64 additions & 0 deletions test/20_nodejs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/// <reference types="mocha" />

import {
basename,
join,
} from '@waiting/shared-core'
import * as assert from 'power-assert'
import rewire = require('rewire')
import {
TextDecoder as NodeTextDecoder,
TextEncoder as NodeTextEncoder,
} from 'util'

import { ErrorMsg } from '../src/index'
import {
fromBuffer,
} from '../src/lib/browser'
import { defaultConfig } from '../src/lib/config'

import { input44, input8 } from './config'


const filename = basename(__filename)
const mods = rewire('../src/lib/helper')

describe(filename, () => {
describe('fromBuffer() works', () => {
it('with ArrayBuffer input', () => {
input8.forEach(row => {
const u8arr = Uint8Array.from(row[0])
const actual = fromBuffer(u8arr.buffer)
const expected = row[1]
assert(actual === expected, `Ensure that ${u8arr} serialise to ${expected}`)
})
})

it('with Uint8Array input', () => {
input8.forEach(row => {
const u8arr = Uint8Array.from(row[0])
const actual = fromBuffer(u8arr)
const expected = row[1]
assert(actual === expected, `Ensure that ${u8arr} serialise to ${expected}`)
})
})

it('with invalid input', () => {
input44.forEach(value => {
try {
// @ts-ignore
fromBuffer(value)
assert(false, 'Should throw error, but NOT')
}
catch (ex) {
assert(
ex.message && ex.message.includes(ErrorMsg.fromArrayBufferInvalidParam),
ex.message,
)
}
})
})
})


})

0 comments on commit c5f8a72

Please sign in to comment.