Skip to content

Commit

Permalink
chore(test): use chai throws() & chai-as-promised isRejected()
Browse files Browse the repository at this point in the history
  • Loading branch information
rvagg committed Jan 7, 2022
1 parent f850c5f commit 6e4ba86
Show file tree
Hide file tree
Showing 8 changed files with 72 additions and 94 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,15 @@
"@stablelib/sha256": "^1.0.1",
"@stablelib/sha512": "^1.0.1",
"@types/chai": "^4.3.0",
"@types/chai-as-promised": "^7.1.4",
"@types/mocha": "^9.0.0",
"@types/node": "^17.0.0",
"@typescript-eslint/eslint-plugin": "^5.6.0",
"@typescript-eslint/parser": "^5.6.0",
"buffer": "^6.0.3",
"c8": "^7.10.0",
"chai": "^4.3.4",
"chai-as-promised": "^7.1.1",
"cids": "^1.1.9",
"ipjs": "^5.2.0",
"mocha": "^9.1.3",
Expand Down
29 changes: 0 additions & 29 deletions test/fixtures/test-throw.js

This file was deleted.

27 changes: 15 additions & 12 deletions test/test-block.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ import * as codec from 'multiformats/codecs/json'
import { sha256 as hasher } from 'multiformats/hashes/sha2'
import * as main from 'multiformats/block'
import { CID, bytes } from 'multiformats'
import { assert } from 'chai'
import { testThrowAsync, testThrowSync } from './fixtures/test-throw.js'
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'

chai.use(chaiAsPromised)
const { assert } = chai

const fixture = { hello: 'world' }
const link = CID.parse('bafyreidykglsfhoixmivffc5uwhcgshx4j465xwqntbmu43nb2dzqwfvae')
Expand Down Expand Up @@ -99,7 +102,7 @@ describe('block', () => {

describe('errors', () => {
it('constructor missing args', () => {
testThrowSync(
assert.throws(
// @ts-expect-error - missing properties
() => new main.Block({}),
'Missing required argument'
Expand All @@ -108,36 +111,36 @@ describe('block', () => {

it('encode', async () => {
// @ts-expect-error
await testThrowAsync(() => main.encode({}), 'Missing required argument "value"')
await assert.isRejected(main.encode({}), 'Missing required argument "value"')
// @ts-expect-error
await testThrowAsync(() => main.encode({ value: true }), 'Missing required argument: codec or hasher')
await assert.isRejected(main.encode({ value: true }), 'Missing required argument: codec or hasher')
})

it('decode', async () => {
// @ts-expect-error
await testThrowAsync(() => main.decode({}), 'Missing required argument "bytes"')
await assert.isRejected(main.decode({}), 'Missing required argument "bytes"')
// @ts-expect-error
await testThrowAsync(() => main.decode({ bytes: true }), 'Missing required argument: codec or hasher')
await assert.isRejected(main.decode({ bytes: true }), 'Missing required argument: codec or hasher')
})

it('createUnsafe', async () => {
// @ts-expect-error
await testThrowAsync(() => main.createUnsafe({}), 'Missing required argument, must either provide "value" or "codec"')
assert.throws(() => main.createUnsafe({}), 'Missing required argument, must either provide "value" or "codec"')
})

it('create', async () => {
// @ts-expect-error
await testThrowAsync(() => main.create({}), 'Missing required argument "bytes"')
await assert.isRejected(main.create({}), 'Missing required argument "bytes"')
// @ts-expect-error
await testThrowAsync(() => main.create({ bytes: true }), 'Missing required argument "hasher"')
await assert.isRejected(main.create({ bytes: true }), 'Missing required argument "hasher"')
const block = await main.encode({ value: fixture, codec, hasher })
const block2 = await main.encode({ value: { ...fixture, test: 'blah' }, codec, hasher })
await testThrowAsync(() => main.create({ bytes: block.bytes, cid: block2.cid, codec, hasher }), 'CID hash does not match bytes')
await assert.isRejected(main.create({ bytes: block.bytes, cid: block2.cid, codec, hasher }), 'CID hash does not match bytes')
})

it('get', async () => {
const block = await main.encode({ value: fixture, codec, hasher })
await testThrowAsync(() => block.get('/asd/fs/dfasd/f'), 'Object has no property at ["asd"]')
assert.throws(() => block.get('/asd/fs/dfasd/f'), 'Object has no property at ["asd"]')
})
})
})
54 changes: 22 additions & 32 deletions test/test-cid.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,20 @@
/* globals describe, it */

import OLDCID from 'cids'
import { assert } from 'chai'
import { fromHex, toHex, equals } from '../src/bytes.js'
import { varint, CID } from 'multiformats'
import { base58btc } from 'multiformats/bases/base58'
import { base32 } from 'multiformats/bases/base32'
import { base64 } from 'multiformats/bases/base64'
import { sha256, sha512 } from 'multiformats/hashes/sha2'
import invalidMultihash from './fixtures/invalid-multihash.js'
import { testThrowSync as testThrow } from './fixtures/test-throw.js'
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'

const textEncoder = new TextEncoder()
chai.use(chaiAsPromised)
const { assert } = chai

/**
* @param {Function} fn
*/
const testThrowAny = async fn => {
try {
await fn()
} catch (e) {
return
}
/* c8 ignore next */
throw new Error('Test failed to throw')
}
const textEncoder = new TextEncoder()

describe('CID', () => {
describe('v0', () => {
Expand Down Expand Up @@ -64,28 +54,28 @@ describe('CID', () => {

it('throws on invalid BS58Str multihash ', async () => {
const msg = 'Non-base58btc character'
await testThrow(() => CID.parse('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zIII'), msg)
assert.throws(() => CID.parse('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zIII'), msg)
})

it('throws on trying to create a CIDv0 with a codec other than dag-pb', async () => {
const hash = await sha256.digest(textEncoder.encode('abc'))
const msg = 'Version 0 CID must use dag-pb (code: 112) block encoding'
await testThrow(() => CID.create(0, 113, hash), msg)
assert.throws(() => CID.create(0, 113, hash), msg)
})

// This was failing for quite some time, test just missed await so it went
// unnoticed. Not sure we still care about checking fourth argument.
// it('throws on trying to pass specific base encoding [deprecated]', async () => {
// const hash = await sha256.digest(textEncoder.encode('abc'))
// const msg = 'No longer supported, cannot specify base encoding in instantiation'
// await testThrow(() => CID.create(0, 112, hash, 'base32'), msg)
// assert.throws(() => CID.create(0, 112, hash, 'base32'), msg)
// })

it('throws on trying to base encode CIDv0 in other base than base58btc', async () => {
const mhStr = 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'
const cid = CID.parse(mhStr)
const msg = 'Cannot string encode V0 in base32 encoding'
await testThrow(() => cid.toString(base32), msg)
assert.throws(() => cid.toString(base32), msg)
})

it('.bytes', async () => {
Expand Down Expand Up @@ -272,7 +262,7 @@ describe('CID', () => {

for (const i of parse) {
const name = `CID.parse(${JSON.stringify(i)})`
it(name, async () => await testThrowAny(() => CID.parse(i)))
it(name, async () => assert.throws(() => CID.parse(i)))
}

const decode = [
Expand All @@ -282,7 +272,7 @@ describe('CID', () => {

for (const i of decode) {
const name = `CID.decode(textEncoder.encode(${JSON.stringify(i.toString())}))`
it(name, async () => await testThrowAny(() => CID.decode(i)))
it(name, async () => assert.throws(() => CID.decode(i)))
}

const create = [
Expand All @@ -296,7 +286,7 @@ describe('CID', () => {
const mh = hash instanceof Uint8Array ? `textEncoder.encode(${form})` : form
const name = `CID.create(${version}, ${code}, ${mh})`
// @ts-expect-error - version issn't always 0|1
it(name, async () => await testThrowAny(() => CID.create(version, code, hash)))
it(name, async () => assert.throws(() => CID.create(version, code, hash)))
}

it('invalid fixtures', async () => {
Expand Down Expand Up @@ -333,13 +323,13 @@ describe('CID', () => {
it('should not convert v1 to v0 if not dag-pb codec', async () => {
const hash = await sha256.digest(textEncoder.encode(`TEST${Date.now()}`))
const cid = CID.create(1, 0x71, hash)
await testThrow(() => cid.toV0(), 'Cannot convert a non dag-pb CID to CIDv0')
assert.throws(() => cid.toV0(), 'Cannot convert a non dag-pb CID to CIDv0')
})

it('should not convert v1 to v0 if not sha2-256 multihash', async () => {
const hash = await sha512.digest(textEncoder.encode(`TEST${Date.now()}`))
const cid = CID.create(1, 112, hash)
await testThrow(() => cid.toV0(), 'Cannot convert non sha2-256 multihash CID to CIDv0')
assert.throws(() => cid.toV0(), 'Cannot convert non sha2-256 multihash CID to CIDv0')
})

it('should return assert.deepStrictEqual instance when converting v1 to v1', async () => {
Expand Down Expand Up @@ -523,7 +513,7 @@ describe('CID', () => {
const cid = CID.create(1, 112, hash)
const msg = 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'

await testThrow(() => CID.parse(cid.toString(base64)), msg)
assert.throws(() => CID.parse(cid.toString(base64)), msg)
})

it('parses base64 encoded CIDv1 if base64 is provided', async () => {
Expand Down Expand Up @@ -586,39 +576,39 @@ describe('CID', () => {
it('codec', async () => {
const hash = await sha256.digest(textEncoder.encode('abc'))
const cid = CID.create(1, 112, hash)
await testThrow(() => cid.codec, '"codec" property is deprecated, use integer "code" property instead')
assert.throws(() => cid.codec, '"codec" property is deprecated, use integer "code" property instead')
// @ts-expect-error - 'string' is not assignable to parameter of type 'number'
await testThrow(() => CID.create(1, 'dag-pb', hash), 'String codecs are no longer supported')
assert.throws(() => CID.create(1, 'dag-pb', hash), 'String codecs are no longer supported')
})

it('multibaseName', async () => {
const hash = await sha256.digest(textEncoder.encode('abc'))
const cid = CID.create(1, 112, hash)
await testThrow(() => cid.multibaseName, '"multibaseName" property is deprecated')
assert.throws(() => cid.multibaseName, '"multibaseName" property is deprecated')
})

it('prefix', async () => {
const hash = await sha256.digest(textEncoder.encode('abc'))
const cid = CID.create(1, 112, hash)
await testThrow(() => cid.prefix, '"prefix" property is deprecated')
assert.throws(() => cid.prefix, '"prefix" property is deprecated')
})

it('toBaseEncodedString()', async () => {
const hash = await sha256.digest(textEncoder.encode('abc'))
const cid = CID.create(1, 112, hash)
// @ts-expect-error - deprecated
await testThrow(() => cid.toBaseEncodedString(), 'Deprecated, use .toString()')
assert.throws(() => cid.toBaseEncodedString(), 'Deprecated, use .toString()')
})
})

it('invalid CID version', async () => {
const encoded = varint.encodeTo(2, new Uint8Array(32))
await testThrow(() => CID.decode(encoded), 'Invalid CID version 2')
assert.throws(() => CID.decode(encoded), 'Invalid CID version 2')
})

it('buffer', async () => {
const hash = await sha256.digest(textEncoder.encode('abc'))
const cid = CID.create(1, 112, hash)
await testThrow(() => cid.buffer, 'Deprecated .buffer property, use .bytes to get Uint8Array instead')
assert.throws(() => cid.buffer, 'Deprecated .buffer property, use .bytes to get Uint8Array instead')
})
})
9 changes: 6 additions & 3 deletions test/test-multibase-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@

import { bases } from 'multiformats/basics'
import { fromString } from '../src/bytes.js'
import { assert } from 'chai'
import { testThrowSync as testThrow } from './fixtures/test-throw.js'
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'

chai.use(chaiAsPromised)
const { assert } = chai

const encoded = [
{
Expand Down Expand Up @@ -194,7 +197,7 @@ describe('spec test', () => {
}

console.info('expect', `Non-${base.name} character`)
testThrow(() => base.decode(base.prefix + '^!@$%!#$%@#y'), `Non-${base.name} character`)
assert.throws(() => base.decode(base.prefix + '^!@$%!#$%@#y'), `Non-${base.name} character`)
})
}
})
25 changes: 14 additions & 11 deletions test/test-multibase.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/* globals describe, it */
import * as bytes from '../src/bytes.js'
import { assert } from 'chai'
import * as b2 from 'multiformats/bases/base2'
import * as b8 from 'multiformats/bases/base8'
import * as b10 from 'multiformats/bases/base10'
Expand All @@ -9,7 +8,11 @@ import * as b32 from 'multiformats/bases/base32'
import * as b36 from 'multiformats/bases/base36'
import * as b58 from 'multiformats/bases/base58'
import * as b64 from 'multiformats/bases/base64'
import { testThrowAsync as testThrow } from './fixtures/test-throw.js'
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'

chai.use(chaiAsPromised)
const { assert } = chai

const { base16, base32, base58btc, base64 } = { ...b16, ...b32, ...b58, ...b64 }

Expand Down Expand Up @@ -40,25 +43,25 @@ describe('multibase', () => {
it('bad chars', () => {
const str = base.prefix + '#$%^&*&^%$#'
const msg = `Non-${base.name} character`
testThrow(() => base.decode(str), msg)
assert.throws(() => base.decode(str), msg)
})
})
}

it('encode string failure', () => {
const msg = 'Unknown type, must be binary type'
// @ts-expect-error - expects bytes
testThrow(() => base32.encode('asdf'), msg)
assert.throws(() => base32.encode('asdf'), msg)
// @ts-expect-error - expects bytes
testThrow(() => base32.encoder.encode('asdf'), msg)
assert.throws(() => base32.encoder.encode('asdf'), msg)
})

it('decode int failure', () => {
const msg = 'Can only multibase decode strings'
// @ts-expect-error - 'number' is not assignable to parameter of type 'string'
testThrow(() => base32.decode(1), msg)
assert.throws(() => base32.decode(1), msg)
// @ts-expect-error - 'number' is not assignable to parameter of type 'string'
testThrow(() => base32.decoder.decode(1), msg)
assert.throws(() => base32.decoder.decode(1), msg)
})

const buff = bytes.fromString('test')
Expand Down Expand Up @@ -124,7 +127,7 @@ describe('multibase', () => {
it('multibase mismatch', () => {
const b64 = base64.encode(bytes.fromString('test'))
const msg = `Unable to decode multibase string "${b64}", base32 decoder only supports inputs prefixed with ${base32.prefix}`
testThrow(() => base32.decode(b64), msg)
assert.throws(() => base32.decode(b64), msg)
})

it('decoder composition', () => {
Expand All @@ -138,13 +141,13 @@ describe('multibase', () => {

const b64 = base64.encode(bytes.fromString('test'))
const msg = `Unable to decode multibase string "${b64}", only inputs prefixed with ${base32.prefix},${base58btc.prefix} are supported`
testThrow(() => base.decode(b64), msg)
assert.throws(() => base.decode(b64), msg)

const baseExt = base.or(base64)
assert.deepStrictEqual(baseExt.decode(b64), bytes.fromString('test'))

// original composition stays intact
testThrow(() => base.decode(b64), msg)
assert.throws(() => base.decode(b64), msg)

// non-composed combined with composed
const baseExt2 = base32.decoder.or(base64.decoder.or(base16.decoder))
Expand All @@ -158,7 +161,7 @@ describe('multibase', () => {
it('truncated data', () => {
const b64 = base64.encode(Uint8Array.from([245, 250]))

testThrow(() => base64.decode(b64.substring(0, b64.length - 1)), 'Unexpected end of data')
assert.throws(() => base64.decode(b64.substring(0, b64.length - 1)), 'Unexpected end of data')
})

it('infers prefix and name corretly', () => {
Expand Down
Loading

0 comments on commit 6e4ba86

Please sign in to comment.