Base64.test.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const { ethers } = require('hardhat');
  2. const { expect } = require('chai');
  3. const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
  4. // Replace "+/" with "-_" in the char table, and remove the padding
  5. // see https://datatracker.ietf.org/doc/html/rfc4648#section-5
  6. const base64toBase64Url = str => str.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
  7. async function fixture() {
  8. const mock = await ethers.deployContract('$Base64');
  9. return { mock };
  10. }
  11. describe('Strings', function () {
  12. beforeEach(async function () {
  13. Object.assign(this, await loadFixture(fixture));
  14. });
  15. describe('base64', function () {
  16. for (const { title, input, expected } of [
  17. { title: 'converts to base64 encoded string with double padding', input: 'test', expected: 'dGVzdA==' },
  18. { title: 'converts to base64 encoded string with single padding', input: 'test1', expected: 'dGVzdDE=' },
  19. { title: 'converts to base64 encoded string without padding', input: 'test12', expected: 'dGVzdDEy' },
  20. { title: 'converts to base64 encoded string (/ case)', input: 'où', expected: 'b/k=' },
  21. { title: 'converts to base64 encoded string (+ case)', input: 'zs~1t8', expected: 'enN+MXQ4' },
  22. { title: 'empty bytes', input: '', expected: '' },
  23. ])
  24. it(title, async function () {
  25. const buffer = Buffer.from(input, 'ascii');
  26. expect(await this.mock.$encode(buffer)).to.equal(ethers.encodeBase64(buffer));
  27. expect(await this.mock.$encode(buffer)).to.equal(expected);
  28. });
  29. });
  30. describe('base64url', function () {
  31. for (const { title, input, expected } of [
  32. { title: 'converts to base64url encoded string with double padding', input: 'test', expected: 'dGVzdA' },
  33. { title: 'converts to base64url encoded string with single padding', input: 'test1', expected: 'dGVzdDE' },
  34. { title: 'converts to base64url encoded string without padding', input: 'test12', expected: 'dGVzdDEy' },
  35. { title: 'converts to base64url encoded string (_ case)', input: 'où', expected: 'b_k' },
  36. { title: 'converts to base64url encoded string (- case)', input: 'zs~1t8', expected: 'enN-MXQ4' },
  37. { title: 'empty bytes', input: '', expected: '' },
  38. ])
  39. it(title, async function () {
  40. const buffer = Buffer.from(input, 'ascii');
  41. expect(await this.mock.$encodeURL(buffer)).to.equal(base64toBase64Url(ethers.encodeBase64(buffer)));
  42. expect(await this.mock.$encodeURL(buffer)).to.equal(expected);
  43. });
  44. });
  45. });