malformed-urn.test.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict'
  2. const test = require('tape')
  3. const fastURI = require('..')
  4. const malformedURNs = [
  5. 'urn:',
  6. 'URN:',
  7. 'urn:foo',
  8. 'urn::foo',
  9. 'urn:foo:',
  10. 'urn:%66oo:bar'
  11. ]
  12. test('parse reports malformed ordinary URNs', (t) => {
  13. for (const uri of malformedURNs) {
  14. t.match(fastURI.parse(uri).error, /^URN can not be parsed\.?$/, uri)
  15. }
  16. t.end()
  17. })
  18. test('normalize preserves malformed ordinary URNs without throwing', (t) => {
  19. for (const uri of malformedURNs) {
  20. t.doesNotThrow(() => fastURI.normalize(uri), `${uri} does not throw`)
  21. t.equal(fastURI.normalize(uri), uri, `${uri} is preserved`)
  22. }
  23. t.equal(
  24. fastURI.normalize('urn:foo', { reference: 'relative' }),
  25. 'urn:foo',
  26. 'an earlier parse error does not hide the missing URN nid'
  27. )
  28. t.end()
  29. })
  30. test('equal returns false for malformed ordinary URNs', (t) => {
  31. for (const uri of malformedURNs) {
  32. t.equal(fastURI.equal(uri, uri, {}), false, `${uri} is not equal to itself as malformed input`)
  33. t.equal(fastURI.equal(uri, 'urn:foo:bar', {}), false, `${uri} is not equal to a valid URN`)
  34. }
  35. t.end()
  36. })
  37. test('resolve handles malformed ordinary URNs without throwing', (t) => {
  38. for (const uri of malformedURNs) {
  39. t.doesNotThrow(() => fastURI.resolve('uri://base/', uri), `${uri} does not throw as a relative reference`)
  40. t.doesNotThrow(() => fastURI.resolve(uri, ''), `${uri} does not throw as a base URI`)
  41. }
  42. // resolve preserves the malformed scheme-specific input rather than surfacing
  43. // an uncaught 'URN without nid cannot be serialized' error (matches upstream uri-js)
  44. t.equal(fastURI.resolve('uri://base/', 'urn:'), 'urn:', 'malformed relative URN is preserved')
  45. t.equal(fastURI.resolve('URN:', ''), 'urn:', 'scheme case is normalized')
  46. t.equal(fastURI.resolve('uri://base/', 'urn:%66oo:bar'), 'urn:foo:bar', 'percent-encoding is decoded')
  47. t.end()
  48. })
  49. test('valid URNs retain their existing behavior', (t) => {
  50. t.equal(fastURI.normalize('URN:FOO:a123,456'), 'urn:foo:a123,456')
  51. t.equal(fastURI.equal('urn:foo:a123,456', 'URN:FOO:a123,456', {}), true)
  52. t.equal(fastURI.resolve('uri://base/', 'urn:'), 'urn:', 'default resolve behavior is unchanged')
  53. t.end()
  54. })