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
|
import gc
import os
from ._version import LooseVersion
import ctypes
import blosc
import unittest
try:
import numpy
except ImportError:
has_numpy = False
else:
has_numpy = True
try:
import psutil
except ImportError:
psutil = None
class TestCodec(unittest.TestCase):
def setUp(self):
self.PY_27_INPUT = b'\x02\x01\x03\x02\x85\x00\x00\x00\x84\x00\x00\x00\x95\x00\x00\x00\x80\x02cnumpy.core.multiarray\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x05\x85cnumpy\ndtype\nq\x04U\x02S2K\x00K\x01\x87Rq\x05(K\x03U\x01|NNNK\x02K\x01K\x00tb\x89U\n\xc3\xa5\xc3\xa7\xc3\xb8\xcf\x80\xcb\x9atb.'
def test_basic_codec(self):
s = b'0123456789'
c = blosc.compress(s, typesize=1)
d = blosc.decompress(c)
self.assertEqual(s, d)
def test_get_clib(self):
s = b'0123456789'
for cname in blosc.compressor_list():
c = blosc.compress(s, typesize=1, cname=cname)
clib = blosc.get_clib(c)
self.assertEqual(clib, blosc.cname2clib[cname])
def test_all_compressors(self):
s = b'0123456789'*100
for cname in blosc.compressor_list():
c = blosc.compress(s, typesize=1, cname=cname)
d = blosc.decompress(c)
self.assertEqual(s, d)
def test_all_filters(self):
s = b'0123456789'*100
filters = [blosc.NOSHUFFLE, blosc.SHUFFLE]
# BITFILTER only works properly from 1.8.0 on
if LooseVersion(blosc.blosclib_version) >= LooseVersion("1.8.0"):
filters.append(blosc.BITSHUFFLE)
for filter_ in filters:
c = blosc.compress(s, typesize=1, shuffle=filter_)
d = blosc.decompress(c)
self.assertEqual(s, d)
def test_set_nthreads_exceptions(self):
self.assertRaises(ValueError, blosc.set_nthreads,
blosc.MAX_THREADS + 1)
def test_compress_input_types(self):
import numpy as np
# assume the expected answer was compressed from bytes
expected = blosc.compress(b'0123456789', typesize=1)
# now for all the things that support the buffer interface
self.assertEqual(expected,
blosc.compress(memoryview(b'0123456789'),
typesize=1))
self.assertEqual(expected, blosc.compress(
bytearray(b'0123456789'), typesize=1))
self.assertEqual(expected, blosc.compress(
np.array([b'0123456789']), typesize=1))
def test_decompress_input_types(self):
import numpy as np
# assume the expected answer was compressed from bytes
expected = b'0123456789'
compressed = blosc.compress(expected, typesize=1)
# now for all the things that support the buffer interface
self.assertEqual(expected, blosc.decompress(compressed))
self.assertEqual(expected, blosc.decompress(memoryview(compressed)))
self.assertEqual(expected, blosc.decompress(bytearray(compressed)))
self.assertEqual(expected, blosc.decompress(np.array([compressed])))
def test_decompress_ptr_input_types(self):
import numpy as np
# assume the expected answer was compressed from bytes
expected = b'0123456789'
out = np.zeros(len(expected), dtype=np.byte)
compressed = blosc.compress(expected, typesize=1)
# now for all the things that support the buffer interface
out[:] = 0 # reset the output array
nout = blosc.decompress_ptr(compressed, out.ctypes.data)
self.assertEqual(expected, out.tobytes())
self.assertEqual(len(expected), nout) # check that we didn't write too many bytes
out[:] = 0
nout = blosc.decompress_ptr(memoryview(compressed), out.ctypes.data)
self.assertEqual(expected, out.tobytes())
self.assertEqual(len(expected), nout)
out[:] = 0
nout = blosc.decompress_ptr(bytearray(compressed), out.ctypes.data)
self.assertEqual(expected, out.tobytes())
self.assertEqual(len(expected), nout)
out[:] = 0
nout = blosc.decompress_ptr(np.frombuffer(compressed, dtype=np.byte), out.ctypes.data)
self.assertEqual(expected, out.tobytes())
self.assertEqual(len(expected), nout)
def test_decompress_releasegil(self):
import numpy as np
# assume the expected answer was compressed from bytes
blosc.set_releasegil(True)
expected = b'0123456789'
compressed = blosc.compress(expected, typesize=1)
# now for all the things that support the buffer interface
self.assertEqual(expected, blosc.decompress(compressed))
self.assertEqual(expected, blosc.decompress(memoryview(compressed)))
self.assertEqual(expected, blosc.decompress(bytearray(compressed)))
self.assertEqual(expected, blosc.decompress(np.array([compressed])))
blosc.set_releasegil(False)
def test_decompress_input_types_as_bytearray(self):
import numpy as np
# assume the expected answer was compressed from bytes
expected = bytearray(b'0123456789')
compressed = blosc.compress(expected, typesize=1)
# now for all the things that support the buffer interface
self.assertEqual(expected, blosc.decompress(compressed,
as_bytearray=True))
self.assertEqual(expected,
blosc.decompress(memoryview(compressed),
as_bytearray=True))
self.assertEqual(expected, blosc.decompress(bytearray(compressed),
as_bytearray=True))
self.assertEqual(expected, blosc.decompress(np.array([compressed]),
as_bytearray=True))
def test_compress_exceptions(self):
s = b'0123456789'
self.assertRaises(ValueError, blosc.compress, s, typesize=0)
self.assertRaises(ValueError, blosc.compress, s,
typesize=blosc.MAX_TYPESIZE+1)
self.assertRaises(ValueError, blosc.compress, s, typesize=1, clevel=-1)
self.assertRaises(ValueError, blosc.compress, s, typesize=1, clevel=10)
self.assertRaises(TypeError, blosc.compress, 1.0, 1)
self.assertRaises(TypeError, blosc.compress, ['abc'], 1)
self.assertRaises(ValueError, blosc.compress, 'abc',
typesize=1, cname='foo')
# Create a simple mock to avoid having to create a buffer of 2 GB
class LenMock:
def __len__(self):
return blosc.MAX_BUFFERSIZE+1
self.assertRaises(ValueError, blosc.compress, LenMock(), typesize=1)
def test_compress_ptr_exceptions(self):
# Make sure we do have a valid address, to reduce the chance of a
# segfault if we do actually start compressing because the exceptions
# aren't raised.
typesize, items = 8, 8
data = [float(i) for i in range(items)]
Array = ctypes.c_double * items
array = Array(*data)
address = ctypes.addressof(array)
self.assertRaises(ValueError, blosc.compress_ptr, address, items,
typesize=-1)
self.assertRaises(ValueError, blosc.compress_ptr, address, items,
typesize=blosc.MAX_TYPESIZE+1)
self.assertRaises(ValueError, blosc.compress_ptr, address, items,
typesize=typesize, clevel=-1)
self.assertRaises(ValueError, blosc.compress_ptr, address, items,
typesize=typesize, clevel=10)
self.assertRaises(TypeError, blosc.compress_ptr, 1.0, items,
typesize=typesize)
self.assertRaises(TypeError, blosc.compress_ptr, ['abc'], items,
typesize=typesize)
self.assertRaises(ValueError, blosc.compress_ptr, address, -1,
typesize=typesize)
self.assertRaises(ValueError, blosc.compress_ptr, address,
blosc.MAX_BUFFERSIZE+1, typesize=typesize)
def test_decompress_exceptions(self):
self.assertRaises(TypeError, blosc.decompress, 1.0)
self.assertRaises(TypeError, blosc.decompress, ['abc'])
def test_decompress_ptr_exceptions(self):
# make sure we do have a valid address
typesize, items = 8, 8
data = [float(i) for i in range(items)]
Array = ctypes.c_double * items
in_array = Array(*data)
c = blosc.compress_ptr(ctypes.addressof(in_array), items, typesize)
out_array = ctypes.create_string_buffer(items*typesize)
self.assertRaises(TypeError, blosc.decompress_ptr, 1.0,
ctypes.addressof(out_array))
self.assertRaises(TypeError, blosc.decompress_ptr, ['abc'],
ctypes.addressof(out_array))
self.assertRaises(TypeError, blosc.decompress_ptr, c, 1.0)
self.assertRaises(TypeError, blosc.decompress_ptr, c, ['abc'])
@unittest.skipIf(not has_numpy, "Numpy not available")
def test_pack_array_exceptions(self):
self.assertRaises(TypeError, blosc.pack_array, 'abc')
self.assertRaises(TypeError, blosc.pack_array, 1.0)
items = (blosc.MAX_BUFFERSIZE // 8) + 1
one = numpy.ones(1, dtype=numpy.int64)
self.assertRaises(ValueError, blosc.pack_array, one, clevel=-1)
self.assertRaises(ValueError, blosc.pack_array, one, clevel=10)
# use stride trick to make an array that looks like a huge one
ones = numpy.lib.stride_tricks.as_strided(one, shape=(1, items),
strides=(8, 0))[0]
# This should always raise an error
self.assertRaises(ValueError, blosc.pack_array, ones)
def test_unpack_array_with_unicode_characters(self):
import numpy as np
input_array = np.array(['å', 'ç', 'ø', 'π', '˚'])
packed_array = blosc.pack_array(input_array)
np.testing.assert_array_equal(input_array, blosc.unpack_array(packed_array, encoding='UTF-8'))
def test_unpack_array_with_from_py27_exceptions(self):
self.assertRaises(UnicodeDecodeError, blosc.unpack_array, self.PY_27_INPUT)
def test_unpack_array_with_unicode_characters_from_py27(self):
import numpy as np
out_array = np.array(['å', 'ç', 'ø', 'π', '˚'])
np.testing.assert_array_equal(out_array, blosc.unpack_array(self.PY_27_INPUT, encoding='bytes'))
def test_unpack_array_exceptions(self):
self.assertRaises(TypeError, blosc.unpack_array, 1.0)
@unittest.skipIf(not psutil, "psutil not available, cannot test for leaks")
def test_no_leaks(self):
num_elements = 10000000
typesize = 8
data = [float(i) for i in range(num_elements)] # ~76MB
Array = ctypes.c_double * num_elements
array = Array(*data)
address = ctypes.addressof(array)
def leaks(operation, repeats=3):
gc.collect()
used_mem_before = psutil.Process(os.getpid()).memory_info()[0]
for _ in range(repeats):
operation()
gc.collect()
used_mem_after = psutil.Process(os.getpid()).memory_info()[0]
# We multiply by an additional factor of .01 to account for
# storage overhead of Python classes
return (used_mem_after - used_mem_before) >= num_elements * 8.01
def compress():
blosc.compress(array, typesize, clevel=1)
def compress_ptr():
blosc.compress_ptr(address, num_elements, typesize, clevel=0)
def decompress():
cx = blosc.compress(array, typesize, clevel=1)
blosc.decompress(cx)
def decompress_ptr():
cx = blosc.compress_ptr(address, num_elements, typesize, clevel=0)
blosc.decompress_ptr(cx, address)
self.assertFalse(leaks(compress), msg='compress leaks memory')
self.assertFalse(leaks(compress_ptr), msg='compress_ptr leaks memory')
self.assertFalse(leaks(decompress), msg='decompress leaks memory')
self.assertFalse(leaks(decompress_ptr), msg='decompress_ptr leaks memory')
def test_get_blocksize(self):
s = b'0123456789' * 1000
blosc.set_blocksize(2**14)
blosc.compress(s, typesize=1)
d = blosc.get_blocksize()
self.assertEqual(d, 2**14)
def test_get_cbuffer_sizes(self):
s = b'0123456789' * 100000
blosc.set_blocksize(2**16)
c = blosc.compress(s, typesize=1)
t = blosc.get_cbuffer_sizes(c)
self.assertEqual(t[0], 1000000)
# One cannot be sure of the exact compressed bytes, so round to KB
self.assertEqual(t[1] // 2**10, 4354 // 2**10)
self.assertEqual(t[2], 2**16)
def test_bitshuffle_not_multiple(self):
# Check the fix for #133
x = numpy.ones(27266, dtype='uint8')
xx = x.tobytes()
zxx = blosc.compress(xx, typesize=8, shuffle=blosc.BITSHUFFLE)
last_xx = blosc.decompress(zxx)[-3:]
self.assertEqual(last_xx, b'\x01\x01\x01')
def test_cbuffer_validate(self):
import numpy as np
expected = b'0123456789' * 1000
compressed = blosc.compress(expected)
# now for all the things that support the buffer interface
self.assertTrue(blosc.cbuffer_validate(compressed))
self.assertTrue(blosc.cbuffer_validate(memoryview(compressed)))
self.assertTrue(blosc.cbuffer_validate(bytearray(compressed)))
self.assertTrue(blosc.cbuffer_validate(np.array([compressed])))
def test_cbuffer_validate_failures(self):
import numpy as np
compressed = b'this_is_total_garbage'
# now for all the things that support the buffer interface
self.assertFalse(blosc.cbuffer_validate(compressed))
self.assertFalse(blosc.cbuffer_validate(memoryview(compressed)))
self.assertFalse(blosc.cbuffer_validate(bytearray(compressed)))
self.assertFalse(blosc.cbuffer_validate(np.array([compressed])))
def test_bithuffle_leftovers(self):
# Test for https://github.com/Blosc/c-blosc2/pull/100
import numpy as np
buffer = b" " * 641091 # a buffer that is not divisible by 8
cbuffer = blosc.compress(buffer, typesize=8, shuffle=blosc.BITSHUFFLE, clevel=1)
dbuffer = blosc.decompress(cbuffer)
self.assertTrue(buffer == dbuffer)
def run(verbosity=2):
import blosc
import blosc.toplevel
blosc.print_versions()
suite = unittest.TestLoader().loadTestsFromTestCase(TestCodec)
# If in the future we split this test file in several, the auto-discover
# might be interesting
# suite = unittest.TestLoader().discover(start_dir='.', pattern='test*.py')
suite.addTests(unittest.TestLoader().loadTestsFromModule(blosc.toplevel))
assert unittest.TextTestRunner(verbosity=verbosity).\
run(suite).wasSuccessful()
if __name__ == '__main__':
run()
|