test_numpy_pickle.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. """Test the numpy pickler as a replacement of the standard pickler."""
  2. import bz2
  3. import copy
  4. import gzip
  5. import io
  6. import mmap
  7. import os
  8. import pickle
  9. import random
  10. import re
  11. import socket
  12. import sys
  13. import warnings
  14. import zlib
  15. from contextlib import closing
  16. from pathlib import Path
  17. try:
  18. import lzma
  19. except ImportError:
  20. lzma = None
  21. import pytest
  22. # numpy_pickle is not a drop-in replacement of pickle, as it takes
  23. # filenames instead of open files as arguments.
  24. from joblib import numpy_pickle, register_compressor
  25. from joblib.compressor import (
  26. _COMPRESSORS,
  27. _LZ4_PREFIX,
  28. LZ4_NOT_INSTALLED_ERROR,
  29. BinaryZlibFile,
  30. CompressorWrapper,
  31. )
  32. from joblib.numpy_pickle_utils import (
  33. _IO_BUFFER_SIZE,
  34. _detect_compressor,
  35. _ensure_native_byte_order,
  36. _is_numpy_array_byte_order_mismatch,
  37. )
  38. from joblib.test import data
  39. from joblib.test.common import (
  40. memory_used,
  41. np,
  42. with_lz4,
  43. with_memory_profiler,
  44. with_numpy,
  45. without_lz4,
  46. )
  47. from joblib.testing import parametrize, raises, warns
  48. ###############################################################################
  49. # Define a list of standard types.
  50. # Borrowed from dill, initial author: Micheal McKerns:
  51. # http://dev.danse.us/trac/pathos/browser/dill/dill_test2.py
  52. typelist = []
  53. # testing types
  54. _none = None
  55. typelist.append(_none)
  56. _type = type
  57. typelist.append(_type)
  58. _bool = bool(1)
  59. typelist.append(_bool)
  60. _int = int(1)
  61. typelist.append(_int)
  62. _float = float(1)
  63. typelist.append(_float)
  64. _complex = complex(1)
  65. typelist.append(_complex)
  66. _string = str(1)
  67. typelist.append(_string)
  68. _tuple = ()
  69. typelist.append(_tuple)
  70. _list = []
  71. typelist.append(_list)
  72. _dict = {}
  73. typelist.append(_dict)
  74. _builtin = len
  75. typelist.append(_builtin)
  76. def _function(x):
  77. yield x
  78. class _class:
  79. def _method(self):
  80. pass
  81. class _newclass(object):
  82. def _method(self):
  83. pass
  84. typelist.append(_function)
  85. typelist.append(_class)
  86. typelist.append(_newclass) # <type 'type'>
  87. _instance = _class()
  88. typelist.append(_instance)
  89. _object = _newclass()
  90. typelist.append(_object) # <type 'class'>
  91. ###############################################################################
  92. # Tests
  93. @parametrize("compress", [0, 1])
  94. @parametrize("member", typelist)
  95. def test_standard_types(tmpdir, compress, member):
  96. # Test pickling and saving with standard types.
  97. filename = tmpdir.join("test.pkl").strpath
  98. numpy_pickle.dump(member, filename, compress=compress)
  99. _member = numpy_pickle.load(filename)
  100. # We compare the pickled instance to the reloaded one only if it
  101. # can be compared to a copied one
  102. if member == copy.deepcopy(member):
  103. assert member == _member
  104. def test_value_error():
  105. # Test inverting the input arguments to dump
  106. with raises(ValueError):
  107. numpy_pickle.dump("foo", dict())
  108. @parametrize("wrong_compress", [-1, 10, dict()])
  109. def test_compress_level_error(wrong_compress):
  110. # Verify that passing an invalid compress argument raises an error.
  111. exception_msg = 'Non valid compress level given: "{0}"'.format(wrong_compress)
  112. with raises(ValueError) as excinfo:
  113. numpy_pickle.dump("dummy", "foo", compress=wrong_compress)
  114. excinfo.match(exception_msg)
  115. @with_numpy
  116. @parametrize("compress", [False, True, 0, 3, "zlib"])
  117. def test_numpy_persistence(tmpdir, compress):
  118. filename = tmpdir.join("test.pkl").strpath
  119. rnd = np.random.RandomState(0)
  120. a = rnd.random_sample((10, 2))
  121. # We use 'a.T' to have a non C-contiguous array.
  122. for index, obj in enumerate(((a,), (a.T,), (a, a), [a, a, a])):
  123. filenames = numpy_pickle.dump(obj, filename, compress=compress)
  124. # All is cached in one file
  125. assert len(filenames) == 1
  126. # Check that only one file was created
  127. assert filenames[0] == filename
  128. # Check that this file does exist
  129. assert os.path.exists(filenames[0])
  130. # Unpickle the object
  131. obj_ = numpy_pickle.load(filename)
  132. # Check that the items are indeed arrays
  133. for item in obj_:
  134. assert isinstance(item, np.ndarray)
  135. # And finally, check that all the values are equal.
  136. np.testing.assert_array_equal(np.array(obj), np.array(obj_))
  137. # Now test with an array subclass
  138. obj = np.memmap(filename + "mmap", mode="w+", shape=4, dtype=np.float64)
  139. filenames = numpy_pickle.dump(obj, filename, compress=compress)
  140. # All is cached in one file
  141. assert len(filenames) == 1
  142. obj_ = numpy_pickle.load(filename)
  143. if type(obj) is not np.memmap and hasattr(obj, "__array_prepare__"):
  144. # We don't reconstruct memmaps
  145. assert isinstance(obj_, type(obj))
  146. np.testing.assert_array_equal(obj_, obj)
  147. # Test with an object containing multiple numpy arrays
  148. obj = ComplexTestObject()
  149. filenames = numpy_pickle.dump(obj, filename, compress=compress)
  150. # All is cached in one file
  151. assert len(filenames) == 1
  152. obj_loaded = numpy_pickle.load(filename)
  153. assert isinstance(obj_loaded, type(obj))
  154. np.testing.assert_array_equal(obj_loaded.array_float, obj.array_float)
  155. np.testing.assert_array_equal(obj_loaded.array_int, obj.array_int)
  156. np.testing.assert_array_equal(obj_loaded.array_obj, obj.array_obj)
  157. @with_numpy
  158. def test_numpy_persistence_bufferred_array_compression(tmpdir):
  159. big_array = np.ones((_IO_BUFFER_SIZE + 100), dtype=np.uint8)
  160. filename = tmpdir.join("test.pkl").strpath
  161. numpy_pickle.dump(big_array, filename, compress=True)
  162. arr_reloaded = numpy_pickle.load(filename)
  163. np.testing.assert_array_equal(big_array, arr_reloaded)
  164. @with_numpy
  165. def test_memmap_persistence(tmpdir):
  166. rnd = np.random.RandomState(0)
  167. a = rnd.random_sample(10)
  168. filename = tmpdir.join("test1.pkl").strpath
  169. numpy_pickle.dump(a, filename)
  170. b = numpy_pickle.load(filename, mmap_mode="r")
  171. assert isinstance(b, np.memmap)
  172. # Test with an object containing multiple numpy arrays
  173. filename = tmpdir.join("test2.pkl").strpath
  174. obj = ComplexTestObject()
  175. numpy_pickle.dump(obj, filename)
  176. obj_loaded = numpy_pickle.load(filename, mmap_mode="r")
  177. assert isinstance(obj_loaded, type(obj))
  178. assert isinstance(obj_loaded.array_float, np.memmap)
  179. assert not obj_loaded.array_float.flags.writeable
  180. assert isinstance(obj_loaded.array_int, np.memmap)
  181. assert not obj_loaded.array_int.flags.writeable
  182. # Memory map not allowed for numpy object arrays
  183. assert not isinstance(obj_loaded.array_obj, np.memmap)
  184. np.testing.assert_array_equal(obj_loaded.array_float, obj.array_float)
  185. np.testing.assert_array_equal(obj_loaded.array_int, obj.array_int)
  186. np.testing.assert_array_equal(obj_loaded.array_obj, obj.array_obj)
  187. # Test we can write in memmapped arrays
  188. obj_loaded = numpy_pickle.load(filename, mmap_mode="r+")
  189. assert obj_loaded.array_float.flags.writeable
  190. obj_loaded.array_float[0:10] = 10.0
  191. assert obj_loaded.array_int.flags.writeable
  192. obj_loaded.array_int[0:10] = 10
  193. obj_reloaded = numpy_pickle.load(filename, mmap_mode="r")
  194. np.testing.assert_array_equal(obj_reloaded.array_float, obj_loaded.array_float)
  195. np.testing.assert_array_equal(obj_reloaded.array_int, obj_loaded.array_int)
  196. # Test w+ mode is caught and the mode has switched to r+
  197. numpy_pickle.load(filename, mmap_mode="w+")
  198. assert obj_loaded.array_int.flags.writeable
  199. assert obj_loaded.array_int.mode == "r+"
  200. assert obj_loaded.array_float.flags.writeable
  201. assert obj_loaded.array_float.mode == "r+"
  202. @with_numpy
  203. def test_memmap_persistence_mixed_dtypes(tmpdir):
  204. # loading datastructures that have sub-arrays with dtype=object
  205. # should not prevent memmapping on fixed size dtype sub-arrays.
  206. rnd = np.random.RandomState(0)
  207. a = rnd.random_sample(10)
  208. b = np.array([1, "b"], dtype=object)
  209. construct = (a, b)
  210. filename = tmpdir.join("test.pkl").strpath
  211. numpy_pickle.dump(construct, filename)
  212. a_clone, b_clone = numpy_pickle.load(filename, mmap_mode="r")
  213. # the floating point array has been memory mapped
  214. assert isinstance(a_clone, np.memmap)
  215. # the object-dtype array has been loaded in memory
  216. assert not isinstance(b_clone, np.memmap)
  217. @with_numpy
  218. def test_masked_array_persistence(tmpdir):
  219. # The special-case picker fails, because saving masked_array
  220. # not implemented, but it just delegates to the standard pickler.
  221. rnd = np.random.RandomState(0)
  222. a = rnd.random_sample(10)
  223. a = np.ma.masked_greater(a, 0.5)
  224. filename = tmpdir.join("test.pkl").strpath
  225. numpy_pickle.dump(a, filename)
  226. b = numpy_pickle.load(filename, mmap_mode="r")
  227. assert isinstance(b, np.ma.masked_array)
  228. @with_numpy
  229. def test_compress_mmap_mode_warning(tmpdir):
  230. # Test the warning in case of compress + mmap_mode
  231. rnd = np.random.RandomState(0)
  232. obj = rnd.random_sample(10)
  233. this_filename = tmpdir.join("test.pkl").strpath
  234. numpy_pickle.dump(obj, this_filename, compress=1)
  235. with warns(UserWarning) as warninfo:
  236. reloaded_obj = numpy_pickle.load(this_filename, mmap_mode="r+")
  237. debug_msg = "\n".join([str(w) for w in warninfo])
  238. warninfo = [w.message for w in warninfo]
  239. assert not isinstance(reloaded_obj, np.memmap)
  240. np.testing.assert_array_equal(obj, reloaded_obj)
  241. assert len(warninfo) == 1, debug_msg
  242. assert (
  243. str(warninfo[0]) == 'mmap_mode "r+" is not compatible with compressed '
  244. f'file {this_filename}. "r+" flag will be ignored.'
  245. )
  246. @with_numpy
  247. @with_memory_profiler
  248. @parametrize("compress", [True, False])
  249. def test_memory_usage(tmpdir, compress):
  250. # Verify memory stays within expected bounds.
  251. filename = tmpdir.join("test.pkl").strpath
  252. small_array = np.ones((10, 10))
  253. big_array = np.ones(shape=100 * int(1e6), dtype=np.uint8)
  254. for obj in (small_array, big_array):
  255. size = obj.nbytes / 1e6
  256. obj_filename = filename + str(np.random.randint(0, 1000))
  257. mem_used = memory_used(numpy_pickle.dump, obj, obj_filename, compress=compress)
  258. # The memory used to dump the object shouldn't exceed the buffer
  259. # size used to write array chunks (16MB).
  260. write_buf_size = _IO_BUFFER_SIZE + 16 * 1024**2 / 1e6
  261. assert mem_used <= write_buf_size
  262. mem_used = memory_used(numpy_pickle.load, obj_filename)
  263. # memory used should be less than array size + buffer size used to
  264. # read the array chunk by chunk.
  265. read_buf_size = 32 + _IO_BUFFER_SIZE # MiB
  266. assert mem_used < size + read_buf_size
  267. @with_numpy
  268. def test_compressed_pickle_dump_and_load(tmpdir):
  269. expected_list = [
  270. np.arange(5, dtype=np.dtype("<i8")),
  271. np.arange(5, dtype=np.dtype(">i8")),
  272. np.arange(5, dtype=np.dtype("<f8")),
  273. np.arange(5, dtype=np.dtype(">f8")),
  274. np.array([1, "abc", {"a": 1, "b": 2}], dtype="O"),
  275. np.arange(256, dtype=np.uint8).tobytes(),
  276. "C'est l'\xe9t\xe9 !",
  277. ]
  278. fname = tmpdir.join("temp.pkl.gz").strpath
  279. dumped_filenames = numpy_pickle.dump(expected_list, fname, compress=1)
  280. assert len(dumped_filenames) == 1
  281. result_list = numpy_pickle.load(fname)
  282. for result, expected in zip(result_list, expected_list):
  283. if isinstance(expected, np.ndarray):
  284. expected = _ensure_native_byte_order(expected)
  285. assert result.dtype == expected.dtype
  286. np.testing.assert_equal(result, expected)
  287. else:
  288. assert result == expected
  289. @with_numpy
  290. def test_memmap_load(tmpdir):
  291. little_endian_dtype = np.dtype("<i8")
  292. big_endian_dtype = np.dtype(">i8")
  293. all_dtypes = (little_endian_dtype, big_endian_dtype)
  294. le_array = np.arange(5, dtype=little_endian_dtype)
  295. be_array = np.arange(5, dtype=big_endian_dtype)
  296. fname = tmpdir.join("temp.pkl").strpath
  297. numpy_pickle.dump([le_array, be_array], fname)
  298. le_array_native_load, be_array_native_load = numpy_pickle.load(
  299. fname, ensure_native_byte_order=True
  300. )
  301. assert le_array_native_load.dtype == be_array_native_load.dtype
  302. assert le_array_native_load.dtype in all_dtypes
  303. le_array_nonnative_load, be_array_nonnative_load = numpy_pickle.load(
  304. fname, ensure_native_byte_order=False
  305. )
  306. assert le_array_nonnative_load.dtype == le_array.dtype
  307. assert be_array_nonnative_load.dtype == be_array.dtype
  308. def test_invalid_parameters_raise():
  309. expected_msg = (
  310. "Native byte ordering can only be enforced if 'mmap_mode' parameter "
  311. "is set to None, but got 'mmap_mode=r+' instead."
  312. )
  313. with raises(ValueError, match=re.escape(expected_msg)):
  314. numpy_pickle.load(
  315. "/path/to/some/dump.pkl", ensure_native_byte_order=True, mmap_mode="r+"
  316. )
  317. def _check_pickle(filename, expected_list, mmap_mode=None):
  318. """Helper function to test joblib pickle content.
  319. Note: currently only pickles containing an iterable are supported
  320. by this function.
  321. """
  322. version_match = re.match(r".+py(\d)(\d).+", filename)
  323. py_version_used_for_writing = int(version_match.group(1))
  324. py_version_to_default_pickle_protocol = {2: 2, 3: 3}
  325. pickle_reading_protocol = py_version_to_default_pickle_protocol.get(3, 4)
  326. pickle_writing_protocol = py_version_to_default_pickle_protocol.get(
  327. py_version_used_for_writing, 4
  328. )
  329. if pickle_reading_protocol >= pickle_writing_protocol:
  330. try:
  331. with warnings.catch_warnings(record=True) as warninfo:
  332. warnings.simplefilter("always")
  333. result_list = numpy_pickle.load(filename, mmap_mode=mmap_mode)
  334. filename_base = os.path.basename(filename)
  335. expected_nb_deprecation_warnings = (
  336. 1 if ("_0.9" in filename_base or "_0.8.4" in filename_base) else 0
  337. )
  338. expected_nb_user_warnings = (
  339. 3
  340. if (re.search("_0.1.+.pkl$", filename_base) and mmap_mode is not None)
  341. else 0
  342. )
  343. expected_nb_warnings = (
  344. expected_nb_deprecation_warnings + expected_nb_user_warnings
  345. )
  346. assert len(warninfo) == expected_nb_warnings, (
  347. "Did not get the expected number of warnings. Expected "
  348. f"{expected_nb_warnings} but got warnings: "
  349. f"{[w.message for w in warninfo]}"
  350. )
  351. deprecation_warnings = [
  352. w for w in warninfo if issubclass(w.category, DeprecationWarning)
  353. ]
  354. user_warnings = [w for w in warninfo if issubclass(w.category, UserWarning)]
  355. for w in deprecation_warnings:
  356. assert (
  357. str(w.message)
  358. == "The file '{0}' has been generated with a joblib "
  359. "version less than 0.10. Please regenerate this "
  360. "pickle file.".format(filename)
  361. )
  362. for w in user_warnings:
  363. escaped_filename = re.escape(filename)
  364. assert re.search(
  365. f"memmapped.+{escaped_filename}.+segmentation fault", str(w.message)
  366. )
  367. for result, expected in zip(result_list, expected_list):
  368. if isinstance(expected, np.ndarray):
  369. expected = _ensure_native_byte_order(expected)
  370. assert result.dtype == expected.dtype
  371. np.testing.assert_equal(result, expected)
  372. else:
  373. assert result == expected
  374. except Exception as exc:
  375. # When trying to read with python 3 a pickle generated
  376. # with python 2 we expect a user-friendly error
  377. if py_version_used_for_writing == 2:
  378. assert isinstance(exc, ValueError)
  379. message = (
  380. "You may be trying to read with "
  381. "python 3 a joblib pickle generated with python 2."
  382. )
  383. assert message in str(exc)
  384. elif filename.endswith(".lz4") and with_lz4.args[0]:
  385. assert isinstance(exc, ValueError)
  386. assert LZ4_NOT_INSTALLED_ERROR in str(exc)
  387. else:
  388. raise
  389. else:
  390. # Pickle protocol used for writing is too high. We expect a
  391. # "unsupported pickle protocol" error message
  392. try:
  393. numpy_pickle.load(filename)
  394. raise AssertionError(
  395. "Numpy pickle loading should have raised a ValueError exception"
  396. )
  397. except ValueError as e:
  398. message = "unsupported pickle protocol: {0}".format(pickle_writing_protocol)
  399. assert message in str(e.args)
  400. @with_numpy
  401. def test_joblib_pickle_across_python_versions():
  402. # We need to be specific about dtypes in particular endianness
  403. # because the pickles can be generated on one architecture and
  404. # the tests run on another one. See
  405. # https://github.com/joblib/joblib/issues/279.
  406. expected_list = [
  407. np.arange(5, dtype=np.dtype("<i8")),
  408. np.arange(5, dtype=np.dtype("<f8")),
  409. np.array([1, "abc", {"a": 1, "b": 2}], dtype="O"),
  410. np.arange(256, dtype=np.uint8).tobytes(),
  411. # np.matrix is a subclass of np.ndarray, here we want
  412. # to verify this type of object is correctly unpickled
  413. # among versions.
  414. np.matrix([0, 1, 2], dtype=np.dtype("<i8")),
  415. "C'est l'\xe9t\xe9 !",
  416. ]
  417. # Testing all the compressed and non compressed
  418. # pickles in joblib/test/data. These pickles were generated by
  419. # the joblib/test/data/create_numpy_pickle.py script for the
  420. # relevant python, joblib and numpy versions.
  421. test_data_dir = os.path.dirname(os.path.abspath(data.__file__))
  422. pickle_extensions = (".pkl", ".gz", ".gzip", ".bz2", "lz4")
  423. if lzma is not None:
  424. pickle_extensions += (".xz", ".lzma")
  425. pickle_filenames = [
  426. os.path.join(test_data_dir, fn)
  427. for fn in os.listdir(test_data_dir)
  428. if any(fn.endswith(ext) for ext in pickle_extensions)
  429. ]
  430. for fname in pickle_filenames:
  431. _check_pickle(fname, expected_list)
  432. @with_numpy
  433. def test_joblib_pickle_across_python_versions_with_mmap():
  434. expected_list = [
  435. np.arange(5, dtype=np.dtype("<i8")),
  436. np.arange(5, dtype=np.dtype("<f8")),
  437. np.array([1, "abc", {"a": 1, "b": 2}], dtype="O"),
  438. np.arange(256, dtype=np.uint8).tobytes(),
  439. # np.matrix is a subclass of np.ndarray, here we want
  440. # to verify this type of object is correctly unpickled
  441. # among versions.
  442. np.matrix([0, 1, 2], dtype=np.dtype("<i8")),
  443. "C'est l'\xe9t\xe9 !",
  444. ]
  445. test_data_dir = os.path.dirname(os.path.abspath(data.__file__))
  446. pickle_filenames = [
  447. os.path.join(test_data_dir, fn)
  448. for fn in os.listdir(test_data_dir)
  449. if fn.endswith(".pkl")
  450. ]
  451. for fname in pickle_filenames:
  452. _check_pickle(fname, expected_list, mmap_mode="r")
  453. @with_numpy
  454. def test_numpy_array_byte_order_mismatch_detection():
  455. # List of numpy arrays with big endian byteorder.
  456. be_arrays = [
  457. np.array([(1, 2.0), (3, 4.0)], dtype=[("", ">i8"), ("", ">f8")]),
  458. np.arange(3, dtype=np.dtype(">i8")),
  459. np.arange(3, dtype=np.dtype(">f8")),
  460. ]
  461. # Verify the byteorder mismatch is correctly detected.
  462. for array in be_arrays:
  463. if sys.byteorder == "big":
  464. assert not _is_numpy_array_byte_order_mismatch(array)
  465. else:
  466. assert _is_numpy_array_byte_order_mismatch(array)
  467. converted = _ensure_native_byte_order(array)
  468. if converted.dtype.fields:
  469. for f in converted.dtype.fields.values():
  470. f[0].byteorder == "="
  471. else:
  472. assert converted.dtype.byteorder == "="
  473. # List of numpy arrays with little endian byteorder.
  474. le_arrays = [
  475. np.array([(1, 2.0), (3, 4.0)], dtype=[("", "<i8"), ("", "<f8")]),
  476. np.arange(3, dtype=np.dtype("<i8")),
  477. np.arange(3, dtype=np.dtype("<f8")),
  478. ]
  479. # Verify the byteorder mismatch is correctly detected.
  480. for array in le_arrays:
  481. if sys.byteorder == "little":
  482. assert not _is_numpy_array_byte_order_mismatch(array)
  483. else:
  484. assert _is_numpy_array_byte_order_mismatch(array)
  485. converted = _ensure_native_byte_order(array)
  486. if converted.dtype.fields:
  487. for f in converted.dtype.fields.values():
  488. f[0].byteorder == "="
  489. else:
  490. assert converted.dtype.byteorder == "="
  491. @parametrize("compress_tuple", [("zlib", 3), ("gzip", 3)])
  492. def test_compress_tuple_argument(tmpdir, compress_tuple):
  493. # Verify the tuple is correctly taken into account.
  494. filename = tmpdir.join("test.pkl").strpath
  495. numpy_pickle.dump("dummy", filename, compress=compress_tuple)
  496. # Verify the file contains the right magic number
  497. with open(filename, "rb") as f:
  498. assert _detect_compressor(f) == compress_tuple[0]
  499. @parametrize(
  500. "compress_tuple,message",
  501. [
  502. (
  503. ("zlib", 3, "extra"), # wrong compress tuple
  504. "Compress argument tuple should contain exactly 2 elements",
  505. ),
  506. (
  507. ("wrong", 3), # wrong compress method
  508. 'Non valid compression method given: "{}"'.format("wrong"),
  509. ),
  510. (
  511. ("zlib", "wrong"), # wrong compress level
  512. 'Non valid compress level given: "{}"'.format("wrong"),
  513. ),
  514. ],
  515. )
  516. def test_compress_tuple_argument_exception(tmpdir, compress_tuple, message):
  517. filename = tmpdir.join("test.pkl").strpath
  518. # Verify setting a wrong compress tuple raises a ValueError.
  519. with raises(ValueError) as excinfo:
  520. numpy_pickle.dump("dummy", filename, compress=compress_tuple)
  521. excinfo.match(message)
  522. @parametrize("compress_string", ["zlib", "gzip"])
  523. def test_compress_string_argument(tmpdir, compress_string):
  524. # Verify the string is correctly taken into account.
  525. filename = tmpdir.join("test.pkl").strpath
  526. numpy_pickle.dump("dummy", filename, compress=compress_string)
  527. # Verify the file contains the right magic number
  528. with open(filename, "rb") as f:
  529. assert _detect_compressor(f) == compress_string
  530. @with_numpy
  531. @parametrize("compress", [1, 3, 6])
  532. @parametrize("cmethod", _COMPRESSORS)
  533. def test_joblib_compression_formats(tmpdir, compress, cmethod):
  534. filename = tmpdir.join("test.pkl").strpath
  535. objects = (
  536. np.ones(shape=(100, 100), dtype="f8"),
  537. range(10),
  538. {"a": 1, 2: "b"},
  539. [],
  540. (),
  541. {},
  542. 0,
  543. 1.0,
  544. )
  545. if cmethod in ("lzma", "xz") and lzma is None:
  546. pytest.skip("lzma is support not available")
  547. elif cmethod == "lz4" and with_lz4.args[0]:
  548. # Skip the test if lz4 is not installed. We here use the with_lz4
  549. # skipif fixture whose argument is True when lz4 is not installed
  550. pytest.skip("lz4 is not installed.")
  551. dump_filename = filename + "." + cmethod
  552. for obj in objects:
  553. numpy_pickle.dump(obj, dump_filename, compress=(cmethod, compress))
  554. # Verify the file contains the right magic number
  555. with open(dump_filename, "rb") as f:
  556. assert _detect_compressor(f) == cmethod
  557. # Verify the reloaded object is correct
  558. obj_reloaded = numpy_pickle.load(dump_filename)
  559. assert isinstance(obj_reloaded, type(obj))
  560. if isinstance(obj, np.ndarray):
  561. np.testing.assert_array_equal(obj_reloaded, obj)
  562. else:
  563. assert obj_reloaded == obj
  564. def _gzip_file_decompress(source_filename, target_filename):
  565. """Decompress a gzip file."""
  566. with closing(gzip.GzipFile(source_filename, "rb")) as fo:
  567. buf = fo.read()
  568. with open(target_filename, "wb") as fo:
  569. fo.write(buf)
  570. def _zlib_file_decompress(source_filename, target_filename):
  571. """Decompress a zlib file."""
  572. with open(source_filename, "rb") as fo:
  573. buf = zlib.decompress(fo.read())
  574. with open(target_filename, "wb") as fo:
  575. fo.write(buf)
  576. @parametrize(
  577. "extension,decompress",
  578. [(".z", _zlib_file_decompress), (".gz", _gzip_file_decompress)],
  579. )
  580. def test_load_externally_decompressed_files(tmpdir, extension, decompress):
  581. # Test that BinaryZlibFile generates valid gzip and zlib compressed files.
  582. obj = "a string to persist"
  583. filename_raw = tmpdir.join("test.pkl").strpath
  584. filename_compressed = filename_raw + extension
  585. # Use automatic extension detection to compress with the right method.
  586. numpy_pickle.dump(obj, filename_compressed)
  587. # Decompress with the corresponding method
  588. decompress(filename_compressed, filename_raw)
  589. # Test that the uncompressed pickle can be loaded and
  590. # that the result is correct.
  591. obj_reloaded = numpy_pickle.load(filename_raw)
  592. assert obj == obj_reloaded
  593. @parametrize(
  594. "extension,cmethod",
  595. # valid compressor extensions
  596. [
  597. (".z", "zlib"),
  598. (".gz", "gzip"),
  599. (".bz2", "bz2"),
  600. (".lzma", "lzma"),
  601. (".xz", "xz"),
  602. # invalid compressor extensions
  603. (".pkl", "not-compressed"),
  604. ("", "not-compressed"),
  605. ],
  606. )
  607. def test_compression_using_file_extension(tmpdir, extension, cmethod):
  608. if cmethod in ("lzma", "xz") and lzma is None:
  609. pytest.skip("lzma is missing")
  610. # test that compression method corresponds to the given filename extension.
  611. filename = tmpdir.join("test.pkl").strpath
  612. obj = "object to dump"
  613. dump_fname = filename + extension
  614. numpy_pickle.dump(obj, dump_fname)
  615. # Verify the file contains the right magic number
  616. with open(dump_fname, "rb") as f:
  617. assert _detect_compressor(f) == cmethod
  618. # Verify the reloaded object is correct
  619. obj_reloaded = numpy_pickle.load(dump_fname)
  620. assert isinstance(obj_reloaded, type(obj))
  621. assert obj_reloaded == obj
  622. @with_numpy
  623. def test_file_handle_persistence(tmpdir):
  624. objs = [np.random.random((10, 10)), "some data"]
  625. fobjs = [bz2.BZ2File, gzip.GzipFile]
  626. if lzma is not None:
  627. fobjs += [lzma.LZMAFile]
  628. filename = tmpdir.join("test.pkl").strpath
  629. for obj in objs:
  630. for fobj in fobjs:
  631. with fobj(filename, "wb") as f:
  632. numpy_pickle.dump(obj, f)
  633. # using the same decompressor prevents from internally
  634. # decompress again.
  635. with fobj(filename, "rb") as f:
  636. obj_reloaded = numpy_pickle.load(f)
  637. # when needed, the correct decompressor should be used when
  638. # passing a raw file handle.
  639. with open(filename, "rb") as f:
  640. obj_reloaded_2 = numpy_pickle.load(f)
  641. if isinstance(obj, np.ndarray):
  642. np.testing.assert_array_equal(obj_reloaded, obj)
  643. np.testing.assert_array_equal(obj_reloaded_2, obj)
  644. else:
  645. assert obj_reloaded == obj
  646. assert obj_reloaded_2 == obj
  647. @with_numpy
  648. def test_in_memory_persistence():
  649. objs = [np.random.random((10, 10)), "some data"]
  650. for obj in objs:
  651. f = io.BytesIO()
  652. numpy_pickle.dump(obj, f)
  653. obj_reloaded = numpy_pickle.load(f)
  654. if isinstance(obj, np.ndarray):
  655. np.testing.assert_array_equal(obj_reloaded, obj)
  656. else:
  657. assert obj_reloaded == obj
  658. @with_numpy
  659. def test_file_handle_persistence_mmap(tmpdir):
  660. obj = np.random.random((10, 10))
  661. filename = tmpdir.join("test.pkl").strpath
  662. with open(filename, "wb") as f:
  663. numpy_pickle.dump(obj, f)
  664. with open(filename, "rb") as f:
  665. obj_reloaded = numpy_pickle.load(f, mmap_mode="r+")
  666. np.testing.assert_array_equal(obj_reloaded, obj)
  667. @with_numpy
  668. def test_file_handle_persistence_compressed_mmap(tmpdir):
  669. obj = np.random.random((10, 10))
  670. filename = tmpdir.join("test.pkl").strpath
  671. with open(filename, "wb") as f:
  672. numpy_pickle.dump(obj, f, compress=("gzip", 3))
  673. with closing(gzip.GzipFile(filename, "rb")) as f:
  674. with warns(UserWarning) as warninfo:
  675. numpy_pickle.load(f, mmap_mode="r+")
  676. assert len(warninfo) == 1
  677. assert (
  678. str(warninfo[0].message)
  679. == '"%(fileobj)r" is not a raw file, mmap_mode "%(mmap_mode)s" '
  680. "flag will be ignored." % {"fileobj": f, "mmap_mode": "r+"}
  681. )
  682. @with_numpy
  683. def test_file_handle_persistence_in_memory_mmap():
  684. obj = np.random.random((10, 10))
  685. buf = io.BytesIO()
  686. numpy_pickle.dump(obj, buf)
  687. with warns(UserWarning) as warninfo:
  688. numpy_pickle.load(buf, mmap_mode="r+")
  689. assert len(warninfo) == 1
  690. assert (
  691. str(warninfo[0].message)
  692. == "In memory persistence is not compatible with mmap_mode "
  693. '"%(mmap_mode)s" flag passed. mmap_mode option will be '
  694. "ignored." % {"mmap_mode": "r+"}
  695. )
  696. @parametrize(
  697. "data",
  698. [
  699. b"a little data as bytes.",
  700. # More bytes
  701. 10000 * "{}".format(random.randint(0, 1000) * 1000).encode("latin-1"),
  702. ],
  703. ids=["a little data as bytes.", "a large data as bytes."],
  704. )
  705. @parametrize("compress_level", [1, 3, 9])
  706. def test_binary_zlibfile(tmpdir, data, compress_level):
  707. filename = tmpdir.join("test.pkl").strpath
  708. # Regular cases
  709. with open(filename, "wb") as f:
  710. with BinaryZlibFile(f, "wb", compresslevel=compress_level) as fz:
  711. assert fz.writable()
  712. fz.write(data)
  713. assert fz.fileno() == f.fileno()
  714. with raises(io.UnsupportedOperation):
  715. fz._check_can_read()
  716. with raises(io.UnsupportedOperation):
  717. fz._check_can_seek()
  718. assert fz.closed
  719. with raises(ValueError):
  720. fz._check_not_closed()
  721. with open(filename, "rb") as f:
  722. with BinaryZlibFile(f) as fz:
  723. assert fz.readable()
  724. assert fz.seekable()
  725. assert fz.fileno() == f.fileno()
  726. assert fz.read() == data
  727. with raises(io.UnsupportedOperation):
  728. fz._check_can_write()
  729. assert fz.seekable()
  730. fz.seek(0)
  731. assert fz.tell() == 0
  732. assert fz.closed
  733. # Test with a filename as input
  734. with BinaryZlibFile(filename, "wb", compresslevel=compress_level) as fz:
  735. assert fz.writable()
  736. fz.write(data)
  737. with BinaryZlibFile(filename, "rb") as fz:
  738. assert fz.read() == data
  739. assert fz.seekable()
  740. # Test without context manager
  741. fz = BinaryZlibFile(filename, "wb", compresslevel=compress_level)
  742. assert fz.writable()
  743. fz.write(data)
  744. fz.close()
  745. fz = BinaryZlibFile(filename, "rb")
  746. assert fz.read() == data
  747. fz.close()
  748. @parametrize("bad_value", [-1, 10, 15, "a", (), {}])
  749. def test_binary_zlibfile_bad_compression_levels(tmpdir, bad_value):
  750. filename = tmpdir.join("test.pkl").strpath
  751. with raises(ValueError) as excinfo:
  752. BinaryZlibFile(filename, "wb", compresslevel=bad_value)
  753. pattern = re.escape(
  754. "'compresslevel' must be an integer between 1 and 9. "
  755. "You provided 'compresslevel={}'".format(bad_value)
  756. )
  757. excinfo.match(pattern)
  758. @parametrize("bad_mode", ["a", "x", "r", "w", 1, 2])
  759. def test_binary_zlibfile_invalid_modes(tmpdir, bad_mode):
  760. filename = tmpdir.join("test.pkl").strpath
  761. with raises(ValueError) as excinfo:
  762. BinaryZlibFile(filename, bad_mode)
  763. excinfo.match("Invalid mode")
  764. @parametrize("bad_file", [1, (), {}])
  765. def test_binary_zlibfile_invalid_filename_type(bad_file):
  766. with raises(TypeError) as excinfo:
  767. BinaryZlibFile(bad_file, "rb")
  768. excinfo.match("filename must be a str or bytes object, or a file")
  769. ###############################################################################
  770. # Test dumping array subclasses
  771. if np is not None:
  772. class SubArray(np.ndarray):
  773. def __reduce__(self):
  774. return _load_sub_array, (np.asarray(self),)
  775. def _load_sub_array(arr):
  776. d = SubArray(arr.shape)
  777. d[:] = arr
  778. return d
  779. class ComplexTestObject:
  780. """A complex object containing numpy arrays as attributes."""
  781. def __init__(self):
  782. self.array_float = np.arange(100, dtype="float64")
  783. self.array_int = np.ones(100, dtype="int32")
  784. self.array_obj = np.array(["a", 10, 20.0], dtype="object")
  785. @with_numpy
  786. def test_numpy_subclass(tmpdir):
  787. filename = tmpdir.join("test.pkl").strpath
  788. a = SubArray((10,))
  789. numpy_pickle.dump(a, filename)
  790. c = numpy_pickle.load(filename)
  791. assert isinstance(c, SubArray)
  792. np.testing.assert_array_equal(c, a)
  793. def test_pathlib(tmpdir):
  794. filename = tmpdir.join("test.pkl").strpath
  795. value = 123
  796. numpy_pickle.dump(value, Path(filename))
  797. assert numpy_pickle.load(filename) == value
  798. numpy_pickle.dump(value, filename)
  799. assert numpy_pickle.load(Path(filename)) == value
  800. @with_numpy
  801. def test_non_contiguous_array_pickling(tmpdir):
  802. filename = tmpdir.join("test.pkl").strpath
  803. for array in [ # Array that triggers a contiguousness issue with nditer,
  804. # see https://github.com/joblib/joblib/pull/352 and see
  805. # https://github.com/joblib/joblib/pull/353
  806. np.asfortranarray([[1, 2], [3, 4]])[1:],
  807. # Non contiguous array with works fine with nditer
  808. np.ones((10, 50, 20), order="F")[:, :1, :],
  809. ]:
  810. assert not array.flags.c_contiguous
  811. assert not array.flags.f_contiguous
  812. numpy_pickle.dump(array, filename)
  813. array_reloaded = numpy_pickle.load(filename)
  814. np.testing.assert_array_equal(array_reloaded, array)
  815. @with_numpy
  816. def test_pickle_highest_protocol(tmpdir):
  817. # ensure persistence of a numpy array is valid even when using
  818. # the pickle HIGHEST_PROTOCOL.
  819. # see https://github.com/joblib/joblib/issues/362
  820. filename = tmpdir.join("test.pkl").strpath
  821. test_array = np.zeros(10)
  822. numpy_pickle.dump(test_array, filename, protocol=pickle.HIGHEST_PROTOCOL)
  823. array_reloaded = numpy_pickle.load(filename)
  824. np.testing.assert_array_equal(array_reloaded, test_array)
  825. @with_numpy
  826. def test_pickle_in_socket():
  827. # test that joblib can pickle in sockets
  828. test_array = np.arange(10)
  829. _ADDR = ("localhost", 12345)
  830. listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  831. listener.bind(_ADDR)
  832. listener.listen(1)
  833. with socket.create_connection(_ADDR) as client:
  834. server, client_addr = listener.accept()
  835. with server.makefile("wb") as sf:
  836. numpy_pickle.dump(test_array, sf)
  837. with client.makefile("rb") as cf:
  838. array_reloaded = numpy_pickle.load(cf)
  839. np.testing.assert_array_equal(array_reloaded, test_array)
  840. # Check that a byte-aligned numpy array written in a file can be send
  841. # over a socket and then read on the other side
  842. bytes_to_send = io.BytesIO()
  843. numpy_pickle.dump(test_array, bytes_to_send)
  844. server.send(bytes_to_send.getvalue())
  845. with client.makefile("rb") as cf:
  846. array_reloaded = numpy_pickle.load(cf)
  847. np.testing.assert_array_equal(array_reloaded, test_array)
  848. @with_numpy
  849. def test_load_memmap_with_big_offset(tmpdir):
  850. # Test that numpy memmap offset is set correctly if greater than
  851. # mmap.ALLOCATIONGRANULARITY, see
  852. # https://github.com/joblib/joblib/issues/451 and
  853. # https://github.com/numpy/numpy/pull/8443 for more details.
  854. fname = tmpdir.join("test.mmap").strpath
  855. size = mmap.ALLOCATIONGRANULARITY
  856. obj = [np.zeros(size, dtype="uint8"), np.ones(size, dtype="uint8")]
  857. numpy_pickle.dump(obj, fname)
  858. memmaps = numpy_pickle.load(fname, mmap_mode="r")
  859. assert isinstance(memmaps[1], np.memmap)
  860. assert memmaps[1].offset > size
  861. np.testing.assert_array_equal(obj, memmaps)
  862. def test_register_compressor(tmpdir):
  863. # Check that registering compressor file works.
  864. compressor_name = "test-name"
  865. compressor_prefix = "test-prefix"
  866. class BinaryCompressorTestFile(io.BufferedIOBase):
  867. pass
  868. class BinaryCompressorTestWrapper(CompressorWrapper):
  869. def __init__(self):
  870. CompressorWrapper.__init__(
  871. self, obj=BinaryCompressorTestFile, prefix=compressor_prefix
  872. )
  873. register_compressor(compressor_name, BinaryCompressorTestWrapper())
  874. assert _COMPRESSORS[compressor_name].fileobj_factory == BinaryCompressorTestFile
  875. assert _COMPRESSORS[compressor_name].prefix == compressor_prefix
  876. # Remove this dummy compressor file from extra compressors because other
  877. # tests might fail because of this
  878. _COMPRESSORS.pop(compressor_name)
  879. @parametrize("invalid_name", [1, (), {}])
  880. def test_register_compressor_invalid_name(invalid_name):
  881. # Test that registering an invalid compressor name is not allowed.
  882. with raises(ValueError) as excinfo:
  883. register_compressor(invalid_name, None)
  884. excinfo.match("Compressor name should be a string")
  885. def test_register_compressor_invalid_fileobj():
  886. # Test that registering an invalid file object is not allowed.
  887. class InvalidFileObject:
  888. pass
  889. class InvalidFileObjectWrapper(CompressorWrapper):
  890. def __init__(self):
  891. CompressorWrapper.__init__(self, obj=InvalidFileObject, prefix=b"prefix")
  892. with raises(ValueError) as excinfo:
  893. register_compressor("invalid", InvalidFileObjectWrapper())
  894. excinfo.match(
  895. "Compressor 'fileobj_factory' attribute should implement "
  896. "the file object interface"
  897. )
  898. class AnotherZlibCompressorWrapper(CompressorWrapper):
  899. def __init__(self):
  900. CompressorWrapper.__init__(self, obj=BinaryZlibFile, prefix=b"prefix")
  901. class StandardLibGzipCompressorWrapper(CompressorWrapper):
  902. def __init__(self):
  903. CompressorWrapper.__init__(self, obj=gzip.GzipFile, prefix=b"prefix")
  904. def test_register_compressor_already_registered():
  905. # Test registration of existing compressor files.
  906. compressor_name = "test-name"
  907. # register a test compressor
  908. register_compressor(compressor_name, AnotherZlibCompressorWrapper())
  909. with raises(ValueError) as excinfo:
  910. register_compressor(compressor_name, StandardLibGzipCompressorWrapper())
  911. excinfo.match("Compressor '{}' already registered.".format(compressor_name))
  912. register_compressor(compressor_name, StandardLibGzipCompressorWrapper(), force=True)
  913. assert compressor_name in _COMPRESSORS
  914. assert _COMPRESSORS[compressor_name].fileobj_factory == gzip.GzipFile
  915. # Remove this dummy compressor file from extra compressors because other
  916. # tests might fail because of this
  917. _COMPRESSORS.pop(compressor_name)
  918. @with_lz4
  919. def test_lz4_compression(tmpdir):
  920. # Check that lz4 can be used when dependency is available.
  921. import lz4.frame
  922. compressor = "lz4"
  923. assert compressor in _COMPRESSORS
  924. assert _COMPRESSORS[compressor].fileobj_factory == lz4.frame.LZ4FrameFile
  925. fname = tmpdir.join("test.pkl").strpath
  926. data = "test data"
  927. numpy_pickle.dump(data, fname, compress=compressor)
  928. with open(fname, "rb") as f:
  929. assert f.read(len(_LZ4_PREFIX)) == _LZ4_PREFIX
  930. assert numpy_pickle.load(fname) == data
  931. # Test that LZ4 is applied based on file extension
  932. numpy_pickle.dump(data, fname + ".lz4")
  933. with open(fname, "rb") as f:
  934. assert f.read(len(_LZ4_PREFIX)) == _LZ4_PREFIX
  935. assert numpy_pickle.load(fname) == data
  936. @without_lz4
  937. def test_lz4_compression_without_lz4(tmpdir):
  938. # Check that lz4 cannot be used when dependency is not available.
  939. fname = tmpdir.join("test.nolz4").strpath
  940. data = "test data"
  941. msg = LZ4_NOT_INSTALLED_ERROR
  942. with raises(ValueError) as excinfo:
  943. numpy_pickle.dump(data, fname, compress="lz4")
  944. excinfo.match(msg)
  945. with raises(ValueError) as excinfo:
  946. numpy_pickle.dump(data, fname + ".lz4")
  947. excinfo.match(msg)
  948. protocols = [pickle.DEFAULT_PROTOCOL]
  949. if pickle.HIGHEST_PROTOCOL != pickle.DEFAULT_PROTOCOL:
  950. protocols.append(pickle.HIGHEST_PROTOCOL)
  951. @with_numpy
  952. @parametrize("protocol", protocols)
  953. def test_memmap_alignment_padding(tmpdir, protocol):
  954. # Test that memmaped arrays returned by numpy.load are correctly aligned
  955. fname = tmpdir.join("test.mmap").strpath
  956. a = np.random.randn(2)
  957. numpy_pickle.dump(a, fname, protocol=protocol)
  958. memmap = numpy_pickle.load(fname, mmap_mode="r")
  959. assert isinstance(memmap, np.memmap)
  960. np.testing.assert_array_equal(a, memmap)
  961. assert memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0
  962. assert memmap.flags.aligned
  963. array_list = [
  964. np.random.randn(2),
  965. np.random.randn(2),
  966. np.random.randn(2),
  967. np.random.randn(2),
  968. ]
  969. # On Windows OSError 22 if reusing the same path for memmap ...
  970. fname = tmpdir.join("test1.mmap").strpath
  971. numpy_pickle.dump(array_list, fname, protocol=protocol)
  972. l_reloaded = numpy_pickle.load(fname, mmap_mode="r")
  973. for idx, memmap in enumerate(l_reloaded):
  974. assert isinstance(memmap, np.memmap)
  975. np.testing.assert_array_equal(array_list[idx], memmap)
  976. assert memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0
  977. assert memmap.flags.aligned
  978. array_dict = {
  979. "a0": np.arange(2, dtype=np.uint8),
  980. "a1": np.arange(3, dtype=np.uint8),
  981. "a2": np.arange(5, dtype=np.uint8),
  982. "a3": np.arange(7, dtype=np.uint8),
  983. "a4": np.arange(11, dtype=np.uint8),
  984. "a5": np.arange(13, dtype=np.uint8),
  985. "a6": np.arange(17, dtype=np.uint8),
  986. "a7": np.arange(19, dtype=np.uint8),
  987. "a8": np.arange(23, dtype=np.uint8),
  988. }
  989. # On Windows OSError 22 if reusing the same path for memmap ...
  990. fname = tmpdir.join("test2.mmap").strpath
  991. numpy_pickle.dump(array_dict, fname, protocol=protocol)
  992. d_reloaded = numpy_pickle.load(fname, mmap_mode="r")
  993. for key, memmap in d_reloaded.items():
  994. assert isinstance(memmap, np.memmap)
  995. np.testing.assert_array_equal(array_dict[key], memmap)
  996. assert memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0
  997. assert memmap.flags.aligned