| 1 |
import datetime |
| 2 |
import warnings |
| 3 |
|
| 4 |
import pytest |
| 5 |
|
| 6 |
try: |
| 7 |
import numpy as np |
| 8 |
import numpy.testing as npt |
| 9 |
from numpy.testing import assert_equal |
| 10 |
except ImportError: |
| 11 |
pytest.skip('numpy is not available', allow_module_level=True) |
| 12 |
|
| 13 |
import jsonpickle |
| 14 |
import jsonpickle.ext.numpy |
| 15 |
from jsonpickle import handlers |
| 16 |
|
| 17 |
|
| 18 |
@pytest.fixture(scope='module', autouse=True) |
| 19 |
def numpy_extension(): |
| 20 |
"""Initialize the numpy extension for this test module""" |
| 21 |
jsonpickle.ext.numpy.register_handlers(ndarray_mode='warn') |
| 22 |
yield # control to the test function. |
| 23 |
jsonpickle.ext.numpy.unregister_handlers() |
| 24 |
|
| 25 |
|
| 26 |
def roundtrip(obj): |
| 27 |
return jsonpickle.decode(jsonpickle.encode(obj)) |
| 28 |
|
| 29 |
|
| 30 |
def test_dtype_roundtrip(): |
| 31 |
dtypes = [ |
| 32 |
np.int_, |
| 33 |
np.int32, |
| 34 |
np.float64, |
| 35 |
np.complex128, |
| 36 |
np.str_, |
| 37 |
np.object_, |
| 38 |
np.dtype(np.void), |
| 39 |
np.dtype(np.int32), |
| 40 |
np.dtype(np.float32), |
| 41 |
np.dtype('f4,i4,f2,i1'), |
| 42 |
np.dtype(('f4', 'i4'), ('f2', 'i1')), |
| 43 |
np.dtype('i4', align=True), |
| 44 |
np.dtype('M8[7D]'), |
| 45 |
np.dtype( |
| 46 |
{ |
| 47 |
'names': ['f0', 'f1', 'f2'], |
| 48 |
'formats': ['<u4', '<u2', '<u2'], |
| 49 |
'offsets': [0, 0, 2], |
| 50 |
}, |
| 51 |
align=True, |
| 52 |
), |
| 53 |
np.dtype([('f0', 'i4'), ('f2', 'i1')]), |
| 54 |
np.dtype( |
| 55 |
[ |
| 56 |
( |
| 57 |
'top', |
| 58 |
[ |
| 59 |
('tiles', ('>f4', (64, 64)), (1,)), |
| 60 |
('rtile', '>f4', (64, 36)), |
| 61 |
], |
| 62 |
(3,), |
| 63 |
), |
| 64 |
( |
| 65 |
'bottom', |
| 66 |
[ |
| 67 |
('bleft', ('>f4', (8, 64)), (1,)), |
| 68 |
('bright', '>f4', (8, 36)), |
| 69 |
], |
| 70 |
), |
| 71 |
] |
| 72 |
), |
| 73 |
] |
| 74 |
|
| 75 |
for dtype in dtypes: |
| 76 |
encoded = jsonpickle.encode(dtype) |
| 77 |
decoded = jsonpickle.decode(encoded) |
| 78 |
assert dtype == decoded |
| 79 |
|
| 80 |
|
| 81 |
def test_generic_roundtrip(): |
| 82 |
values = [ |
| 83 |
np.int_(1), |
| 84 |
np.int32(-2), |
| 85 |
np.float64(2.5), |
| 86 |
np.nan, |
| 87 |
-np.inf, |
| 88 |
np.inf, |
| 89 |
np.datetime64('2014-01-01'), |
| 90 |
np.str_('foo'), |
| 91 |
np.object_({'a': 'b'}), |
| 92 |
np.complex128(1 - 2j), |
| 93 |
] |
| 94 |
for value in values: |
| 95 |
decoded = roundtrip(value) |
| 96 |
assert_equal(decoded, value) |
| 97 |
assert isinstance(decoded, type(value)) |
| 98 |
|
| 99 |
|
| 100 |
def test_ndarray_roundtrip(): |
| 101 |
arrays = [ |
| 102 |
np.random.random((10, 20)), |
| 103 |
np.array([[True, False, True]]), |
| 104 |
np.array(['foo', 'bar']), |
| 105 |
np.array([b'baz']), |
| 106 |
np.array(['2010', 'NaT', '2030']).astype('M'), |
| 107 |
np.rec.array(b'abcdefg' * 100, formats='i2,a3,i4', shape=3), |
| 108 |
np.rec.array( |
| 109 |
[ |
| 110 |
(1, 11, 'a'), |
| 111 |
(2, 22, 'b'), |
| 112 |
(3, 33, 'c'), |
| 113 |
(4, 44, 'd'), |
| 114 |
(5, 55, 'ex'), |
| 115 |
(6, 66, 'f'), |
| 116 |
(7, 77, 'g'), |
| 117 |
], |
| 118 |
formats='u1,f4,a1', |
| 119 |
), |
| 120 |
np.array(['1960-03-12', datetime.date(1960, 3, 12)], dtype='M8[D]'), |
| 121 |
np.array([0, 1, -1, np.inf, -np.inf, np.nan], dtype='f2'), |
| 122 |
] |
| 123 |
|
| 124 |
arrays.extend( |
| 125 |
[ |
| 126 |
np.rec.array( |
| 127 |
[('NGC1001', 11), ('NGC1002', 1.0), ('NGC1003', 1.0)], |
| 128 |
dtype=[('target', 'S20'), ('V_mag', 'f4')], |
| 129 |
) |
| 130 |
] |
| 131 |
) |
| 132 |
for array in arrays: |
| 133 |
decoded = roundtrip(array) |
| 134 |
assert_equal(decoded, array) |
| 135 |
assert decoded.dtype == array.dtype |
| 136 |
|
| 137 |
|
| 138 |
def test_shapes_containing_zeroes(): |
| 139 |
"""Test shapes which cannot be represented as nested lists""" |
| 140 |
expect = np.eye(3)[3:] |
| 141 |
actual = roundtrip(expect) |
| 142 |
npt.assert_array_equal(expect, actual) |
| 143 |
|
| 144 |
|
| 145 |
def test_accuracy(): |
| 146 |
"""Test the accuracy of the string representation""" |
| 147 |
expect = np.random.randn(3, 3) |
| 148 |
actual = roundtrip(expect) |
| 149 |
npt.assert_array_equal(expect, actual) |
| 150 |
|
| 151 |
|
| 152 |
def test_b64(): |
| 153 |
"""Test the binary encoding""" |
| 154 |
# Array of substantial size is stored as b64. |
| 155 |
expect = np.random.rand(10, 10) |
| 156 |
actual = roundtrip(expect) |
| 157 |
npt.assert_array_equal(expect, actual) |
| 158 |
|
| 159 |
|
| 160 |
def test_views(): |
| 161 |
"""Test views under serialization""" |
| 162 |
rng = np.arange(20) # a range of an array |
| 163 |
view = rng[10:] # a view referencing a portion of an array |
| 164 |
data = [rng, view] |
| 165 |
|
| 166 |
actual = roundtrip(data) |
| 167 |
actual[0][15] = -1 |
| 168 |
assert actual[1][5] == -1 |
| 169 |
|
| 170 |
|
| 171 |
def test_strides(): |
| 172 |
"""Test non-standard strides and offsets""" |
| 173 |
arr = np.eye(3) |
| 174 |
view = arr[1:, 1:] |
| 175 |
assert view.base is arr |
| 176 |
|
| 177 |
data = [arr, view] |
| 178 |
actual = roundtrip(data) |
| 179 |
|
| 180 |
# test that the deserialized arrays indeed view the same memory |
| 181 |
new_arr, new_view = actual |
| 182 |
new_arr[1, 2] = -1 |
| 183 |
assert new_view[0, 1] == -1 |
| 184 |
assert new_view.base is new_arr |
| 185 |
|
| 186 |
|
| 187 |
def test_weird_arrays(): |
| 188 |
"""Test references to arrays that do not effectively own their memory""" |
| 189 |
a = np.arange(9) |
| 190 |
b = a[5:] |
| 191 |
a.strides = 1 |
| 192 |
|
| 193 |
# this is kinda fishy; a has overlapping memory, _a does not |
| 194 |
warn_count = 1 |
| 195 |
with warnings.catch_warnings(record=True) as w: |
| 196 |
_a = roundtrip(a) |
| 197 |
assert len(w) == warn_count |
| 198 |
npt.assert_array_equal(a, _a) |
| 199 |
|
| 200 |
# this also requires a deepcopy to work |
| 201 |
with warnings.catch_warnings(record=True) as w: |
| 202 |
_a, _b = roundtrip([a, b]) |
| 203 |
assert len(w) == warn_count |
| 204 |
npt.assert_array_equal(a, _a) |
| 205 |
npt.assert_array_equal(b, _b) |
| 206 |
|
| 207 |
|
| 208 |
def test_transpose(): |
| 209 |
"""test handling of non-c-contiguous memory layout""" |
| 210 |
# simple case; view a c-contiguous array |
| 211 |
a = np.arange(9).reshape(3, 3) |
| 212 |
b = a[1:, 1:] |
| 213 |
assert b.base is a.base |
| 214 |
_a, _b = roundtrip([a, b]) |
| 215 |
assert _b.base is _a.base |
| 216 |
npt.assert_array_equal(a, _a) |
| 217 |
npt.assert_array_equal(b, _b) |
| 218 |
|
| 219 |
# a and b both view the same contiguous array |
| 220 |
a = np.arange(9).reshape(3, 3).T |
| 221 |
b = a[1:, 1:] |
| 222 |
assert b.base is a.base |
| 223 |
_a, _b = roundtrip([a, b]) |
| 224 |
assert _b.base is _a.base |
| 225 |
npt.assert_array_equal(a, _a) |
| 226 |
npt.assert_array_equal(b, _b) |
| 227 |
|
| 228 |
# view an f-contiguous array |
| 229 |
a = a.copy() |
| 230 |
a.strides = a.strides[::-1] |
| 231 |
b = a[1:, 1:] |
| 232 |
assert b.base is a |
| 233 |
_a, _b = roundtrip([a, b]) |
| 234 |
assert _b.base is _a |
| 235 |
npt.assert_array_equal(a, _a) |
| 236 |
npt.assert_array_equal(b, _b) |
| 237 |
|
| 238 |
# now a.data.contiguous is False; we have to make a deepcopy to make |
| 239 |
# this work note that this is a pretty contrived example though! |
| 240 |
a = np.arange(8).reshape(2, 2, 2).copy() |
| 241 |
a.strides = a.strides[0], a.strides[2], a.strides[1] |
| 242 |
b = a[1:, 1:] |
| 243 |
assert b.base is a |
| 244 |
|
| 245 |
warn_count = 1 |
| 246 |
with warnings.catch_warnings(record=True) as w: |
| 247 |
_a, _b = roundtrip([a, b]) |
| 248 |
assert len(w) == warn_count |
| 249 |
npt.assert_array_equal(a, _a) |
| 250 |
npt.assert_array_equal(b, _b) |
| 251 |
|
| 252 |
|
| 253 |
def test_fortran_base(): |
| 254 |
"""Test a base array in fortran order""" |
| 255 |
a = np.asfortranarray(np.arange(100).reshape((10, 10))) |
| 256 |
_a = roundtrip(a) |
| 257 |
npt.assert_array_equal(a, _a) |
| 258 |
|
| 259 |
|
| 260 |
def test_buffer(): |
| 261 |
"""test behavior with memoryviews which are not ndarrays""" |
| 262 |
bstring = b'abcdefgh' |
| 263 |
a = np.frombuffer(bstring, dtype=np.byte) |
| 264 |
warn_count = 1 |
| 265 |
with warnings.catch_warnings(record=True) as w: |
| 266 |
_a = roundtrip(a) |
| 267 |
npt.assert_array_equal(a, _a) |
| 268 |
assert len(w) == warn_count |
| 269 |
|
| 270 |
|
| 271 |
def test_as_strided(): |
| 272 |
"""Test the result of as_strided() |
| 273 |
|
| 274 |
as_strided() returns an object that implements the array interface but |
| 275 |
is not an ndarray. |
| 276 |
|
| 277 |
""" |
| 278 |
warn_count = 1 |
| 279 |
a = np.arange(10) |
| 280 |
b = np.lib.stride_tricks.as_strided(a, shape=(5,), strides=(a.dtype.itemsize * 2,)) |
| 281 |
data = [a, b] |
| 282 |
|
| 283 |
with warnings.catch_warnings(record=True) as w: |
| 284 |
# as_strided returns a DummyArray object, which we can not |
| 285 |
# currently serialize correctly FIXME: would be neat to add |
| 286 |
# support for all objects implementing the __array_interface__ |
| 287 |
_data = roundtrip(data) |
| 288 |
assert len(w) == warn_count |
| 289 |
|
| 290 |
# as we were warned, deserialized result is no longer a view |
| 291 |
_data[0][0] = -1 |
| 292 |
assert _data[1][0] == 0 |
| 293 |
|
| 294 |
|
| 295 |
def test_immutable(): |
| 296 |
"""test that immutability flag is copied correctly""" |
| 297 |
a = np.arange(10) |
| 298 |
a.flags.writeable = False |
| 299 |
_a = roundtrip(a) |
| 300 |
with pytest.raises(ValueError): |
| 301 |
_a[0] = 0 |
| 302 |
|
| 303 |
|
| 304 |
def test_byteorder(): |
| 305 |
"""Test the byteorder for text and binary encodings""" |
| 306 |
# small arr is stored as text |
| 307 |
a = np.arange(10) |
| 308 |
av = a.view(a.dtype.newbyteorder()) |
| 309 |
b = a[:] |
| 310 |
bv = b.view(b.dtype.newbyteorder()) |
| 311 |
_av, _bv = roundtrip([av, bv]) |
| 312 |
npt.assert_array_equal(av, _av) |
| 313 |
npt.assert_array_equal(bv, _bv) |
| 314 |
|
| 315 |
# bigger arr is stored as binary |
| 316 |
a = np.arange(100) |
| 317 |
av = a.view(a.dtype.newbyteorder()) |
| 318 |
b = a[:] |
| 319 |
bv = b.view(b.dtype.newbyteorder()) |
| 320 |
_av, _bv = roundtrip([av, bv]) |
| 321 |
npt.assert_array_equal(av, _av) |
| 322 |
npt.assert_array_equal(bv, _bv) |
| 323 |
|
| 324 |
|
| 325 |
def test_zero_dimensional_array(): |
| 326 |
expect = np.array(float(0.0), dtype="float64") |
| 327 |
actual = jsonpickle.decode(jsonpickle.encode(expect)) |
| 328 |
npt.assert_array_equal(expect, actual) |
| 329 |
|
| 330 |
|
| 331 |
def test_nested_data_list_of_dict_with_list_keys(): |
| 332 |
"""Ensure we can handle numpy arrays within a nested structure""" |
| 333 |
expect = [{'key': [np.array(0)]}] |
| 334 |
actual = roundtrip(expect) |
| 335 |
npt.assert_array_equal(expect[0]['key'][0], actual[0]['key'][0]) |
| 336 |
|
| 337 |
expect = [{'key': [np.array([1.0])]}] |
| 338 |
actual = roundtrip(expect) |
| 339 |
npt.assert_array_equal(expect[0]['key'][0], actual[0]['key'][0]) |
| 340 |
|
| 341 |
|
| 342 |
def test_size_threshold_None(): |
| 343 |
handler = jsonpickle.ext.numpy.NumpyNDArrayHandlerView(size_threshold=None) |
| 344 |
handlers.registry.unregister(np.ndarray) |
| 345 |
handlers.registry.register(np.ndarray, handler, base=True) |
| 346 |
expect = np.array([0, 1]) |
| 347 |
actual = roundtrip(expect) |
| 348 |
npt.assert_array_equal(expect, actual) |
| 349 |
|
| 350 |
|
| 351 |
def test_ndarray_dtype_object(): |
| 352 |
a = np.array(['F' + str(i) for i in range(30)], dtype=object) |
| 353 |
buf = jsonpickle.encode(a) |
| 354 |
# This is critical for reproducing the numpy segfault issue when |
| 355 |
# restoring ndarray of dtype object. |
| 356 |
del a |
| 357 |
expect = np.array(['F' + str(i) for i in range(30)], dtype=object) |
| 358 |
actual = jsonpickle.decode(buf) |
| 359 |
npt.assert_array_equal(expect, actual) |
| 360 |
|
| 361 |
|
| 362 |
def test_np_random(): |
| 363 |
"""Ensure random.random() arrays can be serialized""" |
| 364 |
obj = np.random.random(100) |
| 365 |
encoded = jsonpickle.encode(obj) |
| 366 |
clone = jsonpickle.decode(encoded) |
| 367 |
assert 100 == len(clone) |
| 368 |
for idx, (expect, actual) in enumerate(zip(obj, clone)): |
| 369 |
assert expect == actual |
| 370 |
|
| 371 |
|
| 372 |
def test_np_poly1d(): |
| 373 |
# issue 391, test poly1d roundtrip |
| 374 |
obj = np.poly1d([1, 2, 3]) |
| 375 |
assert obj == jsonpickle.decode(jsonpickle.encode(obj)) |