aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/lz4/py3/tests/stream/test_stream_1.py
blob: 6b49267e262b01f282ed6da27bc3a479278ff026 (plain) (blame)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
import lz4.stream
import pytest
import sys
import os


if sys.version_info < (3, ):
    from struct import pack, unpack

    def _get_format(length, byteorder, signed):
        _order = {'l': '<', 'b': '>'}
        _fmt = {1: 'b', 2: 'h', 4: 'i', 8: 'q'}
        _sign = {True: lambda x: x.lower(), False: lambda x: x.upper()}
        return _sign[signed](_order[byteorder[0].lower()] + _fmt[length])

    def int_to_bytes(value, length=4, byteorder='little', signed=False):
        return bytearray(pack(_get_format(length, byteorder, signed), value))

    def int_from_bytes(bytes, byteorder='little', signed=False):
        return unpack(_get_format(len(bytes), byteorder, signed), bytes)[0]

else:
    def int_to_bytes(value, length=4, byteorder='little', signed=False):
        return value.to_bytes(length, byteorder, signed=signed)

    def int_from_bytes(bytes, byteorder='little', signed=False):
        return int.from_bytes(bytes, byteorder, signed=signed)


# This test requires allocating a big lump of memory. In order to
# avoid a massive memory allocation during byte compilation, we have
# to declare a variable for the size of the buffer we're going to
# create outside the scope of the function below. See:
# https://bugs.python.org/issue21074
_4GB = 0x100000000  # 4GB


def compress(x, c_kwargs, return_block_offset=False, check_block_type=False):
    o = [0, ]
    if c_kwargs.get('return_bytearray', False):
        c = bytearray()
    else:
        c = bytes()
    with lz4.stream.LZ4StreamCompressor(**c_kwargs) as proc:
        for start in range(0, len(x), c_kwargs['buffer_size']):
            chunk = x[start:start + c_kwargs['buffer_size']]
            block = proc.compress(chunk)
            c += block
            if return_block_offset:
                o.append(len(c))
            if check_block_type:
                assert isinstance(block, c.__class__)
    if return_block_offset:
        return c, o
    else:
        return c


def decompress(x, d_kwargs, check_chunk_type=False):
    if d_kwargs.get('return_bytearray', False):
        d = bytearray()
    else:
        d = bytes()
    with lz4.stream.LZ4StreamDecompressor(**d_kwargs) as proc:
        start = 0
        while start < len(x):
            block = proc.get_block(x[start:])
            chunk = proc.decompress(block)
            d += chunk
            start += d_kwargs['store_comp_size'] + len(block)
            if check_chunk_type:
                assert isinstance(chunk, d.__class__)
    return d


def test_invalid_config_c_1():
    c_kwargs = {}
    c_kwargs['strategy'] = "ring_buffer"
    c_kwargs['buffer_size'] = 1024

    with pytest.raises(NotImplementedError):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)


def test_invalid_config_d_1():
    d_kwargs = {}
    d_kwargs['strategy'] = "ring_buffer"
    d_kwargs['buffer_size'] = 1024

    with pytest.raises(NotImplementedError):
        lz4.stream.LZ4StreamDecompressor(**d_kwargs)


def test_invalid_config_c_2():
    c_kwargs = {}
    c_kwargs['strategy'] = "foo"
    c_kwargs['buffer_size'] = 1024

    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)


def test_invalid_config_d_2():
    d_kwargs = {}
    d_kwargs['strategy'] = "foo"
    d_kwargs['buffer_size'] = 1024

    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamDecompressor(**d_kwargs)


def test_invalid_config_c_3(store_comp_size):
    c_kwargs = {}
    c_kwargs['strategy'] = "double_buffer"
    c_kwargs['buffer_size'] = 1024
    c_kwargs['store_comp_size'] = store_comp_size['store_comp_size'] + 5

    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)


def test_invalid_config_d_3(store_comp_size):
    d_kwargs = {}
    d_kwargs['strategy'] = "double_buffer"
    d_kwargs['buffer_size'] = 1024
    d_kwargs['store_comp_size'] = store_comp_size['store_comp_size'] + 5

    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamDecompressor(**d_kwargs)


def test_invalid_config_c_4(store_comp_size):
    c_kwargs = {}
    c_kwargs['strategy'] = "double_buffer"
    c_kwargs['buffer_size'] = 1 << (8 * store_comp_size['store_comp_size'])
    c_kwargs.update(store_comp_size)

    if store_comp_size['store_comp_size'] >= 4:
        # No need for skiping this test case, since arguments check is
        # expecting to raise an error.

        # Make sure the page size is larger than what the input bound will be,
        # but still fit in 4 bytes
        c_kwargs['buffer_size'] -= 1

    if c_kwargs['buffer_size'] > lz4.stream.LZ4_MAX_INPUT_SIZE:
        message = r"^Invalid buffer_size argument: \d+. Cannot define output buffer size. Must be lesser or equal to 2113929216$"  # noqa
        err_class = ValueError
    else:
        message = r"^Inconsistent buffer_size/store_comp_size values. Maximal compressed length \(\d+\) cannot fit in a \d+ byte-long integer$"  # noqa
        err_class = lz4.stream.LZ4StreamError

    with pytest.raises(err_class, match=message):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)


def test_invalid_config_d_4(store_comp_size):
    d_kwargs = {}
    d_kwargs['strategy'] = "double_buffer"
    d_kwargs['buffer_size'] = 1 << (8 * store_comp_size['store_comp_size'])
    d_kwargs.update(store_comp_size)

    if store_comp_size['store_comp_size'] >= 4:

        if sys.maxsize < 0xffffffff:
            pytest.skip('Py_ssize_t too small for this test')

        # Make sure the page size is larger than what the input bound will be,
        # but still fit in 4 bytes
        d_kwargs['buffer_size'] -= 1

    # No failure expected during instanciation/initialization
    lz4.stream.LZ4StreamDecompressor(**d_kwargs)


def test_invalid_config_c_5():
    c_kwargs = {}
    c_kwargs['strategy'] = "double_buffer"
    c_kwargs['buffer_size'] = lz4.stream.LZ4_MAX_INPUT_SIZE

    if sys.maxsize < 0xffffffff:
        pytest.skip('Py_ssize_t too small for this test')

    # No failure expected
    lz4.stream.LZ4StreamCompressor(**c_kwargs)

    c_kwargs['buffer_size'] = lz4.stream.LZ4_MAX_INPUT_SIZE + 1
    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)

    # Make sure the page size is larger than what the input bound will be,
    # but still fit in 4 bytes
    c_kwargs['buffer_size'] = _4GB - 1  # 4GB - 1 (to fit in 4 bytes)
    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)


def test_invalid_config_d_5():
    d_kwargs = {}
    d_kwargs['strategy'] = "double_buffer"

    # No failure expected during instanciation/initialization
    d_kwargs['buffer_size'] = lz4.stream.LZ4_MAX_INPUT_SIZE

    if sys.maxsize < 0xffffffff:
        pytest.skip('Py_ssize_t too small for this test')

    lz4.stream.LZ4StreamDecompressor(**d_kwargs)

    # No failure expected during instanciation/initialization
    d_kwargs['buffer_size'] = lz4.stream.LZ4_MAX_INPUT_SIZE + 1

    if sys.maxsize < 0xffffffff:
        pytest.skip('Py_ssize_t too small for this test')

    lz4.stream.LZ4StreamDecompressor(**d_kwargs)

    # No failure expected during instanciation/initialization
    d_kwargs['buffer_size'] = _4GB - 1  # 4GB - 1 (to fit in 4 bytes)

    if sys.maxsize < 0xffffffff:
        pytest.skip('Py_ssize_t too small for this test')

    lz4.stream.LZ4StreamDecompressor(**d_kwargs)


def test_decompress_corrupted_input_1():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = compress(b'A' * 512, c_kwargs)
    decompress(data, d_kwargs)

    message = r"^Requested input size \(\d+\) larger than source size \(\d+\)$"

    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data[4:], d_kwargs)


def test_decompress_corrupted_input_2():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = compress(b'A' * 512, c_kwargs)
    decompress(data, d_kwargs)

    message = r"^Decompression failed. error: \d+$"

    # Block size corruption in the first block

    # Block size longer than actual:
    data = int_to_bytes(int_from_bytes(data[:4], 'little') + 1, 4, 'little') + data[4:]
    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)

    # Block size shorter than actual:
    data = int_to_bytes(int_from_bytes(data[:4], 'little') - 2, 4, 'little') + data[4:]
    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)


def test_decompress_corrupted_input_3():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = compress(b'A' * 512, c_kwargs)
    decompress(data, d_kwargs)

    message = r"^Decompression failed. error: \d+$"

    # Block size corruption in a block in the middle of the stream
    offset = 4 + int_from_bytes(data[:4], 'little')

    # Block size longer than actual:
    block_len = int_from_bytes(data[offset:offset + 4], 'little') + 1
    data = data[:offset] + int_to_bytes(block_len, 4, 'little') + data[offset + 4:]

    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)

    # Block size shorter than actual:
    block_len = int_from_bytes(data[offset:offset + 4], 'little') - 2
    data = data[:offset] + int_to_bytes(block_len, 4, 'little') + data[offset + 4:]

    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)


def test_decompress_corrupted_input_4():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = compress(b'A' * 256, c_kwargs)
    decompress(data, d_kwargs)

    # Block size corruption in the last block of the stream
    offset = 4 + int_from_bytes(data[:4], 'little')

    # Block size longer than actual:
    block_len = int_from_bytes(data[offset:offset + 4], 'little') + 1
    data = data[:offset] + int_to_bytes(block_len, 4, 'little') + data[offset + 4:]

    message = r"^Requested input size \(\d+\) larger than source size \(\d+\)$"

    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)

    # Block size shorter than actual:
    block_len = int_from_bytes(data[offset:offset + 4], 'little') - 2
    data = data[:offset] + int_to_bytes(block_len, 4, 'little') + data[offset + 4:]

    message = r"^Decompression failed. error: \d+$"

    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)


def test_decompress_truncated():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123" * 24
    compressed, block_offsets = compress(input_data, c_kwargs, return_block_offset=True)

    last_block_offset = 0
    for n in range(len(compressed)):
        if n in block_offsets:
            # end of input matches end of block, so decompression must succeed
            last_block_offset = n
            decompress(compressed[:n], d_kwargs)

        else:
            # end of input does not match end of block, so decompression failure is expected
            if n - last_block_offset < c_kwargs['store_comp_size']:
                message = "^Invalid source, too small for holding any block$"
            else:
                message = r"^Requested input size \(\d+\) larger than source size \(\d+\)$"

            with pytest.raises(lz4.stream.LZ4StreamError, match=message):
                decompress(compressed[:n], d_kwargs)


# This next test is probably redundant given test_decompress_truncated above
# since the trailing bytes will be considered as the truncated last block, but
# we will keep them for now


def test_decompress_with_trailer():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = b'A' * 64
    comp = compress(data, c_kwargs)

    message = "^Invalid source, too small for holding any block$"
    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(comp + b'A', d_kwargs)

    message = r"^Requested input size \(\d+\) larger than source size \(\d+\)$"
    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(comp + b'A' * 10, d_kwargs)

    for n in range(1, 10):
        if n < d_kwargs['store_comp_size']:
            message = "^Invalid source, too small for holding any block$"
        else:
            message = r"^Decompression failed. error: \d+$"
        with pytest.raises(lz4.stream.LZ4StreamError, match=message):
            decompress(comp + b'\x00' * n, d_kwargs)


def test_unicode():
    if sys.version_info < (3,):
        return  # skip

    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    DATA = b'x'
    with pytest.raises(TypeError):
        compress(DATA.decode('latin1'), c_kwargs)
        decompress(compress(DATA, c_kwargs).decode('latin1'), d_kwargs)


# These next two are probably redundant given test_1 above but we'll keep them
# for now


def test_return_bytearray():
    if sys.version_info < (3,):
        return  # skip

    c_kwargs_r = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}
    c_kwargs = {'return_bytearray': True}
    c_kwargs.update(c_kwargs_r)

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = os.urandom(128 * 1024)  # Read 128kb
    compressed = compress(data, c_kwargs_r, check_block_type=True)
    b = compress(data, c_kwargs, check_block_type=True)
    assert isinstance(b, bytearray)
    assert bytes(b) == compressed
    b = decompress(compressed, d_kwargs, check_chunk_type=True)
    assert isinstance(b, bytearray)
    assert bytes(b) == data


def test_memoryview():
    if sys.version_info < (2, 7):
        return  # skip

    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = os.urandom(128 * 1024)  # Read 128kb
    compressed = compress(data, c_kwargs)
    assert compress(memoryview(data), c_kwargs) == compressed
    assert decompress(memoryview(compressed), d_kwargs) == data


def test_with_dict_none():
    kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123" * 24
    for mode in ['default', 'high_compression']:
        c_kwargs = {'mode': mode, 'dictionary': None}
        c_kwargs.update(kwargs)
        d_kwargs = {}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

        c_kwargs = {'mode': mode}
        c_kwargs.update(kwargs)
        d_kwargs = {'dictionary': None}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

        c_kwargs = {'mode': mode, 'dictionary': b''}
        c_kwargs.update(kwargs)
        d_kwargs = {}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

        c_kwargs = {'mode': mode}
        c_kwargs.update(kwargs)
        d_kwargs = {'dictionary': b''}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

        c_kwargs = {'mode': mode, 'dictionary': ''}
        c_kwargs.update(kwargs)
        d_kwargs = {}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

        c_kwargs = {'mode': mode}
        c_kwargs.update(kwargs)
        d_kwargs = {'dictionary': ''}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data


def test_with_dict():
    kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123" * 24
    dict1 = input_data[10:30]
    dict2 = input_data[20:40]
    message = r"^Decompression failed. error: \d+$"

    for mode in ['default', 'high_compression']:
        c_kwargs = {'mode': mode, 'dictionary': dict1}
        c_kwargs.update(kwargs)
        compressed = compress(input_data, c_kwargs)

        d_kwargs = {}
        d_kwargs.update(kwargs)
        with pytest.raises(lz4.stream.LZ4StreamError, match=message):
            decompress(compressed, d_kwargs)

        d_kwargs = {'dictionary': dict1[:2]}
        d_kwargs.update(kwargs)
        with pytest.raises(lz4.stream.LZ4StreamError, match=message):
            decompress(compressed, d_kwargs)

        d_kwargs = {'dictionary': dict2}
        d_kwargs.update(kwargs)
        assert decompress(compressed, d_kwargs) != input_data

        d_kwargs = {'dictionary': dict1}
        d_kwargs.update(kwargs)
        assert decompress(compressed, d_kwargs) == input_data

    c_kwargs = {}
    c_kwargs.update(kwargs)
    d_kwargs = {'dictionary': dict1}
    d_kwargs.update(kwargs)
    assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data


def test_known_decompress_1():
    d_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    output = b''

    input = b'\x00\x00\x00\x00'
    message = "^Decompression failed. error: 1$"
    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(input, d_kwargs)

    input = b'\x01\x00\x00\x00\x00'
    assert decompress(input, d_kwargs) == output


def test_known_decompress_2():
    d_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    input = b'\x02\x00\x00\x00\x10 '
    output = b' '
    assert decompress(input, d_kwargs) == output


def test_known_decompress_3():
    d_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    # uncompressed data size smaller than buffer_size
    input = b'%\x00\x00\x00\xff\x0bLorem ipsum dolor sit amet\x1a\x006P amet'
    output = b'Lorem ipsum dolor sit amet' * 4
    assert decompress(input, d_kwargs) == output


def test_known_decompress_4():
    d_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    input = b'%\x00\x00\x00\xff\x0bLorem ipsum dolor sit amet\x1a\x00NPit am\n\x00\x00\x00\x0fh\x00hP sit \x05\x00\x00\x00@amet'
    output = b'Lorem ipsum dolor sit amet' * 10
    assert decompress(input, d_kwargs) == output