feat: accept Buffer input (#39)

README states that input can be a Buffer, but
https://github.com/multiformats/js-mafmt/blob/v6.0.6/src/index.js#L148
would fail due to missing Buffer.protoNames

This commit moves validation to js-multiaddr and adds tests for
object and buffer variants.

License: MIT
Signed-off-by: Marcin Rataj <lidel@lidel.org>
This commit is contained in:
Marcin Rataj
2019-02-26 16:31:50 +01:00
committed by Vasco Santos
parent be174e4d9d
commit c2adc27b22
2 changed files with 24 additions and 3 deletions

View File

@ -138,7 +138,7 @@ exports.IPFS = IPFS
function makeMatchesFunction (partialMatch) {
return function matches (a) {
if (typeof a === 'string') {
if (!multiaddr.isMultiaddr(a)) {
try {
a = multiaddr(a)
} catch (err) { // catch error

View File

@ -4,6 +4,7 @@
const expect = require('chai').expect
const mafmt = require('./../src')
const multiaddr = require('multiaddr')
describe('multiaddr validation', function () {
const goodDNS = [
@ -167,7 +168,10 @@ describe('multiaddr validation', function () {
tests.forEach(function (test) {
test.forEach(function (testcase) {
try {
expect(p.matches(testcase)).to.be.eql(true)
expect(p.matches(testcase), `assertMatches: ${testcase} (string)`).to.be.eql(true)
const ma = multiaddr(testcase)
expect(p.matches(ma), `assertMatches: ${testcase} (multiaddr object)`).to.be.eql(true)
expect(p.matches(ma.buffer), `assertMatches: ${testcase} (multiaddr.buffer)`).to.be.eql(true)
} catch (err) {
err.stack = '[testcase=' + JSON.stringify(testcase) + ', shouldMatch=true] ' + err.stack
throw err
@ -181,7 +185,20 @@ describe('multiaddr validation', function () {
tests.forEach(function (test) {
test.forEach(function (testcase) {
try {
expect(p.matches(testcase)).to.be.eql(false)
expect(p.matches(testcase), `assertMismatches: ${testcase} (string)`).to.be.eql(false)
let validMultiaddrObj
try {
// if testcase string happens to be a valid multiaddr,
// we expect 'p' test to also return false for Multiaddr object and Buffer versions
validMultiaddrObj = multiaddr(testcase)
} catch (e) {
// Ignoring testcase as the string is not a multiaddr
// (There is a separate 'Buffer is invalid' test later below)
}
if (validMultiaddrObj) {
expect(p.matches(validMultiaddrObj), `assertMismatches: ${testcase} (multiaddr object)`).to.be.eql(false)
expect(p.matches(validMultiaddrObj.buffer), `assertMismatches: ${testcase} (multiaddr.buffer)`).to.be.eql(false)
}
} catch (err) {
err.stack = '[testcase=' + JSON.stringify(testcase) + ', shouldMatch=false] ' + err.stack
throw err
@ -194,6 +211,10 @@ describe('multiaddr validation', function () {
expect(mafmt.HTTP.matches('/http-google-com')).to.be.eql(false)
})
it('do not throw if multiaddr Buffer is invalid', function () {
expect(mafmt.HTTP.matches(Buffer.from('no spoon'))).to.be.eql(false)
})
it('DNS validation', function () {
assertMatches(mafmt.DNS, goodDNS)
assertMismatches(mafmt.DNS, badDNS, badIP)