test.deflator.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* eslint-disable no-console */
  2. const expect = chai.expect;
  3. import { inflateInit, inflate } from "../vendor/pako/lib/zlib/inflate.js";
  4. import ZStream from "../vendor/pako/lib/zlib/zstream.js";
  5. import Deflator from "../core/deflator.js";
  6. function _inflator(compText, expected) {
  7. let strm = new ZStream();
  8. let chunkSize = 1024 * 10 * 10;
  9. strm.output = new Uint8Array(chunkSize);
  10. inflateInit(strm, 5);
  11. if (expected > chunkSize) {
  12. chunkSize = expected;
  13. strm.output = new Uint8Array(chunkSize);
  14. }
  15. /* eslint-disable camelcase */
  16. strm.input = compText;
  17. strm.avail_in = strm.input.length;
  18. strm.next_in = 0;
  19. strm.next_out = 0;
  20. strm.avail_out = expected.length;
  21. /* eslint-enable camelcase */
  22. let ret = inflate(strm, 0);
  23. // Check that return code is not an error
  24. expect(ret).to.be.greaterThan(-1);
  25. return new Uint8Array(strm.output.buffer, 0, strm.next_out);
  26. }
  27. describe('Deflate data', function () {
  28. it('should be able to deflate messages', function () {
  29. let deflator = new Deflator();
  30. let text = "123asdf";
  31. let preText = new Uint8Array(text.length);
  32. for (let i = 0; i < preText.length; i++) {
  33. preText[i] = text.charCodeAt(i);
  34. }
  35. let compText = deflator.deflate(preText);
  36. let inflatedText = _inflator(compText, text.length);
  37. expect(inflatedText).to.array.equal(preText);
  38. });
  39. it('should be able to deflate large messages', function () {
  40. let deflator = new Deflator();
  41. /* Generate a big string with random characters. Used because
  42. repetition of letters might be deflated more effectively than
  43. random ones. */
  44. let text = "";
  45. let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  46. for (let i = 0; i < 300000; i++) {
  47. text += characters.charAt(Math.floor(Math.random() * characters.length));
  48. }
  49. let preText = new Uint8Array(text.length);
  50. for (let i = 0; i < preText.length; i++) {
  51. preText[i] = text.charCodeAt(i);
  52. }
  53. let compText = deflator.deflate(preText);
  54. //Check that the compressed size is expected size
  55. expect(compText.length).to.be.greaterThan((1024 * 10 * 10) * 2);
  56. let inflatedText = _inflator(compText, text.length);
  57. expect(inflatedText).to.array.equal(preText);
  58. });
  59. });