ShortStrings.test.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. const { expect } = require('chai');
  2. const { expectRevertCustomError } = require('../helpers/customError');
  3. const ShortStrings = artifacts.require('$ShortStrings');
  4. function decode(sstr) {
  5. const length = parseInt(sstr.slice(64), 16);
  6. return web3.utils.toUtf8(sstr).slice(0, length);
  7. }
  8. contract('ShortStrings', function () {
  9. before(async function () {
  10. this.mock = await ShortStrings.new();
  11. });
  12. for (const str of [0, 1, 16, 31, 32, 64, 1024].map(length => 'a'.repeat(length))) {
  13. describe(`with string length ${str.length}`, function () {
  14. it('encode / decode', async function () {
  15. if (str.length < 32) {
  16. const encoded = await this.mock.$toShortString(str);
  17. expect(decode(encoded)).to.be.equal(str);
  18. const length = await this.mock.$length(encoded);
  19. expect(length.toNumber()).to.be.equal(str.length);
  20. const decoded = await this.mock.$toString(encoded);
  21. expect(decoded).to.be.equal(str);
  22. } else {
  23. await expectRevertCustomError(this.mock.$toShortString(str), `StringTooLong("${str}")`);
  24. }
  25. });
  26. it('set / get with fallback', async function () {
  27. const { logs } = await this.mock.$toShortStringWithFallback(str, 0);
  28. const { ret0 } = logs.find(({ event }) => event == 'return$toShortStringWithFallback').args;
  29. expect(await this.mock.$toString(ret0)).to.be.equal(str.length < 32 ? str : '');
  30. const recovered = await this.mock.$toStringWithFallback(ret0, 0);
  31. expect(recovered).to.be.equal(str);
  32. });
  33. });
  34. }
  35. });