summaryrefslogtreecommitdiff
path: root/tests/test.deflator.js
blob: 2f2fab3a2f169af89a3fac529092ee7030053032 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/* eslint-disable no-console */
const expect = chai.expect;

import { inflateInit, inflate } from "../vendor/pako/lib/zlib/inflate.js";
import ZStream from "../vendor/pako/lib/zlib/zstream.js";
import Deflator from "../core/deflator.js";

function _inflator(compText, expected) {
    let strm = new ZStream();
    let chunkSize = 1024 * 10 * 10;
    strm.output = new Uint8Array(chunkSize);

    inflateInit(strm, 5);

    if (expected > chunkSize) {
        chunkSize = expected;
        strm.output = new Uint8Array(chunkSize);
    }

    strm.input = compText;
    strm.avail_in = strm.input.length;
    strm.next_in = 0;

    strm.next_out = 0;
    strm.avail_out = expected.length;

    let ret = inflate(strm, 0);

    // Check that return code is not an error
    expect(ret).to.be.greaterThan(-1);

    return new Uint8Array(strm.output.buffer, 0, strm.next_out);
}

describe('Deflate data', function () {

    it('should be able to deflate messages', function () {
        let deflator = new Deflator();

        let text = "123asdf";
        let preText = new Uint8Array(text.length);
        for (let i = 0; i < preText.length; i++) {
            preText[i] = text.charCodeAt(i);
        }

        let compText = deflator.deflate(preText);

        let inflatedText = _inflator(compText, text.length);
        expect(inflatedText).to.array.equal(preText);

    });

    it('should be able to deflate large messages', function () {
        let deflator = new Deflator();

        /* Generate a big string with random characters. Used because
           repetition of letters might be deflated more effectively than
           random ones. */
        let text = "";
        let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        for (let i = 0; i < 300000; i++) {
            text += characters.charAt(Math.floor(Math.random() * characters.length));
        }

        let preText = new Uint8Array(text.length);
        for (let i = 0; i < preText.length; i++) {
            preText[i] = text.charCodeAt(i);
        }

        let compText = deflator.deflate(preText);

        //Check that the compressed size is expected size
        expect(compText.length).to.be.greaterThan((1024 * 10 * 10) * 2);

        let inflatedText = _inflator(compText, text.length);

        expect(inflatedText).to.array.equal(preText);

    });
});