Debian Codegraph @

tests/block/test_block_0.py

raw symbols SCIP
1 import lz4.block
2 from multiprocessing.pool import ThreadPool
3 import sys
4 import copy
5 import pytest
6 from functools import partial
7 if sys.version_info <= (3, 2):
8 import struct
9
10
11 def get_stored_size(buff):
12 if sys.version_info > (2, 7):
13 if isinstance(buff, memoryview):
14 b = buff.tobytes()
15 else:
16 b = bytes(buff)
17 else:
18 b = bytes(buff)
19
20 if len(b) < 4:
21 return None
22
23 if sys.version_info > (3, 2):
24 return int.from_bytes(b[:4], 'little')
25 else:
26 # This would not work on a memoryview object, hence buff.tobytes call
27 # above
28 return struct.unpack('<I', b[:4])[0]
29
30
31 def roundtrip(x, c_kwargs, d_kwargs, dictionary):
32 if dictionary:
33 if isinstance(dictionary, tuple):
34 d = x[dictionary[0]:dictionary[1]]
35 else:
36 d = dictionary
37 c_kwargs['dict'] = d
38 d_kwargs['dict'] = d
39
40 c = lz4.block.compress(x, **c_kwargs)
41
42 if c_kwargs['store_size']:
43 assert get_stored_size(c) == len(x)
44 else:
45 d_kwargs['uncompressed_size'] = len(x)
46
47 return lz4.block.decompress(c, **d_kwargs)
48
49
50 def setup_kwargs(mode, store_size, c_return_bytearray=None, d_return_bytearray=None):
51 c_kwargs = {}
52
53 if mode[0] is not None:
54 c_kwargs['mode'] = mode[0]
55 if mode[1] is not None:
56 c_kwargs.update(mode[1])
57
58 c_kwargs.update(store_size)
59
60 if c_return_bytearray:
61 c_kwargs.update(c_return_bytearray)
62
63 d_kwargs = {}
64
65 if d_return_bytearray:
66 d_kwargs.update(d_return_bytearray)
67
68 return (c_kwargs, d_kwargs)
69
70
71 # Test single threaded usage with all valid variations of input
72 def test_1(data, mode, store_size, c_return_bytearray, d_return_bytearray, dictionary):
73 if isinstance(data, memoryview):
74 data = memoryview(copy.deepcopy(data.obj))
75 elif isinstance(data, bytearray):
76 data_x = bytearray()
77 data_x[:] = data
78 data = data_x
79
80 (c_kwargs, d_kwargs) = setup_kwargs(
81 mode, store_size, c_return_bytearray, d_return_bytearray)
82
83 d = roundtrip(data, c_kwargs, d_kwargs, dictionary)
84
85 assert d == data
86 if d_return_bytearray['return_bytearray']:
87 assert isinstance(d, bytearray)
88
89
90 # Test multi threaded usage with all valid variations of input
91 @pytest.mark.thread_unsafe
92 def test_2(data, mode, store_size, dictionary):
93 (c_kwargs, d_kwargs) = setup_kwargs(mode, store_size)
94
95 def copy_buf(data):
96 if isinstance(data, memoryview):
97 data_x = memoryview(copy.deepcopy(data.obj))
98 elif isinstance(data, bytearray):
99 data_x = bytearray()
100 data_x[:] = data
101 else:
102 data_x = data
103 return data_x
104
105 data_in = [copy_buf(data) for i in range(32)]
106
107 pool = ThreadPool(2)
108 rt = partial(roundtrip, c_kwargs=c_kwargs,
109 d_kwargs=d_kwargs, dictionary=dictionary)
110 data_out = pool.map(rt, data_in)
111 pool.close()
112 assert data_in == data_out