Debian Codegraph @

tests/jsonpickle_test.py

raw
1 # Copyright (C) 2008 John Paulett (john -at- paulett.org)
2 # Copyright (C) 2009-2024 David Aguilar (davvid -at- gmail.com)
3 # All rights reserved.
4 #
5 # This software is licensed as described in the file COPYING, which
6 # you should have received as part of this distribution.
7
8 import collections
9 import os
10 import warnings
11
12 import pytest
13
14 import jsonpickle
15 import jsonpickle.backend
16 import jsonpickle.handlers
17 from jsonpickle import tags, util
18
19
20 class ListLike:
21 def __init__(self):
22 self.internal_list = []
23
24 def append(self, item):
25 self.internal_list.append(item)
26
27 def __getitem__(self, i):
28 return self.internal_list[i]
29
30
31 class Thing:
32 def __init__(self, name):
33 self.name = name
34 self.child = None
35
36 def __iter__(self):
37 for attr in [
38 x for x in getattr(self.__class__, '__dict__') if not x.startswith('__')
39 ]:
40 yield attr, getattr(self, attr)
41
42 def __repr__(self):
43 return 'Thing("%s")' % self.name
44
45
46 class Capture:
47 def __init__(self, *args, **kwargs):
48 self.args = args
49 self.kwargs = kwargs
50
51 def __repr__(self):
52 return object.__repr__(self) + (f'({self.args!r}, {self.kwargs!r})')
53
54
55 class ThingWithProps:
56 def _get_identity(self):
57 keys = [self.dogs, self.monkies, self.name]
58 return hash('-'.join([str(key) for key in keys]))
59
60 identity = property(_get_identity)
61
62 def _get_dogs(self):
63 return self._critters[0][1]
64
65 dogs = property(_get_dogs)
66
67 def _get_monkies(self):
68 return self._critters[1][1]
69
70 monkies = property(_get_monkies)
71
72 def __init__(self, name='', dogs='reliable', monkies='tricksy'):
73 self.name = name
74 self._critters = (('dogs', dogs), ('monkies', monkies))
75
76 def __eq__(self, other):
77 return self.identity == other.identity
78
79 def __getstate__(self):
80 out = dict(
81 __identity__=self.identity,
82 nom=self.name,
83 dogs=self.dogs,
84 monkies=self.monkies,
85 )
86 return out
87
88 def __setstate__(self, state_dict):
89 self._critters = (
90 ('dogs', state_dict.get('dogs')),
91 ('monkies', state_dict.get('monkies')),
92 )
93 self.name = state_dict.get('nom', '')
94 ident = state_dict.get('__identity__')
95 if ident != self.identity:
96 raise ValueError('expanded object does not match original state!')
97
98
99 class UserDict(dict):
100 """A user class that inherits from :class:`dict`"""
101
102 def __init__(self, **kwargs):
103 dict.__init__(self, **kwargs)
104 self.valid = False
105
106
107 class Outer:
108 class Middle:
109 class Inner:
110 pass
111
112
113 class MySlots:
114 __slots__ = ('alpha', '__beta')
115
116 def __init__(self):
117 self.alpha = 1
118 self.__beta = 1
119
120
121 class MyPropertiesSlots:
122 __slots__ = ('alpha', 'arr')
123
124 def __init__(self):
125 self.alpha = 1
126 self.arr = [1, 2, 3]
127
128 @property
129 def arr_len(self):
130 return len(self.arr)
131
132 @property
133 def other_object(self):
134 return Thing('Test')
135
136 def __eq__(self, other):
137 return (
138 self.alpha == other.alpha
139 and self.arr == other.arr
140 and self.arr_len == other.arr_len
141 and list(self.other_object) == list(other.other_object)
142 )
143
144
145 class MyPropertiesDict:
146 def __init__(self):
147 self.alpha = 1
148 self.arr = [1, 2, 3]
149
150 @property
151 def arr_len(self):
152 return len(self.arr)
153
154 @property
155 def other_object(self):
156 return Thing('Test')
157
158 def __eq__(self, other):
159 return (
160 self.alpha == other.alpha
161 and self.arr == other.arr
162 and self.arr_len == other.arr_len
163 and list(self.other_object) == list(other.other_object)
164 )
165
166
167 # see issue #478
168 class SafeData:
169 __slots__ = ()
170
171
172 class SafeString(str, SafeData):
173 __slots__ = ()
174
175
176 def on_missing_callback(class_name):
177 # not actually a runtime problem but it doesn't matter
178 warnings.warn('The unpickler could not find %s' % class_name, RuntimeWarning)
179
180
181 @pytest.fixture
182 def pickler():
183 """Returns a default-constructed pickler"""
184 return jsonpickle.pickler.Pickler()
185
186
187 @pytest.fixture
188 def unpickler():
189 """Returns a default-constructed unpickler"""
190 return jsonpickle.unpickler.Unpickler()
191
192
193 @pytest.fixture
194 def b85_pickler():
195 """Returns a pickler setup for base85 encoding"""
196 return jsonpickle.pickler.Pickler(use_base85=True)
197
198
199 def test_bytes_base85(b85_pickler):
200 """base85 is emitted when the pickler is setup to do so"""
201 data = os.urandom(16)
202 encoded = util.b85encode(data)
203 assert b85_pickler.flatten(data) == {tags.B85: encoded}
204
205
206 def test_bytes_base64_default(pickler):
207 """base64 must be used by default"""
208 data = os.urandom(16)
209 encoded = util.b64encode(data)
210 assert pickler.flatten(data) == {tags.B64: encoded}
211
212
213 def test_decode_base85(unpickler):
214 """base85 data must be restored"""
215 expected = 'Pÿthöñ 3!'.encode()
216 pickled = {tags.B85: util.b85encode(expected)}
217 assert unpickler.restore(pickled) == expected
218
219
220 @pytest.mark.parametrize('value', ['', '/', '\udc00', 1, True, False, None, [], {}])
221 def test_decode_invalid_b85(value, unpickler):
222 """Invalid base85 data restores to an empty string"""
223 expected = b''
224 pickled = {tags.B85: value}
225 assert unpickler.restore(pickled) == expected
226
227
228 def test_base85_still_handles_base64(unpickler):
229 """base64 must be restored even though base85 is the default"""
230 expected = 'Pÿthöñ 3!'.encode()
231 pickled = {tags.B64: util.b64encode(expected)}
232 assert unpickler.restore(pickled) == expected
233
234
235 @pytest.mark.parametrize(
236 'value', ['', 'x', '!', '\udc00', 0, 1, True, False, None, [], {}]
237 )
238 def test_decode_invalid_b64(value, unpickler):
239 """Invalid base85 data restores to an empty string"""
240 expected = b''
241 pickled = {tags.B64: value}
242 assert unpickler.restore(pickled) == expected
243
244
245 def test_string(pickler, unpickler):
246 """Strings must roundtrip"""
247 assert pickler.flatten('a string') == 'a string'
248 assert unpickler.restore('a string') == 'a string'
249
250
251 def test_int(pickler, unpickler):
252 """Ints must roundtrip"""
253 assert pickler.flatten(3) == 3
254 assert unpickler.restore(3) == 3
255
256
257 def test_float(pickler, unpickler):
258 """Floats must roundtrip"""
259 assert pickler.flatten(3.5) == 3.5
260 assert unpickler.restore(3.5) == 3.5
261
262
263 def test_boolean(pickler, unpickler):
264 """Booleans must roundtrip"""
265 assert pickler.flatten(True) is True
266 assert pickler.flatten(False) is False
267 assert unpickler.restore(True) is True
268 assert unpickler.restore(False) is False
269
270
271 def test_none(pickler, unpickler):
272 """None must roundtrip"""
273 assert pickler.flatten(None) is None
274 assert unpickler.restore(None) is None
275
276
277 def test_list(pickler, unpickler):
278 """Nested and mixed lists must roundtrip"""
279 # multiple types of values
280 list_a = [1, 35.0, 'value']
281 assert pickler.flatten(list_a) == list_a
282 assert unpickler.restore(list_a) == list_a
283 # nested list
284 list_b = [40, 40, list_a, 6]
285 assert pickler.flatten(list_b) == list_b
286 assert unpickler.restore(list_b) == list_b
287 # 2D list
288 list_c = [[1, 2], [3, 4]]
289 assert pickler.flatten(list_c) == list_c
290 assert unpickler.restore(list_c) == list_c
291 # empty list
292 list_d = []
293 assert pickler.flatten(list_d) == list_d
294 assert unpickler.restore(list_d) == list_d
295
296
297 def test_nonetype():
298 """NoneType must roundtrip"""
299 typ = type(None)
300 typ_pickled = jsonpickle.encode(typ)
301 typ_unpickled = jsonpickle.decode(typ_pickled)
302 assert typ_unpickled == typ
303
304
305 def test_set(pickler, unpickler):
306 """Validate the internal representation for set() objects"""
307 set_list = ['orange', 'apple', 'grape']
308 set_obj = set(set_list)
309 flattened = pickler.flatten(set_obj)
310 for s in set_list:
311 assert s in flattened[tags.SET]
312 set_pickle = {tags.SET: set_list}
313 assert unpickler.restore(set_pickle) == set_obj
314
315
316 @pytest.mark.parametrize('value', ['', 0, 1, True, False, None, [], {}])
317 def test_set_with_invalid_data(value, unpickler):
318 """Invalid serialized set data results in an empty set"""
319 data = {tags.SET: value}
320 result = unpickler.restore(data)
321 assert result == set()
322
323
324 @pytest.mark.parametrize('value', ['', 0, 1, True, False, None, [], {}])
325 def test_tuple_with_invalid_data(value, unpickler):
326 """Invalid serialized tuple data results in an empty tuple"""
327 data = {tags.TUPLE: value}
328 result = unpickler.restore(data)
329 assert result == tuple()
330
331
332 def test_iterator_with_invalid_data(unpickler):
333 """Invalid serialized iterator data results in an empty iterator"""
334 data = {tags.ITERATOR: set()}
335 result = unpickler.restore(data)
336 with pytest.raises(StopIteration):
337 next(result)
338 assert False
339
340
341 @pytest.mark.parametrize(
342 'value', ['', 0, True, False, None, [], {}, ('x',), {'x': True}]
343 )
344 def test_reduce_with_invalid_data(value, unpickler):
345 """Invalid serialized reduce data results in an empty list"""
346 data = {tags.REDUCE: value}
347 result = unpickler.restore(data)
348 assert result == []
349
350
351 @pytest.mark.parametrize('value', ['', 'x', 1, True, [], {}])
352 def test_restore_id_with_invalid_data(value, unpickler):
353 """Invalid serialized ID data results in None"""
354 result = unpickler.restore({'ref': {tags.ID: value}})
355 assert result['ref'] is None
356
357
358 def test_dict(pickler, unpickler):
359 """Our custom keys are preserved when user dicts contain them"""
360 dict_a = {'key1': 1.0, 'key2': 20, 'key3': 'thirty', tags.JSON_KEY + '6': 6}
361 assert pickler.flatten(dict_a) == dict_a
362 assert unpickler.restore(dict_a) == dict_a
363 dict_b = {}
364 assert pickler.flatten(dict_b) == dict_b
365 assert unpickler.restore(dict_b) == dict_b
366
367
368 def test_tuple(pickler, unpickler):
369 """Validate the internal represntation for tuples"""
370 # currently all collections are converted to lists
371 tuple_a = (4, 16, 32)
372 tuple_a_pickle = {tags.TUPLE: [4, 16, 32]}
373 assert pickler.flatten(tuple_a) == tuple_a_pickle
374 assert unpickler.restore(tuple_a_pickle) == tuple_a
375 tuple_b = (4,)
376 tuple_b_pickle = {tags.TUPLE: [4]}
377 assert pickler.flatten(tuple_b) == tuple_b_pickle
378 assert unpickler.restore(tuple_b_pickle) == tuple_b
379
380
381 def _roundtrip(data):
382 """Encode and decode and object through jsonpickle"""
383 return jsonpickle.decode(jsonpickle.encode(data))
384
385
386 def test_tuple_roundtrip():
387 """Tuples can roundtrip"""
388 data = (1, 2, 3)
389 assert _roundtrip(data) == data
390
391
392 def test_set_roundtrip():
393 """Sets can roundtrip"""
394 data = {1, 2, 3}
395 assert _roundtrip(data) == data
396
397
398 def test_list_roundtrip():
399 """Lists can roundtrip"""
400 data = [1, 2, 3]
401 assert _roundtrip(data) == data
402
403
404 def test_class(pickler, unpickler):
405 """Nested objects can roundtrip"""
406 inst = Thing('test name')
407 inst.child = Thing('child name')
408 flattened = pickler.flatten(inst)
409 assert flattened['name'] == 'test name'
410 child = flattened['child']
411 assert child['name'] == 'child name'
412 inflated = unpickler.restore(flattened)
413 assert inflated.name == 'test name'
414 assert type(inflated) is Thing
415 assert inflated.child.name == 'child name'
416 assert type(inflated.child) is Thing
417
418
419 def test_classlist(pickler, unpickler):
420 """Lists with mixed object values can roundtrip"""
421 array = [Thing('one'), Thing('two'), 'a string']
422 flattened = pickler.flatten(array)
423 assert 'one' == flattened[0]['name']
424 assert 'two' == flattened[1]['name']
425 assert 'a string' == flattened[2]
426 inflated = unpickler.restore(flattened)
427 assert 'one' == inflated[0].name
428 assert type(inflated[0]) is Thing
429 assert 'two' == inflated[1].name
430 assert type(inflated[1]) is Thing
431 assert 'a string' == inflated[2]
432
433
434 def test_classdict(pickler, unpickler):
435 """Dicts with object values can roundtrip"""
436 obj_dict = {'k1': Thing('one'), 'k2': Thing('two'), 'k3': 3}
437 flattened = pickler.flatten(obj_dict)
438 assert 'one' == flattened['k1']['name']
439 assert 'two' == flattened['k2']['name']
440 assert 3 == flattened['k3']
441 inflated = unpickler.restore(flattened)
442 assert 'one' == inflated['k1'].name
443 assert type(inflated['k1']) is Thing
444 assert 'two' == inflated['k2'].name
445 assert type(inflated['k2']) is Thing
446 assert 3 == inflated['k3']
447
448
449 def test_recursive():
450 """create a recursive structure and test that we can handle it"""
451 parent = Thing('parent')
452 child = Thing('child')
453 child.sibling = Thing('sibling')
454 parent.self = parent
455 parent.child = child
456 parent.child.twin = child
457 parent.child.parent = parent
458 parent.child.sibling.parent = parent
459 cloned = jsonpickle.decode(jsonpickle.encode(parent))
460 assert parent.name == cloned.name
461 assert parent.child.name == cloned.child.name
462 assert parent.child.sibling.name == cloned.child.sibling.name
463 assert cloned == cloned.child.parent
464 assert cloned == cloned.child.sibling.parent
465 assert cloned == cloned.child.twin.parent
466 assert cloned.child == cloned.child.twin
467
468
469 def test_tuple_notunpicklable(pickler):
470 """Tuples become lists when unpicklable is False"""
471 pickler.unpicklable = False
472 flattened = pickler.flatten(('one', 2, 3))
473 assert flattened == ['one', 2, 3]
474
475
476 def test_set_not_unpicklable(pickler):
477 """Sets become lists when unpicklable is False"""
478 pickler.unpicklable = False
479 flattened = pickler.flatten({'one', 2, 3})
480 assert 'one' in flattened
481 assert 2 in flattened
482 assert 3 in flattened
483 assert isinstance(flattened, list)
484
485
486 def test_thing_with_module(pickler, unpickler):
487 """Objects with references to modules can roundtrip"""
488 obj = Thing('with-module')
489 obj.themodule = os
490 flattened = pickler.flatten(obj)
491 inflated = unpickler.restore(flattened)
492 assert inflated.themodule == os
493
494
495 def test_thing_with_module_safe(pickler, unpickler):
496 """Objects with inner references to modules can roundtrip in safe mode"""
497 obj = Thing('with-module')
498 obj.themodule = os
499 flattened = pickler.flatten(obj)
500 unpickler.safe = True
501 inflated = unpickler.restore(flattened)
502 assert inflated.themodule is os
503 # Unsafe mode
504 unpickler.safe = False
505 inflated = unpickler.restore(flattened)
506 assert inflated.themodule is os
507
508
509 def test_thing_with_submodule(pickler, unpickler):
510 """Objects with inner references to modules can roundtrip"""
511 obj = Thing('with-submodule')
512 obj.submodule = collections
513 flattened = pickler.flatten(obj)
514 inflated = unpickler.restore(flattened)
515 assert inflated.submodule == collections
516
517
518 def test_type_reference(pickler, unpickler):
519 """This test ensures that users can store references to types."""
520 obj = Thing('object-with-type-reference')
521 # reference the built-in 'object' type
522 obj.typeref = object
523 flattened = pickler.flatten(obj)
524 assert flattened['typeref'] == {tags.TYPE: 'builtins.object'}
525 inflated = unpickler.restore(flattened)
526 assert inflated.typeref == object
527
528
529 def test_class_reference(pickler, unpickler):
530 """This test ensures that users can store references to classes."""
531 obj = Thing('object-with-class-reference')
532 # reference the 'Thing' class (not an instance of the class)
533 obj.classref = Thing
534 flattened = pickler.flatten(obj)
535 assert flattened['classref'] == {tags.TYPE: 'jsonpickle_test.Thing'}
536 inflated = unpickler.restore(flattened)
537 assert inflated.classref is Thing
538
539
540 def test_supports_getstate_setstate(pickler, unpickler):
541 """Objects with getstate and setstate can roundtrip"""
542 obj = ThingWithProps('object-which-defines-getstate-setstate')
543 flattened = pickler.flatten(obj)
544 assert flattened[tags.STATE].get('__identity__')
545 assert flattened[tags.STATE].get('nom')
546 inflated = unpickler.restore(flattened)
547 assert obj == inflated
548
549
550 def test_references(pickler, unpickler):
551 """References in lists can roundtrip"""
552 obj_a = Thing('foo')
553 obj_b = Thing('bar')
554 coll = [obj_a, obj_b, obj_b]
555 flattened = pickler.flatten(coll)
556 inflated = unpickler.restore(flattened)
557 assert len(inflated) == len(coll)
558 for x in range(len(coll)):
559 assert repr(coll[x]) == repr(inflated[x])
560
561
562 def test_references_in_number_keyed_dict(pickler, unpickler):
563 """Dicts with numbers as keys and objects as values can roundtrip
564
565 Because JSON must coerce integers to strings in dict keys, the sort
566 order may have a tendency to change between pickling and unpickling,
567 and this could affect the object references.
568 """
569 one = Thing('one')
570 two = Thing('two')
571 twelve = Thing('twelve')
572 two.child = twelve
573 obj = {
574 1: one,
575 2: two,
576 12: twelve,
577 }
578 assert list(sorted(obj.keys())) != list(map(int, sorted(map(str, obj.keys()))))
579 flattened = pickler.flatten(obj)
580 inflated = unpickler.restore(flattened)
581 assert len(inflated) == 3
582 assert inflated['12'].name == 'twelve'
583
584
585 def test_builtin_error():
586 """Builtin errors can roundtrip"""
587 expect = AssertionError
588 json = jsonpickle.encode(expect)
589 actual = jsonpickle.decode(json)
590 assert expect == actual
591 assert expect is actual
592
593
594 def test_builtin_function():
595 """Builtin functions can roundtrip"""
596 expect = dir
597 json = jsonpickle.encode(expect)
598 actual = jsonpickle.decode(json)
599 assert expect == actual
600 assert expect is actual
601
602
603 def test_restore_legacy_builtins():
604 """Decoding is backwards compatible.
605
606 jsonpickle 0.9.6 and earlier used the Python 2 `__builtin__`
607 naming for builtins. Ensure those can be loaded until they're
608 no longer supported.
609 """
610 ae = jsonpickle.decode('{"py/type": "__builtin__.AssertionError"}')
611 assert ae is AssertionError
612 ae = jsonpickle.decode('{"py/type": "exceptions.AssertionError"}')
613 assert ae is AssertionError
614 cls = jsonpickle.decode('{"py/type": "__builtin__.int"}')
615 assert cls is int
616
617
618 @pytest.mark.parametrize(
619 'value,expect',
620 [
621 ('module_does_not_exist/ignored', None),
622 ('builtins/int', None),
623 ('builtins/invalid.int', None),
624 ('builtins/builtinsx.int', None),
625 ],
626 )
627 def test_restore_invalid_repr(value, expect, unpickler):
628 """Test restoring invalid repr tags"""
629 result = unpickler.restore({tags.REPR: value})
630 assert result is expect
631
632
633 def test_unpickler_on_missing():
634 """Emit warnings when decoding objects whose classes are missing"""
635 encoded = jsonpickle.encode(Outer.Middle.Inner())
636 assert isinstance(jsonpickle.decode(encoded), Outer.Middle.Inner)
637 # Alter the encoded string to create cases where the class is missing
638 # at multiple levels.
639 assert encoded == '{"py/object": "jsonpickle_test.Outer.Middle.Inner"}'
640 missing_cases = [
641 '{"py/object": "MISSING.Outer.Middle.Inner"}',
642 '{"py/object": "jsonpickle_test.MISSING.Middle.Inner"}',
643 '{"py/object": "jsonpickle_test.Outer.MISSING.Inner"}',
644 '{"py/object": "jsonpickle_test.Outer.Middle.MISSING"}',
645 ]
646 for case in missing_cases:
647 # https://docs.python.org/3/library/warnings.html#testing-warnings
648 with warnings.catch_warnings(record=True) as w:
649 warnings.simplefilter("always")
650 jsonpickle.decode(case, on_missing='warn')
651 assert issubclass(w[-1].category, UserWarning)
652 assert 'Unpickler._restore_object could not find' in str(w[-1].message)
653 jsonpickle.decode(case, on_missing=on_missing_callback)
654 assert issubclass(w[-1].category, RuntimeWarning)
655 assert 'The unpickler could not find' in str(w[-1].message)
656
657 assert jsonpickle.decode(
658 case, on_missing='ignore'
659 ) == jsonpickle.backend.json.loads(case)
660 try:
661 jsonpickle.decode(case, on_missing='error')
662 except jsonpickle.errors.ClassNotFoundError:
663 # it's supposed to error
664 assert True
665 else:
666 assert False
667
668
669 def test_private_slot_members():
670 """Objects with private slot members can roundtrip"""
671 obj = jsonpickle.loads(jsonpickle.dumps(MySlots()))
672 alpha = getattr(obj, 'alpha', '(missing alpha)')
673 beta = getattr(obj, '_' + obj.__class__.__name__ + '__beta', '(missing beta)')
674 assert alpha == beta
675
676
677 def test_include_properties_slots():
678 """Properties of slot-using objects are encoded with include_properties=True"""
679 obj = MyPropertiesSlots()
680 dumped = jsonpickle.dumps(obj, include_properties=True)
681 assert 'py/property' in dumped
682 assert jsonpickle.loads(dumped) == obj
683
684
685 def test_include_properties_dict():
686 """Dicts with properties are encoded with include_properties=True"""
687 obj = MyPropertiesDict()
688 dumped = jsonpickle.dumps(obj, include_properties=True)
689 assert 'py/property' in dumped
690 assert jsonpickle.loads(dumped) == obj
691
692
693 def test_load_non_fully_qualified_classes():
694 """Custom classes can be specified using string names when decoding"""
695 # reuse MyPropertiesSlots because it has a nice eq method
696 obj = MyPropertiesSlots()
697 encoded = jsonpickle.encode(obj)
698 # MyPropertiesSlots and MyPropertiesDict have compatible eq methods
699 decoded = jsonpickle.decode(
700 encoded, classes={'MyPropertiesSlots': MyPropertiesDict}
701 )
702 assert isinstance(decoded, MyPropertiesDict)
703 assert obj == decoded
704
705
706 def test_classes_dict():
707 """Custom classes can be used when decoding"""
708 # reuse MyPropertiesSlots because it has a nice eq method
709 obj = MyPropertiesSlots()
710 encoded = jsonpickle.encode(obj)
711 # MyPropertiesSlots and MyPropertiesDict have compatible eq methods
712 decoded = jsonpickle.decode(encoded, classes={MyPropertiesSlots: MyPropertiesDict})
713 assert isinstance(decoded, MyPropertiesDict)
714 assert obj == decoded
715
716
717 def test_warnings():
718 """Emit warnings when pickling file descriptors"""
719 data = os.fdopen(os.pipe()[0])
720 with warnings.catch_warnings(record=True) as w:
721 jsonpickle.encode(data, warn=True)
722 assert len(w) == 1
723 assert issubclass(w[-1].category, UserWarning)
724 assert "replaced with None" in str(w[-1].message)
725
726
727 def test_API_names():
728 """Enforce expected names in main module"""
729 names = list(vars(jsonpickle))
730 assert 'pickler' in names
731 assert 'unpickler' in names
732 assert 'JSONBackend' in names
733 assert '__version__' in names
734 assert 'register' in names
735 assert 'unregister' in names
736 assert 'Pickler' in names
737 assert 'Unpickler' in names
738 assert 'encode' in names
739 assert 'decode' in names
740
741
742 def test_encode():
743 """Encode an object with default settings"""
744 expect = Thing('A name')
745 pickle = jsonpickle.encode(expect)
746 actual = jsonpickle.decode(pickle)
747 assert expect.name == actual.name
748 assert expect.child == actual.child
749
750
751 def test_encode_notunpicklable():
752 """Encode an object with unpicklable=False"""
753 obj = Thing('A name')
754 expect = {'name': 'A name', 'child': None}
755 pickle = jsonpickle.encode(obj, unpicklable=False)
756 actual = jsonpickle.decode(pickle)
757 assert expect['name'] == actual['name']
758
759
760 def test_decode():
761 """Validate that we can decode a known json payload"""
762 expect = Thing('A name')
763 expected_json = (
764 '{"%s": "jsonpickle_test.Thing", "name": "A name", "child": null}' % tags.OBJECT
765 )
766 actual = jsonpickle.decode(expected_json)
767 assert expect.name == actual.name
768 assert type(expect) is type(actual)
769
770
771 def test_json():
772 """Validate the json representation"""
773 expect = Thing('A name')
774 expected_json = (
775 '{"%s": "jsonpickle_test.Thing", "name": "A name", "child": null}' % tags.OBJECT
776 )
777 pickle = jsonpickle.encode(expect)
778 actual = jsonpickle.decode(pickle)
779 assert actual.name == expect.name
780 assert actual.child == expect.child
781 actual = jsonpickle.decode(expected_json)
782 assert expect.name == actual.name
783 assert type(expect) is type(actual)
784
785
786 def test_unicode_dict_keys():
787 """Non-ascii unicode data in dict keys is preserved"""
788 uni = chr(0x1234)
789 pickle = jsonpickle.encode({uni: uni})
790 actual = jsonpickle.decode(pickle)
791 assert uni in actual
792 assert actual[uni] == uni
793
794
795 def test_tuple_dict_keys_default():
796 """Test that we handle dictionaries with tuples as keys."""
797 tuple_dict = {(1, 2): 3, (4, 5): {(7, 8): 9}}
798 pickle = jsonpickle.encode(tuple_dict)
799 expect = {'(1, 2)': 3, '(4, 5)': {'(7, 8)': 9}}
800 actual = jsonpickle.decode(pickle)
801 assert expect == actual
802 tuple_dict = {(1, 2): [1, 2]}
803 pickle = jsonpickle.encode(tuple_dict)
804 actual = jsonpickle.decode(pickle)
805 assert actual['(1, 2)'] == [1, 2]
806
807
808 def test_tuple_dict_keys_with_keys_enabled():
809 """Test that we handle dictionaries with tuples as keys."""
810 tuple_dict = {(1, 2): 3, (4, 5): {(7, 8): 9}}
811 pickle = jsonpickle.encode(tuple_dict, keys=True)
812 expect = tuple_dict
813 actual = jsonpickle.decode(pickle, keys=True)
814 assert expect == actual
815 tuple_dict = {(1, 2): [1, 2]}
816 pickle = jsonpickle.encode(tuple_dict, keys=True)
817 actual = jsonpickle.decode(pickle, keys=True)
818 assert actual[(1, 2)] == [1, 2]
819
820
821 def test_None_dict_key_default():
822 """None is stringified by default when used as a dict key"""
823 expect = {'null': None}
824 obj = {None: None}
825 pickle = jsonpickle.encode(obj)
826 actual = jsonpickle.decode(pickle)
827 assert expect == actual
828
829
830 def test_None_dict_key_with_keys_enabled():
831 """None can be used as a dict key when keys=True"""
832 expect = {None: None}
833 obj = {None: None}
834 pickle = jsonpickle.encode(obj, keys=True)
835 actual = jsonpickle.decode(pickle, keys=True)
836 assert expect == actual
837
838
839 def test_object_dict_keys():
840 """Test that we handle random objects as keys."""
841 thing = Thing('random')
842 pickle = jsonpickle.encode({thing: True})
843 actual = jsonpickle.decode(pickle)
844 assert actual == {'Thing("random")': True}
845
846
847 def test_int_dict_keys_defaults():
848 """Int keys are stringified by default"""
849 int_dict = {1000: [1, 2]}
850 pickle = jsonpickle.encode(int_dict)
851 actual = jsonpickle.decode(pickle)
852 assert actual['1000'] == [1, 2]
853
854
855 def test_int_dict_keys_with_keys_enabled():
856 """Int keys are supported with keys=True"""
857 int_dict = {1000: [1, 2]}
858 pickle = jsonpickle.encode(int_dict, keys=True)
859 actual = jsonpickle.decode(pickle, keys=True)
860 assert actual[1000] == [1, 2]
861
862
863 def test_string_key_requiring_escape_dict_keys_with_keys_enabled():
864 """Dict keys that require escaping are handled"""
865 json_key_dict = {tags.JSON_KEY + '6': [1, 2]}
866 pickled = jsonpickle.encode(json_key_dict, keys=True)
867 unpickled = jsonpickle.decode(pickled, keys=True)
868 assert unpickled[tags.JSON_KEY + '6'] == [1, 2]
869
870
871 def test_string_key_not_requiring_escape_dict_keys_with_keys_enabled():
872 """String keys that do not require escaping are not escaped"""
873 str_dict = {'name': [1, 2]}
874 pickled = jsonpickle.encode(str_dict, keys=True)
875 unpickled = jsonpickle.decode(pickled)
876 assert 'name' in unpickled
877
878
879 def test_dict_subclass():
880 """Dict subclasses can roundtrip"""
881 obj = UserDict()
882 obj.valid = True
883 obj.s = 'string'
884 obj.d = 'd_string'
885 obj['d'] = {}
886 obj['s'] = 'test'
887 pickle = jsonpickle.encode(obj)
888 actual = jsonpickle.decode(pickle)
889 assert type(actual) is UserDict
890 assert 'd' in actual
891 assert 's' in actual
892 assert hasattr(actual, 'd')
893 assert hasattr(actual, 's')
894 assert hasattr(actual, 'valid')
895 assert obj['d'] == actual['d']
896 assert obj['s'] == actual['s']
897 assert obj.d == actual.d
898 assert obj.s == actual.s
899 assert obj.valid == actual.valid
900
901
902 def test_dict_subclass_with_references():
903 """Dict subclasses with references can roundtrip"""
904 d = UserDict()
905 d.s = 'string'
906 d['s'] = 'test'
907 obj = [d, d, d.__dict__]
908 pickle = jsonpickle.encode(obj)
909 actual = jsonpickle.decode(pickle)
910 assert type(actual) is list
911 assert type(actual[0]) is UserDict
912 assert actual[0].s == 'string'
913 assert actual[0]['s'] == 'test'
914 assert actual[0] == actual[1]
915 assert actual[0].__dict__ == actual[2]
916
917
918 def test_list_of_objects():
919 """Using the same object in a list is preserved and not duplicated"""
920 a = Thing('a')
921 b = Thing('b')
922 pickle = jsonpickle.encode([a, b, b])
923 actual = jsonpickle.decode(pickle)
924 assert actual[1] == actual[2]
925 assert type(actual[0]) is Thing
926 assert actual[0].name == 'a'
927 assert actual[1].name == 'b'
928 assert actual[2].name == 'b'
929
930
931 def test_refs_keys_values():
932 """Objects in dict keys can roundtrip"""
933 j = Thing('random')
934 object_dict = {j: j}
935 pickle = jsonpickle.encode(object_dict, keys=True)
936 actual = jsonpickle.decode(pickle, keys=True)
937 assert list(actual.values()) == list(actual.keys())
938
939
940 def test_object_keys_to_list():
941 """Objects in dict values have their references preserved"""
942 j = Thing('random')
943 object_dict = {j: [j, j]}
944 pickle = jsonpickle.encode(object_dict, keys=True)
945 actual = jsonpickle.decode(pickle, keys=True)
946 obj = list(actual.keys())[0]
947 assert obj.name == j.name
948 assert obj is actual[obj][0]
949 assert obj is actual[obj][1]
950
951
952 def test_refs_in_objects():
953 """Objects in lists have their references preserved"""
954 a = Thing('a')
955 b = Thing('b')
956 pickle = jsonpickle.encode([a, b, b])
957 actual = jsonpickle.decode(pickle)
958 assert actual[0] != actual[1]
959 assert actual[1] == actual[2]
960 assert actual[1] is actual[2]
961
962
963 def test_refs_recursive():
964 """Complicated recursive refs can roundtrip"""
965 a = Thing('a')
966 a.self_list = [Thing('0'), Thing('1'), Thing('2')]
967 a.first = a.self_list[0]
968 a.stuff = {a.first: a.first}
969 a.morestuff = {a.self_list[1]: a.stuff}
970 pickle = jsonpickle.encode(a, keys=True)
971 b = jsonpickle.decode(pickle, keys=True)
972 item = b.self_list[0]
973 assert item == b.first
974 assert item == b.stuff[b.first]
975 assert item == b.morestuff[b.self_list[1]][b.first]
976
977
978 def test_load_backend():
979 """Ensures that load_backend() is working"""
980 assert jsonpickle.load_backend('simplejson', 'dumps', 'loads', ValueError)
981
982
983 def test_set_preferred_backend_allows_magic():
984 """Pluggable backends can be used"""
985 backend = 'os.path'
986 jsonpickle.load_backend(backend, 'split', 'join', AttributeError)
987 jsonpickle.set_preferred_backend(backend)
988 slash_hello, world = jsonpickle.encode('/hello/world')
989 jsonpickle.remove_backend(backend)
990
991 assert slash_hello == '/hello'
992 assert world == 'world'
993
994
995 def test_load_backend_submodule():
996 """Inner modules can be used as a backend"""
997 jsonpickle.load_backend('os.path', 'split', 'join', AttributeError)
998 assert (
999 'os.path' in jsonpickle.json._backend_names
1000 and 'os.path' in jsonpickle.json._encoders
1001 and 'os.path' in jsonpickle.json._decoders
1002 and 'os.path' in jsonpickle.json._encoder_options
1003 and 'os.path' in jsonpickle.json._decoder_exceptions
1004 )
1005 jsonpickle.remove_backend('os.path')
1006
1007
1008 def _backend_is_partially_loaded(backend):
1009 """Return True if the specified backend is incomplete"""
1010 return (
1011 backend in jsonpickle.json._backend_names
1012 or backend in jsonpickle.json._encoders
1013 or backend in jsonpickle.json._decoders
1014 or backend in jsonpickle.json._encoder_options
1015 or backend in jsonpickle.json._decoder_exceptions
1016 )
1017
1018
1019 def test_load_backend_handles_bad_encode():
1020 """Ignore bad encoders"""
1021 load_backend = jsonpickle.load_backend
1022 assert not load_backend('os.path', 'bad!', 'split', AttributeError)
1023 assert not _backend_is_partially_loaded('os.path')
1024
1025
1026 def test_load_backend_raises_on_bad_decode():
1027 """Ignore bad decoders"""
1028 load_backend = jsonpickle.load_backend
1029 assert not load_backend('os.path', 'join', 'bad!', AttributeError)
1030 assert not _backend_is_partially_loaded('os.path')
1031
1032
1033 def test_load_backend_handles_bad_loads_exc():
1034 """Ignore bad decoder exceptions"""
1035 load_backend = jsonpickle.load_backend
1036 assert not load_backend('os.path', 'join', 'split', 'bad!')
1037 assert not _backend_is_partially_loaded('os.path')
1038
1039
1040 def test_list_item_reference():
1041 """References to objects inside lists are preserved"""
1042 thing = Thing('parent')
1043 thing.child = Thing('child')
1044 thing.child.refs = [thing]
1045 encoded = jsonpickle.encode(thing)
1046 decoded = jsonpickle.decode(encoded)
1047 assert id(decoded) == id(decoded.child.refs[0])
1048
1049
1050 def test_reference_to_list():
1051 """References to lists are preserved"""
1052 thing = Thing('parent')
1053 thing.a = [1]
1054 thing.b = thing.a
1055 thing.b.append(thing.a)
1056 thing.b.append([thing.a])
1057 encoded = jsonpickle.encode(thing)
1058 decoded = jsonpickle.decode(encoded)
1059 assert 1 == decoded.a[0]
1060 assert 1 == decoded.b[0]
1061 assert id(decoded.b) == id(decoded.a)
1062 assert id(decoded.a[1]) == id(decoded.a)
1063 assert id(decoded.a[2][0]) == id(decoded.a)
1064
1065
1066 def test_make_refs_disabled_list():
1067 """Lists are duplicated when make_refs is False"""
1068 obj_a = Thing('foo')
1069 obj_b = Thing('bar')
1070 coll = [obj_a, obj_b, obj_b]
1071 encoded = jsonpickle.encode(coll, make_refs=False)
1072 decoded = jsonpickle.decode(encoded)
1073
1074 assert len(decoded) == 3
1075 assert decoded[0] is not decoded[1]
1076 assert decoded[1] is not decoded[2]
1077
1078
1079 def test_make_refs_disabled_reference_to_list():
1080 """References are lost when maek_refs is False"""
1081 thing = Thing('parent')
1082 thing.a = [1]
1083 thing.b = thing.a
1084 thing.b.append(thing.a)
1085 thing.b.append([thing.a])
1086 encoded = jsonpickle.encode(thing, make_refs=False)
1087 decoded = jsonpickle.decode(encoded)
1088 assert decoded.a[0] == 1
1089 assert decoded.b[0] == 1
1090 assert decoded.a[1][0:3] == '[1,' # ]
1091 assert decoded.a[2][0][0:3] == '[1,' # ]
1092
1093
1094 def test_can_serialize_inner_classes():
1095 """Specify hidden classes when decoding"""
1096
1097 class InnerScope:
1098 """Private class visible to this method only"""
1099
1100 def __init__(self, name):
1101 self.name = name
1102
1103 obj = InnerScope('test')
1104 encoded = jsonpickle.encode(obj)
1105 # Single class
1106 decoded = jsonpickle.decode(encoded, classes=InnerScope)
1107 _test_inner_class(InnerScope, obj, decoded)
1108 # List of classes
1109 decoded = jsonpickle.decode(encoded, classes=[InnerScope])
1110 _test_inner_class(InnerScope, obj, decoded)
1111 # Tuple of classes
1112 decoded = jsonpickle.decode(encoded, classes=(InnerScope,))
1113 _test_inner_class(InnerScope, obj, decoded)
1114 # Set of classes
1115 decoded = jsonpickle.decode(encoded, classes={InnerScope})
1116 _test_inner_class(InnerScope, obj, decoded)
1117
1118
1119 def _test_inner_class(cls, obj, decoded):
1120 assert isinstance(obj, cls)
1121 assert decoded.name == obj.name
1122
1123
1124 def test_can_serialize_nested_classes():
1125 """Instances of nested classes can roundtrip"""
1126 middle = Outer.Middle
1127 inner = Outer.Middle.Inner
1128 encoded_middle = jsonpickle.encode(middle)
1129 encoded_inner = jsonpickle.encode(inner)
1130 decoded_middle = jsonpickle.decode(encoded_middle)
1131 decoded_inner = jsonpickle.decode(encoded_inner)
1132
1133 assert isinstance(decoded_middle, type)
1134 assert isinstance(decoded_inner, type)
1135 assert decoded_middle == middle
1136 assert decoded_inner == inner
1137
1138
1139 def test_can_serialize_nested_class_objects():
1140 """Class objects in an inner scope can roundtrip"""
1141 middle_obj = Outer.Middle()
1142 middle_obj.attribute = 5
1143 inner_obj = Outer.Middle.Inner()
1144 inner_obj.attribute = 6
1145 encoded_middle_obj = jsonpickle.encode(middle_obj)
1146 encoded_inner_obj = jsonpickle.encode(inner_obj)
1147 decoded_middle_obj = jsonpickle.decode(encoded_middle_obj)
1148 decoded_inner_obj = jsonpickle.decode(encoded_inner_obj)
1149 assert isinstance(decoded_middle_obj, Outer.Middle)
1150 assert isinstance(decoded_inner_obj, Outer.Middle.Inner)
1151 assert middle_obj.attribute == decoded_middle_obj.attribute
1152 assert inner_obj.attribute == decoded_inner_obj.attribute
1153
1154
1155 def test_listlike():
1156 """List-like objects can roundtrip"""
1157 # https://github.com/jsonpickle/jsonpickle/issues/362
1158 ll = ListLike()
1159 ll.internal_list.append(1)
1160 roundtrip_ll = jsonpickle.decode(jsonpickle.encode(ll))
1161 assert len(roundtrip_ll.internal_list) == len(ll.internal_list)
1162
1163
1164 def test_v1_decode():
1165 # TODO: Find a simple example that reproduces #364
1166 assert True
1167
1168
1169 def test_depth_tracking(pickler):
1170 liszt = []
1171 pickler.flatten([liszt, liszt, liszt, liszt, liszt])
1172 assert pickler._depth == -1
1173
1174
1175 def test_readonly_attrs():
1176 """Objects with readonly attributes can roundtrip"""
1177 safe_str = SafeString('test')
1178 pickled = jsonpickle.encode(safe_str, handle_readonly=True)
1179 pickled_json_dict = jsonpickle.backend.json.loads(pickled)
1180 # make sure it's giving concise output by erroring if it includes
1181 # a default method which is unnecessary
1182 assert 'join' not in pickled_json_dict
1183 unpickled = jsonpickle.decode(pickled)
1184 assert SafeString == unpickled.__class__
1185 assert safe_str == unpickled
1186
1187
1188 def test_readonly_str_attrs():
1189 """Objects with readonly string attributes can roundtrip"""
1190 safe_str = SafeString('test')
1191 # We'll first try setting handle_readonly=True when encoding.
1192 encoded = jsonpickle.encode(safe_str, handle_readonly=True)
1193 actual = jsonpickle.decode(encoded, handle_readonly=True)
1194 assert safe_str == actual
1195 # Next we'll ensure that we can decode a payload that contains readonly attributes
1196 # by omitting the handle_readonly option when pickling.
1197 encoded = jsonpickle.encode(safe_str)
1198 actual = jsonpickle.decode(encoded, handle_readonly=True)
1199 assert safe_str == actual
1200
1201
1202 class PicklableNamedTuple:
1203 """A namedtuple wrapper that uses ``__getnewargs__``
1204
1205 Demonstrates the need for protocol 2 compatibility.
1206 This is contrived in its use of new but it demonstrates the issue.
1207 """
1208
1209 def __new__(cls, propnames, vals):
1210 # it's necessary to use the correct class name for class resolution
1211 # classes that fake their own names may never be unpicklable
1212 ntuple = collections.namedtuple(cls.__name__, propnames)
1213 ntuple.__getnewargs__ = lambda self: (propnames, vals)
1214 instance = ntuple.__new__(ntuple, *vals)
1215 return instance
1216
1217
1218 class PicklableNamedTupleEx:
1219 """A namedtuple wrapper that uses ``__getnewargs__`` and ``__getnewargs_ex__``
1220
1221 Demonstrates the need for protocol 4 compatibility.
1222 This is contrived in its use of new but it demonstrates the issue.
1223 """
1224
1225 def __getnewargs__(self):
1226 raise NotImplementedError("This class needs __getnewargs_ex__")
1227
1228 def __new__(cls, newargs=__getnewargs__, **kwargs):
1229 # it's necessary to use the correct class name for class resolution
1230 # classes that fake their own names may never be unpicklable
1231 ntuple = collections.namedtuple(cls.__name__, sorted(kwargs.keys()))
1232 ntuple.__getnewargs_ex__ = lambda self: ((), kwargs)
1233 ntuple.__getnewargs__ = newargs
1234 instance = ntuple.__new__(ntuple, *[b for a, b in sorted(kwargs.items())])
1235 return instance
1236
1237
1238 class PickleProtocol2Thing:
1239 """An object that implements ``__getnewargs__`` for pickle protocol v2"""
1240
1241 def __init__(self, *args):
1242 self.args = args
1243
1244 def __getnewargs__(self):
1245 return self.args
1246
1247 def __eq__(self, other):
1248 """
1249 Make PickleProtocol2Thing('slotmagic') ==
1250 PickleProtocol2Thing('slotmagic')
1251 """
1252 if self.__dict__ == other.__dict__ and dir(self) == dir(other):
1253 for prop in dir(self):
1254 selfprop = getattr(self, prop)
1255 if not callable(selfprop) and prop[0] != '_':
1256 if selfprop != getattr(other, prop):
1257 return False
1258 return True
1259 else:
1260 return False
1261
1262
1263 # these two instances are used below and in tests
1264 slotmagic = PickleProtocol2Thing('slotmagic')
1265 dictmagic = PickleProtocol2Thing('dictmagic')
1266
1267
1268 class PickleProtocol2GetState(PickleProtocol2Thing):
1269 """An object whose ``__getstate__`` returns a string"""
1270
1271 def __new__(cls, *args):
1272 instance = super().__new__(cls)
1273 instance.newargs = args
1274 return instance
1275
1276 def __getstate__(self):
1277 return 'I am magic'
1278
1279
1280 class PickleProtocol2GetStateDict(PickleProtocol2Thing):
1281 """An object whose ``__getstate__`` returns a regular dict"""
1282
1283 def __getstate__(self):
1284 return {'magic': True}
1285
1286
1287 class PickleProtocol2GetStateNestedDict(PickleProtocol2Thing):
1288 """An object whose ``__getstate__`` returns a nested dict"""
1289
1290 def __getstate__(self):
1291 return {'nested': {'magic': True}}
1292
1293
1294 class PickleProtocol2GetStateSlots(PickleProtocol2Thing):
1295 """An object whose ``__getstate__`` return a tuple containing None and slot data"""
1296
1297 def __getstate__(self):
1298 return (None, {'slotmagic': slotmagic})
1299
1300
1301 class PickleProtocol2GetStateSlotsDict(PickleProtocol2Thing):
1302 """An object whose ``__getstate__`` return a tuple containing dict and slot data"""
1303
1304 def __getstate__(self):
1305 return ({'dictmagic': dictmagic}, {'slotmagic': slotmagic})
1306
1307
1308 class PickleProtocol2GetSetState(PickleProtocol2GetState):
1309 """An object whose ``__setstate__`` detects specific strings"""
1310
1311 def __setstate__(self, state):
1312 """Contrived example, easy to test"""
1313 if state == 'I am magic':
1314 self.magic = True
1315 else:
1316 self.magic = False
1317
1318
1319 class PickleProtocol2ChildThing:
1320 """Provides ``__getnewargs__`` for pickle protocol v2"""
1321
1322 def __init__(self, child):
1323 self.child = child
1324
1325 def __getnewargs__(self):
1326 return ([self.child],)
1327
1328
1329 class PickleProtocol2ReduceString:
1330 """A reducible object that implements ``__reduce__`` only"""
1331
1332 def __reduce__(self):
1333 return __name__ + '.slotmagic'
1334
1335
1336 class PickleProtocol2ReduceExString:
1337 """A reducible object that implements both ``__reduce_ex__`` and ``__reduce__``"""
1338
1339 def __reduce_ex__(self, n):
1340 return __name__ + '.slotmagic'
1341
1342 def __reduce__(self):
1343 """This method is ignored"""
1344 assert False, 'Should not be here'
1345
1346
1347 class PickleProtocol2ReduceTuple:
1348 """A reducible object that returns the PickleProtocol2ReduceTuple callable"""
1349
1350 def __init__(self, argval, optional=None):
1351 self.argval = argval
1352 self.optional = optional
1353
1354 def __reduce__(self):
1355 return (
1356 PickleProtocol2ReduceTuple, # callable
1357 ('yam', 1), # args
1358 None, # state
1359 iter([]), # listitems
1360 iter([]), # dictitems
1361 )
1362
1363
1364 class ReducibleIterator:
1365 """A reducible iterator"""
1366
1367 def __next__(self):
1368 raise StopIteration()
1369
1370 def __iter__(self):
1371 return self
1372
1373 def __reduce__(self):
1374 return ReducibleIterator, ()
1375
1376
1377 def protocol_2_reduce_tuple_func(*args):
1378 """Return a pickle protocol v2 reducer"""
1379 return PickleProtocol2ReduceTupleFunc(*args)
1380
1381
1382 class PickleProtocol2ReduceTupleFunc:
1383 """A reducible object with args and optional state"""
1384
1385 def __init__(self, argval, optional=None):
1386 self.argval = argval
1387 self.optional = optional
1388
1389 def __reduce__(self):
1390 return (
1391 protocol_2_reduce_tuple_func, # callable
1392 ('yam', 1), # args
1393 None, # state
1394 iter([]), # listitems
1395 iter([]), # dictitems
1396 )
1397
1398
1399 def __newobj__(lol, fail):
1400 """newobj is special-cased so that it is not actually called"""
1401
1402
1403 class PickleProtocol2ReduceNewobj(PickleProtocol2ReduceTupleFunc):
1404 """Reducible object that return the ``__newobj__`` callable and args"""
1405
1406 def __new__(cls, *args):
1407 inst = super(cls, cls).__new__(cls)
1408 inst.newargs = args
1409 return inst
1410
1411 def __reduce__(self):
1412 return (
1413 __newobj__, # callable
1414 (PickleProtocol2ReduceNewobj, 'yam', 1), # args
1415 None, # state
1416 iter([]), # listitems
1417 iter([]), # dictitems
1418 )
1419
1420
1421 class PickleProtocol2ReduceTupleState(PickleProtocol2ReduceTuple):
1422 """Reducible object with args and state"""
1423
1424 def __reduce__(self):
1425 return (
1426 PickleProtocol2ReduceTuple, # callable
1427 ('yam', 1), # args
1428 {'foo': 1}, # state
1429 iter([]), # listitems
1430 iter([]), # dictitems
1431 )
1432
1433
1434 class PickleProtocol2ReduceTupleSetState(PickleProtocol2ReduceTuple):
1435 """Reducible object with args and state that implements ``__setstate__``"""
1436
1437 def __reduce__(self):
1438 return (
1439 type(self), # callable
1440 ('yam', 1), # args
1441 {'foo': 1}, # state
1442 iter([]), # listitems
1443 iter([]), # dictitems
1444 )
1445
1446 def __setstate__(self, state):
1447 self.bar = state['foo']
1448
1449
1450 class PickleProtocol2ReduceTupleStateSlots:
1451 """Reducible object with tuple ``__slots__``"""
1452
1453 __slots__ = ('argval', 'optional', 'foo')
1454
1455 def __init__(self, argval, optional=None):
1456 self.argval = argval
1457 self.optional = optional
1458
1459 def __reduce__(self):
1460 return (
1461 PickleProtocol2ReduceTuple, # callable
1462 ('yam', 1), # args
1463 {'foo': 1}, # state
1464 iter([]), # listitems
1465 iter([]), # dictitems
1466 )
1467
1468
1469 class PickleProtocol2ReduceListitemsAppend:
1470 """A reducible object that only implements append()"""
1471
1472 def __init__(self):
1473 self.inner = []
1474
1475 def append(self, item):
1476 self.inner.append(item)
1477
1478 def __reduce__(self):
1479 return (
1480 PickleProtocol2ReduceListitemsAppend, # callable
1481 (), # args
1482 {}, # state
1483 iter(['foo', 'bar']), # listitems
1484 iter([]), # dictitems
1485 )
1486
1487
1488 class PickleProtocol2ReduceListitemsExtend:
1489 """A reducible object that only implements extend()"""
1490
1491 def __init__(self):
1492 self.inner = []
1493
1494 def extend(self, items):
1495 self.inner.exend(items)
1496
1497 def __reduce__(self):
1498 return (
1499 PickleProtocol2ReduceListitemsAppend, # callable
1500 (), # args
1501 {}, # state
1502 iter(['foo', 'bar']), # listitems
1503 iter([]), # dictitems
1504 )
1505
1506
1507 class PickleProtocol2ReduceDictitems:
1508 """A reducible object with dictitems that implements ``__setitem__``"""
1509
1510 def __init__(self):
1511 self.inner = {}
1512
1513 def __setitem__(self, k, v):
1514 return self.inner.__setitem__(k, v)
1515
1516 def __reduce__(self):
1517 return (
1518 PickleProtocol2ReduceDictitems, # callable
1519 (), # args
1520 {}, # state
1521 [], # listitems
1522 iter(zip(['foo', 'bar'], ['foo', 'bar'])), # dictitems
1523 )
1524
1525
1526 def test_pickle_newargs_ex():
1527 """
1528 Ensure we can pickle and unpickle an object whose class needs arguments
1529 to __new__ and get back the same type
1530 """
1531 instance = PicklableNamedTupleEx(**{'a': 'b', 'n': 2})
1532 encoded = jsonpickle.encode(instance)
1533 decoded = jsonpickle.decode(encoded)
1534 assert instance == decoded
1535
1536
1537 def test_validate_reconstruct_by_newargs_ex():
1538 """
1539 Ensure that the exemplar tuple's __getnewargs_ex__ works
1540 This is necessary to know whether the breakage exists
1541 in jsonpickle or not
1542 """
1543 instance = PicklableNamedTupleEx(**{'a': 'b', 'n': 2})
1544 args, kwargs = instance.__getnewargs_ex__()
1545 newinstance = PicklableNamedTupleEx.__new__(PicklableNamedTupleEx, *args, **kwargs)
1546 assert instance == newinstance
1547
1548
1549 def test_references_named_tuple():
1550 """Object references and identities are preserved inside a named tuple"""
1551 shared = Thing('shared')
1552 instance = PicklableNamedTupleEx(**{'a': shared, 'n': shared})
1553 child = Thing('child')
1554 shared.child = child
1555 child.child = instance
1556 encoded = jsonpickle.encode(instance)
1557 decoded = jsonpickle.decode(encoded)
1558 assert decoded[0] == decoded[1]
1559 assert decoded[0] is decoded[1]
1560 assert decoded.a is decoded.n
1561 assert decoded.a.name == 'shared'
1562 assert decoded.a.child.name == 'child'
1563 assert decoded.a.child.child is decoded
1564 assert decoded.n.child.child is decoded
1565 assert decoded.a.child is decoded.n.child
1566 assert decoded.__class__.__name__ == PicklableNamedTupleEx.__name__
1567 # TODO the class itself looks just like the real class, but it's
1568 # actually a reconstruction; PicklableNamedTupleEx is not type(decoded).
1569 assert decoded.__class__ is not PicklableNamedTupleEx
1570
1571
1572 def test_reduce_complex_num():
1573 """Test complex/imaginary numbers"""
1574 instance = 5j
1575 encoded = jsonpickle.encode(instance)
1576 decoded = jsonpickle.decode(encoded)
1577 assert decoded == instance
1578
1579
1580 def test_reduce_complex_zero():
1581 """Test complex/imaginary zero"""
1582 instance = 0j
1583 encoded = jsonpickle.encode(instance)
1584 decoded = jsonpickle.decode(encoded)
1585 assert decoded == instance
1586
1587
1588 def test_reduce_dictitems():
1589 """Test reduce with dictitems set (as a generator)"""
1590 instance = PickleProtocol2ReduceDictitems()
1591 encoded = jsonpickle.encode(instance)
1592 decoded = jsonpickle.decode(encoded)
1593 assert decoded.inner == {'foo': 'foo', 'bar': 'bar'}
1594
1595
1596 def test_reduce_listitems_extend():
1597 """Test reduce with listitems set (as a generator), yielding single items"""
1598 instance = PickleProtocol2ReduceListitemsExtend()
1599 encoded = jsonpickle.encode(instance)
1600 decoded = jsonpickle.decode(encoded)
1601 assert decoded.inner == ['foo', 'bar']
1602
1603
1604 def test_reduce_listitems_append():
1605 """Test reduce with listitems set (as a generator), yielding single items"""
1606 instance = PickleProtocol2ReduceListitemsAppend()
1607 encoded = jsonpickle.encode(instance)
1608 decoded = jsonpickle.decode(encoded)
1609 assert decoded.inner == ['foo', 'bar']
1610
1611
1612 def test_reduce_state_setstate():
1613 """Objects with ``__setstate__`` and optional state arguments can roundtrip"""
1614 instance = PickleProtocol2ReduceTupleSetState(5)
1615 encoded = jsonpickle.encode(instance)
1616 decoded = jsonpickle.decode(encoded)
1617 assert decoded.argval == 'yam'
1618 assert decoded.optional == 1
1619 assert decoded.bar == 1
1620 assert not hasattr(decoded, 'foo')
1621
1622
1623 def test_reduce_state_no_dict():
1624 """Objects with state but without `__dict__`` and ``__setstate__`` can roundtrip"""
1625 instance = PickleProtocol2ReduceTupleStateSlots(5)
1626 encoded = jsonpickle.encode(instance)
1627 decoded = jsonpickle.decode(encoded)
1628 assert decoded.argval == 'yam'
1629 assert decoded.optional == 1
1630 assert decoded.foo == 1
1631
1632
1633 def test_reduce_state_dict():
1634 """Reduce an object with __dict__ and no __setstate__"""
1635 instance = PickleProtocol2ReduceTupleState(5)
1636 encoded = jsonpickle.encode(instance)
1637 decoded = jsonpickle.decode(encoded)
1638 assert decoded.argval == 'yam'
1639 assert decoded.optional == 1
1640 assert decoded.foo == 1
1641
1642
1643 def test_reduce_basic():
1644 """Reduce an object with callable and args only"""
1645 instance = PickleProtocol2ReduceTuple(5)
1646 encoded = jsonpickle.encode(instance)
1647 decoded = jsonpickle.decode(encoded)
1648 assert decoded.argval == 'yam'
1649 assert decoded.optional == 1
1650
1651
1652 def test_reduce_basic_func():
1653 """Reduce an object with args and a module-level callable"""
1654 instance = PickleProtocol2ReduceTupleFunc(5)
1655 encoded = jsonpickle.encode(instance)
1656 decoded = jsonpickle.decode(encoded)
1657 assert decoded.argval == 'yam'
1658 assert decoded.optional == 1
1659
1660
1661 def test_reduce_newobj():
1662 """Reduce an object with a callable __newobj__"""
1663 instance = PickleProtocol2ReduceNewobj(5)
1664 encoded = jsonpickle.encode(instance)
1665 decoded = jsonpickle.decode(encoded)
1666 assert decoded.newargs == ('yam', 1)
1667
1668
1669 def test_reduce_iter():
1670 """Iterators with ``__reduce__`` can roundtrip"""
1671 instance = iter('123')
1672 assert util.is_iterator(instance)
1673 encoded = jsonpickle.encode(instance)
1674 decoded = jsonpickle.decode(encoded)
1675 assert next(decoded) == '1'
1676 assert next(decoded) == '2'
1677 assert next(decoded) == '3'
1678
1679
1680 def test_reduce_iterable():
1681 """Reducible objects that are iterable should also pickle"""
1682 instance = ReducibleIterator()
1683 assert util.is_iterator(instance)
1684 encoded = jsonpickle.encode(instance)
1685 decoded = jsonpickle.decode(encoded)
1686 assert isinstance(decoded, ReducibleIterator)
1687
1688
1689 def test_reduce_string():
1690 """Handle redirection to another object when ``__reduce__`` returns a string"""
1691 instance = PickleProtocol2ReduceString()
1692 encoded = jsonpickle.encode(instance)
1693 decoded = jsonpickle.decode(encoded)
1694 assert decoded == slotmagic
1695
1696
1697 def test_reduce_ex_string():
1698 """Handle redirection to another object when ``__reduce_ex__`` returns a string
1699
1700 Ensure that ``__reduce_ex__`` has higher priority than ``__reduce__``.
1701 """
1702 instance = PickleProtocol2ReduceExString()
1703 encoded = jsonpickle.encode(instance)
1704 decoded = jsonpickle.decode(encoded)
1705 assert decoded == slotmagic
1706
1707
1708 def test_pickle_newargs():
1709 """Objects whose class needs arguments to ``__new__`` can roundtrip"""
1710 instance = PicklableNamedTuple(('a', 'b'), (1, 2))
1711 encoded = jsonpickle.encode(instance)
1712 decoded = jsonpickle.decode(encoded)
1713 assert instance == decoded
1714
1715
1716 def test_validate_reconstruct_by_newargs():
1717 """Validate PicklableNamedTuple's Python semantics
1718
1719 Ensure that the exemplar tuple's __getnewargs__ works This is necessary to
1720 know whether potential breakage exists in jsonpickle or in the test class.
1721 """
1722 instance = PicklableNamedTuple(('a', 'b'), (1, 2))
1723 newinstance = PicklableNamedTuple.__new__(
1724 PicklableNamedTuple, *(instance.__getnewargs__())
1725 )
1726 assert instance == newinstance
1727
1728
1729 def test_getnewargs_priority():
1730 """newargs must be used before py/state when decoding
1731
1732 As per PEP 307, classes are not supposed to implement
1733 all three magic methods.
1734 """
1735 instance = PickleProtocol2GetState('whatevs')
1736 encoded = jsonpickle.encode(instance)
1737 decoded = jsonpickle.decode(encoded)
1738 assert decoded.newargs == ('whatevs',)
1739
1740
1741 def test_restore_dict_state():
1742 """getstate without setstate can roundtrip
1743
1744 If ``__getstate__`` returns a dict and there is no custom ``__setstate__`` then the
1745 dict is used as a source of variables to restore.
1746 """
1747 instance = PickleProtocol2GetStateDict('whatevs')
1748 encoded = jsonpickle.encode(instance)
1749 decoded = jsonpickle.decode(encoded)
1750 assert decoded.magic
1751
1752
1753 def test_restore_nested_dict_state_with_references_preserved():
1754 """Nested dicts in "py/state" retain references and are not duplicated"""
1755 instance1 = PickleProtocol2GetStateNestedDict('whatevs')
1756 instance2 = PickleProtocol2GetStateNestedDict('different')
1757 encoded = jsonpickle.encode([instance1, instance1, instance2, instance2])
1758 decoded = jsonpickle.decode(encoded)
1759 assert decoded[0].nested['magic']
1760 assert decoded[1] is decoded[0]
1761 assert decoded[2].nested['magic']
1762 assert decoded[3] is decoded[2]
1763
1764
1765 def test_restore_slots_state():
1766 """Serialize objects with __slots__
1767
1768 Ensure that if getstate returns a 2-tuple with a dict in the second
1769 position, and there is no custom __setstate__, the dict is used as a
1770 source of variables to restore.
1771 """
1772 instance = PickleProtocol2GetStateSlots('whatevs')
1773 encoded = jsonpickle.encode(instance)
1774 decoded = jsonpickle.decode(encoded)
1775 assert decoded.slotmagic.__dict__ == slotmagic.__dict__
1776 assert decoded.slotmagic == slotmagic
1777
1778
1779 def test_restore_slots_dict_state():
1780 """getstate with dicts in both positions can roundtrip
1781
1782 If ``__getstate__`` returns a 2-tuple with a dict in both positions,
1783 and there is no custom ``__setstate__``, the dicts are used as a source of
1784 variables to restore.
1785 """
1786 instance = PickleProtocol2GetStateSlotsDict('whatevs')
1787 encoded = jsonpickle.encode(instance)
1788 decoded = jsonpickle.decode(encoded)
1789 assert PickleProtocol2Thing('slotmagic') == PickleProtocol2Thing('slotmagic')
1790 assert decoded.slotmagic.__dict__ == slotmagic.__dict__
1791 assert decoded.slotmagic == slotmagic
1792 assert decoded.dictmagic == dictmagic
1793
1794
1795 def test_setstate():
1796 """Ensure output of getstate is passed to setstate"""
1797 instance = PickleProtocol2GetSetState('whatevs')
1798 encoded = jsonpickle.encode(instance)
1799 decoded = jsonpickle.decode(encoded)
1800 assert decoded.magic
1801
1802
1803 def test_handles_nested_objects():
1804 """Nested objects can roundtrip"""
1805 child = PickleProtocol2Thing(None)
1806 instance = PickleProtocol2Thing(child, child)
1807 encoded = jsonpickle.encode(instance)
1808 decoded = jsonpickle.decode(encoded)
1809 assert PickleProtocol2Thing == decoded.__class__
1810 assert PickleProtocol2Thing == decoded.args[0].__class__
1811 assert PickleProtocol2Thing == decoded.args[1].__class__
1812 assert decoded.args[0] is decoded.args[1]
1813
1814
1815 def test_cyclical_objects():
1816 """Cyclical objects with inner tuples and lists can roundtrip"""
1817 _test_cyclical_objects(True)
1818 _test_cyclical_objects(False)
1819
1820
1821 def _test_cyclical_objects(use_tuple):
1822 child = Capture(None)
1823 instance = Capture(child, child)
1824 # create a cycle
1825 if use_tuple:
1826 child.args = (instance,)
1827 else:
1828 child.args = [instance]
1829 encoded = jsonpickle.encode(instance)
1830 decoded = jsonpickle.decode(encoded)
1831 # Ensure the right objects were constructed
1832 assert Capture == decoded.__class__
1833 assert Capture == decoded.args[0].__class__
1834 assert Capture == decoded.args[1].__class__
1835 assert Capture == decoded.args[0].args[0].__class__
1836 assert Capture == decoded.args[1].args[0].__class__
1837 # It's turtles all the way down
1838 assert (
1839 Capture
1840 == decoded.args[0]
1841 .args[0]
1842 .args[0]
1843 .args[0]
1844 .args[0]
1845 .args[0]
1846 .args[0]
1847 .args[0]
1848 .args[0]
1849 .args[0]
1850 .args[0]
1851 .args[0]
1852 .args[0]
1853 .args[0]
1854 .args[0]
1855 .__class__
1856 )
1857 # Ensure that references are properly constructed
1858 assert decoded.args[0] is decoded.args[1]
1859 assert decoded is decoded.args[0].args[0]
1860 assert decoded is decoded.args[1].args[0]
1861 assert decoded.args[0] is decoded.args[0].args[0].args[0]
1862 assert decoded.args[0] is decoded.args[1].args[0].args[0]
1863
1864
1865 def test_handles_cyclical_objects_in_lists():
1866 """Cyclical objects in lists can roundtrip"""
1867 child = PickleProtocol2ChildThing(None)
1868 instance = PickleProtocol2ChildThing([child, child])
1869 child.child = instance # create a cycle
1870 encoded = jsonpickle.encode(instance)
1871 decoded = jsonpickle.decode(encoded)
1872 assert decoded is decoded.child[0].child
1873 assert decoded is decoded.child[1].child
1874
1875
1876 def test_cyclical_objects_unpickleable():
1877 """Cyclical objects can roundtrip with their references retained"""
1878 _test_cyclical_objects_unpickleable(True)
1879 _test_cyclical_objects_unpickleable(False)
1880
1881
1882 def _test_cyclical_objects_unpickleable(use_tuple):
1883 child = Capture(None)
1884 instance = Capture(child, child)
1885 # create a cycle
1886 if use_tuple:
1887 child.args = (instance,)
1888 else:
1889 child.args = [instance]
1890 encoded = jsonpickle.encode(instance, unpicklable=False)
1891 decoded = jsonpickle.decode(encoded)
1892 assert isinstance(decoded, dict)
1893 assert 'args' in decoded
1894 assert 'kwargs' in decoded
1895 # Tuple is lost via json
1896 args = decoded['args']
1897 assert isinstance(args, list)
1898 # Get the children
1899 assert len(args) == 2
1900 decoded_child0 = args[0]
1901 decoded_child1 = args[1]
1902 # Circular references become None
1903 assert decoded_child0 == {'args': [None], 'kwargs': {}}
1904 assert decoded_child1 == {'args': [None], 'kwargs': {}}
1905
1906
1907 def test_dict_references_are_preserved():
1908 """References and object identities are preserved in dicts"""
1909 data = {}
1910 actual = jsonpickle.decode(jsonpickle.encode([data, data]))
1911 assert isinstance(actual, list)
1912 assert isinstance(actual[0], dict)
1913 assert isinstance(actual[1], dict)
1914 assert actual[0] is actual[1]
1915
1916
1917 def test_repeat_objects_are_expanded():
1918 """All objects are present in the json output"""
1919 # When references are disabled we should create expanded copies
1920 # of any object that appears more than once in the object stream.
1921 alice = Thing('alice')
1922 bob = Thing('bob')
1923 alice.child = bob
1924 car = Thing('car')
1925 car.driver = alice
1926 car.owner = alice
1927 car.passengers = [alice, bob]
1928 pickler = jsonpickle.Pickler(make_refs=False)
1929 flattened = pickler.flatten(car)
1930 assert flattened['name'] == 'car'
1931 assert flattened['driver']['name'] == 'alice'
1932 assert flattened['owner']['name'] == 'alice'
1933 assert flattened['passengers'][0]['name'] == 'alice'
1934 assert flattened['passengers'][1]['name'] == 'bob'
1935 assert flattened['driver']['child']['name'] == 'bob'
1936 assert flattened['passengers'][0]['child']['name'] == 'bob'