| 1 |
import array |
| 2 |
import collections |
| 3 |
import datetime |
| 4 |
import decimal |
| 5 |
import enum |
| 6 |
import queue |
| 7 |
import re |
| 8 |
import threading |
| 9 |
|
| 10 |
import pytest |
| 11 |
from helper import SkippableTest |
| 12 |
|
| 13 |
import jsonpickle |
| 14 |
from jsonpickle import handlers, tags, util |
| 15 |
|
| 16 |
|
| 17 |
@pytest.fixture |
| 18 |
def pickler(): |
| 19 |
"""Returns a default-constructed pickler""" |
| 20 |
return jsonpickle.pickler.Pickler() |
| 21 |
|
| 22 |
|
| 23 |
@pytest.fixture |
| 24 |
def unpickler(): |
| 25 |
"""Returns a default-constructed unpickler""" |
| 26 |
return jsonpickle.unpickler.Unpickler() |
| 27 |
|
| 28 |
|
| 29 |
class Thing: |
| 30 |
def __init__(self, name): |
| 31 |
self.name = name |
| 32 |
self.child = None |
| 33 |
|
| 34 |
|
| 35 |
class DictSubclass(dict): |
| 36 |
name = 'Test' |
| 37 |
|
| 38 |
|
| 39 |
class ListSubclass(list): |
| 40 |
pass |
| 41 |
|
| 42 |
|
| 43 |
class BrokenReprThing(Thing): |
| 44 |
def __repr__(self): |
| 45 |
raise Exception('%s has a broken repr' % self.name) |
| 46 |
|
| 47 |
def __str__(self): |
| 48 |
return '<BrokenReprThing "%s">' % self.name |
| 49 |
|
| 50 |
|
| 51 |
class GetstateDict(dict): |
| 52 |
def __init__(self, name, **kwargs): |
| 53 |
dict.__init__(self, **kwargs) |
| 54 |
self.name = name |
| 55 |
self.active = False |
| 56 |
|
| 57 |
def __getstate__(self): |
| 58 |
return (self.name, dict(self.items())) |
| 59 |
|
| 60 |
def __setstate__(self, state): |
| 61 |
self.name, vals = state |
| 62 |
self.update(vals) |
| 63 |
self.active = True |
| 64 |
|
| 65 |
|
| 66 |
class GetstateOnly: |
| 67 |
def __init__(self, a=1, b=2): |
| 68 |
self.a = a |
| 69 |
self.b = b |
| 70 |
|
| 71 |
def __getstate__(self): |
| 72 |
return [self.a, self.b] |
| 73 |
|
| 74 |
|
| 75 |
class GetstateReturnsList: |
| 76 |
def __init__(self, x, y): |
| 77 |
self.x = x |
| 78 |
self.y = y |
| 79 |
|
| 80 |
def __getstate__(self): |
| 81 |
return [self.x, self.y] |
| 82 |
|
| 83 |
def __setstate__(self, state): |
| 84 |
self.x, self.y = state[0], state[1] |
| 85 |
|
| 86 |
|
| 87 |
class GetstateRecursesInfintely: |
| 88 |
def __getstate__(self): |
| 89 |
return GetstateRecursesInfintely() |
| 90 |
|
| 91 |
|
| 92 |
class ListSubclassWithInit(list): |
| 93 |
def __init__(self, attr): |
| 94 |
self.attr = attr |
| 95 |
super().__init__() |
| 96 |
|
| 97 |
|
| 98 |
NamedTuple = collections.namedtuple('NamedTuple', 'a, b, c') |
| 99 |
|
| 100 |
|
| 101 |
class ObjWithJsonPickleRepr: |
| 102 |
def __init__(self): |
| 103 |
self.data = {'a': self} |
| 104 |
|
| 105 |
def __repr__(self): |
| 106 |
return jsonpickle.encode(self) |
| 107 |
|
| 108 |
|
| 109 |
class OldStyleClass: |
| 110 |
pass |
| 111 |
|
| 112 |
|
| 113 |
class SetSubclass(set): |
| 114 |
pass |
| 115 |
|
| 116 |
|
| 117 |
def func(x): |
| 118 |
return x |
| 119 |
|
| 120 |
|
| 121 |
class ThingWithFunctionRefs: |
| 122 |
def __init__(self): |
| 123 |
self.fn = func |
| 124 |
|
| 125 |
|
| 126 |
class ThingWithQueue: |
| 127 |
def __init__(self): |
| 128 |
self.child_1 = queue.Queue() |
| 129 |
self.child_2 = queue.Queue() |
| 130 |
self.childref_1 = self.child_1 |
| 131 |
self.childref_2 = self.child_2 |
| 132 |
|
| 133 |
|
| 134 |
class ThingWithSlots: |
| 135 |
__slots__ = ('a', 'b') |
| 136 |
|
| 137 |
def __init__(self, a, b): |
| 138 |
self.a = a |
| 139 |
self.b = b |
| 140 |
|
| 141 |
|
| 142 |
class ThingWithInheritedSlots(ThingWithSlots): |
| 143 |
__slots__ = ('c',) |
| 144 |
|
| 145 |
def __init__(self, a, b, c): |
| 146 |
ThingWithSlots.__init__(self, a, b) |
| 147 |
self.c = c |
| 148 |
|
| 149 |
|
| 150 |
class ThingWithIterableSlots: |
| 151 |
__slots__ = iter('ab') |
| 152 |
|
| 153 |
def __init__(self, a, b): |
| 154 |
self.a = a |
| 155 |
self.b = b |
| 156 |
|
| 157 |
|
| 158 |
class ThingWithStringSlots: |
| 159 |
__slots__ = 'ab' |
| 160 |
|
| 161 |
def __init__(self, a, b): |
| 162 |
self.ab = a + b |
| 163 |
|
| 164 |
|
| 165 |
class ThingWithSelfAsDefaultFactory(collections.defaultdict): |
| 166 |
"""defaultdict subclass that uses itself as its default factory""" |
| 167 |
|
| 168 |
def __init__(self): |
| 169 |
self.default_factory = self |
| 170 |
|
| 171 |
def __call__(self): |
| 172 |
return self.__class__() |
| 173 |
|
| 174 |
|
| 175 |
class ThingWithClassAsDefaultFactory(collections.defaultdict): |
| 176 |
"""defaultdict subclass that uses its class as its default factory""" |
| 177 |
|
| 178 |
def __init__(self): |
| 179 |
self.default_factory = self.__class__ |
| 180 |
|
| 181 |
def __call__(self): |
| 182 |
return self.__class__() |
| 183 |
|
| 184 |
|
| 185 |
class ThingWithDefaultFactoryRegistry: |
| 186 |
"""Counts calls to ThingWithDefaultFactory.__init__()""" |
| 187 |
|
| 188 |
count = 0 # Incremented by ThingWithDefaultFactory(). |
| 189 |
|
| 190 |
|
| 191 |
class ThingWithDefaultFactory: |
| 192 |
"""Class that ensures that provides a default factory""" |
| 193 |
|
| 194 |
def __new__(cls, *args, **kwargs): |
| 195 |
"""Ensure that jsonpickle uses our constructor during initialization""" |
| 196 |
return super().__new__(cls, *args, **kwargs) |
| 197 |
|
| 198 |
def __init__(self): |
| 199 |
self.default_factory = self.__class__ |
| 200 |
# Keep track of how many times this constructor has been run. |
| 201 |
ThingWithDefaultFactoryRegistry.count += 1 |
| 202 |
|
| 203 |
|
| 204 |
class IntEnumTest(enum.IntEnum): |
| 205 |
X = 1 |
| 206 |
Y = 2 |
| 207 |
|
| 208 |
|
| 209 |
class StringEnumTest(enum.Enum): |
| 210 |
A = 'a' |
| 211 |
B = 'b' |
| 212 |
|
| 213 |
|
| 214 |
class SubEnum(enum.Enum): |
| 215 |
a = 1 |
| 216 |
b = 2 |
| 217 |
|
| 218 |
|
| 219 |
class EnumClass: |
| 220 |
def __init__(self): |
| 221 |
self.enum_a = SubEnum.a |
| 222 |
self.enum_b = SubEnum.b |
| 223 |
|
| 224 |
|
| 225 |
class MessageTypes(enum.Enum): |
| 226 |
STATUS = ('STATUS',) |
| 227 |
CONTROL = 'CONTROL' |
| 228 |
|
| 229 |
|
| 230 |
class MessageStatus(enum.Enum): |
| 231 |
OK = ('OK',) |
| 232 |
ERROR = 'ERROR' |
| 233 |
|
| 234 |
|
| 235 |
class MessageCommands(enum.Enum): |
| 236 |
STATUS_ALL = 'STATUS_ALL' |
| 237 |
|
| 238 |
|
| 239 |
class Message: |
| 240 |
def __init__(self, message_type, command, status=None, body=None): |
| 241 |
self.message_type = MessageTypes(message_type) |
| 242 |
if command: |
| 243 |
self.command = MessageCommands(command) |
| 244 |
if status: |
| 245 |
self.status = MessageStatus(status) |
| 246 |
if body: |
| 247 |
self.body = body |
| 248 |
|
| 249 |
|
| 250 |
class ThingWithTimedeltaAttribute: |
| 251 |
def __init__(self, offset): |
| 252 |
self.offset = datetime.timedelta(offset) |
| 253 |
|
| 254 |
def __getinitargs__(self): |
| 255 |
return (self.offset,) |
| 256 |
|
| 257 |
|
| 258 |
class FailSafeTestCase(SkippableTest): |
| 259 |
class BadClass: |
| 260 |
def __getstate__(self): |
| 261 |
raise ValueError('Intentional error') |
| 262 |
|
| 263 |
good = 'good' |
| 264 |
|
| 265 |
to_pickle = [BadClass(), good] |
| 266 |
|
| 267 |
def test_no_error(self): |
| 268 |
encoded = jsonpickle.encode(self.to_pickle, fail_safe=lambda e: None) |
| 269 |
decoded = jsonpickle.decode(encoded) |
| 270 |
assert decoded[0] is None |
| 271 |
assert decoded[1] == 'good' |
| 272 |
|
| 273 |
def test_error_recorded(self): |
| 274 |
exceptions = [] |
| 275 |
|
| 276 |
def recorder(exception): |
| 277 |
exceptions.append(exception) |
| 278 |
|
| 279 |
jsonpickle.encode(self.to_pickle, fail_safe=recorder) |
| 280 |
assert len(exceptions) == 1 |
| 281 |
assert isinstance(exceptions[0], Exception) |
| 282 |
|
| 283 |
def test_custom_err_msg(self): |
| 284 |
CUSTOM_ERR_MSG = 'custom err msg' |
| 285 |
encoded = jsonpickle.encode(self.to_pickle, fail_safe=lambda e: CUSTOM_ERR_MSG) |
| 286 |
decoded = jsonpickle.decode(encoded) |
| 287 |
assert decoded[0] == CUSTOM_ERR_MSG |
| 288 |
|
| 289 |
|
| 290 |
class IntKeysObject: |
| 291 |
def __init__(self): |
| 292 |
self.data = {0: 0} |
| 293 |
|
| 294 |
def __getstate__(self): |
| 295 |
return self.__dict__ |
| 296 |
|
| 297 |
|
| 298 |
class ExceptionWithArguments(Exception): |
| 299 |
def __init__(self, value): |
| 300 |
super().__init__('test') |
| 301 |
self.value = value |
| 302 |
|
| 303 |
|
| 304 |
class ThingWithExclusion: |
| 305 |
_jsonpickle_exclude = ["foo"] |
| 306 |
|
| 307 |
def __init__(self, a): |
| 308 |
self.foo = 1 |
| 309 |
self.bar = a |
| 310 |
|
| 311 |
|
| 312 |
class ThingWithExcludeSubclass: |
| 313 |
def __init__(self, foo): |
| 314 |
self.foo = foo |
| 315 |
self.thing = ThingWithExclusion(3) |
| 316 |
|
| 317 |
|
| 318 |
def test_list_subclass(pickler, unpickler): |
| 319 |
obj = ListSubclass() |
| 320 |
obj.extend([1, 2, 3]) |
| 321 |
flattened = pickler.flatten(obj) |
| 322 |
assert tags.OBJECT in flattened |
| 323 |
assert tags.SEQ in flattened |
| 324 |
assert len(flattened[tags.SEQ]) == 3 |
| 325 |
for v in obj: |
| 326 |
assert v in flattened[tags.SEQ] |
| 327 |
restored = unpickler.restore(flattened) |
| 328 |
assert type(restored) is ListSubclass |
| 329 |
assert restored == obj |
| 330 |
|
| 331 |
|
| 332 |
def test_list_subclass_with_init(pickler, unpickler): |
| 333 |
obj = ListSubclassWithInit('foo') |
| 334 |
assert obj.attr == 'foo' |
| 335 |
flattened = pickler.flatten(obj) |
| 336 |
inflated = unpickler.restore(flattened) |
| 337 |
assert type(inflated) is ListSubclassWithInit |
| 338 |
|
| 339 |
|
| 340 |
def test_list_subclass_with_data(pickler, unpickler): |
| 341 |
obj = ListSubclass() |
| 342 |
obj.extend([1, 2, 3]) |
| 343 |
data = SetSubclass([1, 2, 3]) |
| 344 |
obj.data = data |
| 345 |
flattened = pickler.flatten(obj) |
| 346 |
restored = unpickler.restore(flattened) |
| 347 |
assert restored == obj |
| 348 |
assert type(restored.data) is SetSubclass |
| 349 |
assert restored.data == data |
| 350 |
|
| 351 |
|
| 352 |
def test_set_subclass(pickler, unpickler): |
| 353 |
obj = SetSubclass([1, 2, 3]) |
| 354 |
flattened = pickler.flatten(obj) |
| 355 |
assert tags.OBJECT in flattened |
| 356 |
assert tags.SEQ in flattened |
| 357 |
assert len(flattened[tags.SEQ]) == 3 |
| 358 |
for v in obj: |
| 359 |
assert v in flattened[tags.SEQ] |
| 360 |
restored = unpickler.restore(flattened) |
| 361 |
assert type(restored) is SetSubclass |
| 362 |
assert restored == obj |
| 363 |
|
| 364 |
|
| 365 |
def test_set_subclass_with_data(pickler, unpickler): |
| 366 |
obj = SetSubclass([1, 2, 3]) |
| 367 |
data = ListSubclass() |
| 368 |
data.extend([1, 2, 3]) |
| 369 |
obj.data = data |
| 370 |
flattened = pickler.flatten(obj) |
| 371 |
restored = unpickler.restore(flattened) |
| 372 |
assert restored.data.__class__ == ListSubclass |
| 373 |
assert restored.data == data |
| 374 |
|
| 375 |
|
| 376 |
def test_decimal(pickler, unpickler): |
| 377 |
obj = decimal.Decimal('0.5') |
| 378 |
flattened = pickler.flatten(obj) |
| 379 |
inflated = unpickler.restore(flattened) |
| 380 |
assert isinstance(inflated, decimal.Decimal) |
| 381 |
|
| 382 |
|
| 383 |
def test_oldstyleclass(pickler, unpickler): |
| 384 |
obj = OldStyleClass() |
| 385 |
obj.value = 1234 |
| 386 |
flattened = pickler.flatten(obj) |
| 387 |
assert flattened['value'] == 1234 |
| 388 |
inflated = unpickler.restore(flattened) |
| 389 |
assert inflated.value == 1234 |
| 390 |
|
| 391 |
|
| 392 |
def test_dictsubclass(pickler, unpickler): |
| 393 |
obj = DictSubclass() |
| 394 |
obj['key1'] = 1 |
| 395 |
expect = { |
| 396 |
tags.OBJECT: 'object_test.DictSubclass', |
| 397 |
'key1': 1, |
| 398 |
'__dict__': {}, |
| 399 |
} |
| 400 |
flattened = pickler.flatten(obj) |
| 401 |
assert expect == flattened |
| 402 |
inflated = unpickler.restore(flattened) |
| 403 |
assert type(inflated) is DictSubclass |
| 404 |
assert inflated['key1'] == 1 |
| 405 |
assert inflated.name == 'Test' |
| 406 |
|
| 407 |
|
| 408 |
def test_dictsubclass_notunpickable(pickler, unpickler): |
| 409 |
pickler.unpicklable = False |
| 410 |
obj = DictSubclass() |
| 411 |
obj['key1'] = 1 |
| 412 |
flattened = pickler.flatten(obj) |
| 413 |
assert flattened['key1'] == 1 |
| 414 |
assert tags.OBJECT not in flattened |
| 415 |
inflated = unpickler.restore(flattened) |
| 416 |
assert inflated['key1'] == 1 |
| 417 |
|
| 418 |
|
| 419 |
def test_getstate_dict_subclass_structure(pickler): |
| 420 |
obj = GetstateDict('test') |
| 421 |
obj['key1'] = 1 |
| 422 |
flattened = pickler.flatten(obj) |
| 423 |
assert tags.OBJECT in flattened |
| 424 |
assert 'object_test.GetstateDict' == flattened[tags.OBJECT] |
| 425 |
assert tags.STATE in flattened |
| 426 |
assert tags.TUPLE in flattened[tags.STATE] |
| 427 |
assert ['test' == {'key1': 1}], flattened[tags.STATE][tags.TUPLE] |
| 428 |
|
| 429 |
|
| 430 |
def test_getstate_dict_subclass_roundtrip_simple(pickler, unpickler): |
| 431 |
obj = GetstateDict('test') |
| 432 |
obj['key1'] = 1 |
| 433 |
flattened = pickler.flatten(obj) |
| 434 |
inflated = unpickler.restore(flattened) |
| 435 |
assert inflated['key1'] == 1 |
| 436 |
assert inflated.name == 'test' |
| 437 |
|
| 438 |
|
| 439 |
def test_getstate_dict_subclass_roundtrip_cyclical(pickler, unpickler): |
| 440 |
obj = GetstateDict('test') |
| 441 |
obj['key1'] = 1 |
| 442 |
# The "name" field of obj2 points to obj (reference) |
| 443 |
obj2 = GetstateDict(obj) |
| 444 |
# The "obj2" key in obj points to obj2 (cyclical reference) |
| 445 |
obj['obj2'] = obj2 |
| 446 |
flattened = pickler.flatten(obj) |
| 447 |
inflated = unpickler.restore(flattened) |
| 448 |
# The dict must be preserved |
| 449 |
assert inflated['key1'] == 1 |
| 450 |
# __getstate__/__setstate__ must have been run |
| 451 |
assert inflated.name == 'test' |
| 452 |
assert inflated.active is True |
| 453 |
assert inflated['obj2'].active is True |
| 454 |
# The reference must be preserved |
| 455 |
assert inflated is inflated['obj2'].name |
| 456 |
|
| 457 |
|
| 458 |
def test_getstate_list_simple(pickler, unpickler): |
| 459 |
obj = GetstateReturnsList(1, 2) |
| 460 |
flattened = pickler.flatten(obj) |
| 461 |
inflated = unpickler.restore(flattened) |
| 462 |
assert inflated.x == 1 |
| 463 |
assert inflated.y == 2 |
| 464 |
|
| 465 |
|
| 466 |
def test_getstate_list_inside_list(pickler, unpickler): |
| 467 |
obj1 = GetstateReturnsList(1, 2) |
| 468 |
obj2 = GetstateReturnsList(3, 4) |
| 469 |
obj = [obj1, obj2] |
| 470 |
flattened = pickler.flatten(obj) |
| 471 |
inflated = unpickler.restore(flattened) |
| 472 |
assert inflated[0].x == 1 |
| 473 |
assert inflated[0].y == 2 |
| 474 |
assert inflated[1].x == 3 |
| 475 |
assert inflated[1].y == 4 |
| 476 |
|
| 477 |
|
| 478 |
def test_getstate_with_getstate_only(pickler, unpickler): |
| 479 |
obj = GetstateOnly() |
| 480 |
a = obj.a = 'this object implements' |
| 481 |
b = obj.b = '__getstate__ but not __setstate__' |
| 482 |
expect = [a, b] |
| 483 |
flat = pickler.flatten(obj) |
| 484 |
actual = flat[tags.STATE] |
| 485 |
assert expect == actual |
| 486 |
restored = unpickler.restore(flat) |
| 487 |
assert expect == restored |
| 488 |
|
| 489 |
|
| 490 |
def test_thing_with_queue(pickler, unpickler): |
| 491 |
obj = ThingWithQueue() |
| 492 |
flattened = pickler.flatten(obj) |
| 493 |
restored = unpickler.restore(flattened) |
| 494 |
assert type(restored.child_1) is type(queue.Queue()) |
| 495 |
assert type(restored.child_2) is type(queue.Queue()) |
| 496 |
# Check references |
| 497 |
assert restored.child_1 is restored.childref_1 |
| 498 |
assert restored.child_2 is restored.childref_2 |
| 499 |
|
| 500 |
|
| 501 |
def test_thing_with_func(pickler, unpickler): |
| 502 |
obj = ThingWithFunctionRefs() |
| 503 |
obj.ref = obj |
| 504 |
flattened = pickler.flatten(obj) |
| 505 |
restored = unpickler.restore(flattened) |
| 506 |
assert restored.fn is obj.fn |
| 507 |
expect = 'success' |
| 508 |
actual1 = restored.fn(expect) |
| 509 |
assert expect == actual1 |
| 510 |
assert restored is restored.ref |
| 511 |
|
| 512 |
|
| 513 |
def test_thing_with_compiled_regex(pickler, unpickler): |
| 514 |
rgx = re.compile(r'(.*)(cat)') |
| 515 |
obj = Thing(rgx) |
| 516 |
flattened = pickler.flatten(obj) |
| 517 |
restored = unpickler.restore(flattened) |
| 518 |
match = restored.name.match('fatcat') |
| 519 |
assert 'fat' == match.group(1) |
| 520 |
assert 'cat' == match.group(2) |
| 521 |
|
| 522 |
|
| 523 |
def test_base_object_roundrip(pickler, unpickler): |
| 524 |
roundtrip = unpickler.restore(pickler.flatten(object())) |
| 525 |
assert type(roundtrip) is object |
| 526 |
|
| 527 |
|
| 528 |
def test_enum34(pickler, unpickler): |
| 529 |
restore = unpickler.restore |
| 530 |
flatten = pickler.flatten |
| 531 |
|
| 532 |
def roundtrip(obj): |
| 533 |
return restore(flatten(obj)) |
| 534 |
|
| 535 |
assert roundtrip(IntEnumTest.X) is IntEnumTest.X |
| 536 |
assert roundtrip(IntEnumTest) is IntEnumTest |
| 537 |
assert roundtrip(StringEnumTest.A) is StringEnumTest.A |
| 538 |
assert roundtrip(StringEnumTest) is StringEnumTest |
| 539 |
|
| 540 |
|
| 541 |
def test_bytes_unicode(pickler, unpickler): |
| 542 |
b1 = b'foo' |
| 543 |
b2 = b'foo\xff' |
| 544 |
u1 = 'foo' |
| 545 |
# unicode strings get encoded/decoded as is |
| 546 |
encoded = pickler.flatten(u1) |
| 547 |
assert encoded == u1 |
| 548 |
assert isinstance(encoded, str) |
| 549 |
decoded = unpickler.restore(encoded) |
| 550 |
assert decoded == u1 |
| 551 |
assert isinstance(decoded, str) |
| 552 |
# bytestrings are wrapped in py 3 |
| 553 |
encoded = pickler.flatten(b1) |
| 554 |
assert encoded != u1 |
| 555 |
encoded_ustr = util.b64encode(b'foo') |
| 556 |
assert {tags.B64: encoded_ustr} == encoded |
| 557 |
assert isinstance(encoded[tags.B64], str) |
| 558 |
decoded = unpickler.restore(encoded) |
| 559 |
assert decoded == b1 |
| 560 |
assert isinstance(decoded, bytes) |
| 561 |
# bytestrings that we can't decode to UTF-8 will always be wrapped |
| 562 |
encoded = pickler.flatten(b2) |
| 563 |
assert encoded != b2 |
| 564 |
encoded_ustr = util.b64encode(b'foo\xff') |
| 565 |
assert {tags.B64: encoded_ustr} == encoded |
| 566 |
assert isinstance(encoded[tags.B64], str) |
| 567 |
decoded = unpickler.restore(encoded) |
| 568 |
assert decoded == b2 |
| 569 |
assert isinstance(decoded, bytes) |
| 570 |
|
| 571 |
|
| 572 |
def test_nested_objects(pickler, unpickler): |
| 573 |
obj = ThingWithTimedeltaAttribute(99) |
| 574 |
flattened = pickler.flatten(obj) |
| 575 |
restored = unpickler.restore(flattened) |
| 576 |
assert restored.offset == datetime.timedelta(99) |
| 577 |
|
| 578 |
|
| 579 |
def test_threading_lock(pickler, unpickler): |
| 580 |
obj = Thing('lock') |
| 581 |
obj.lock = threading.Lock() |
| 582 |
lock_class = obj.lock.__class__ |
| 583 |
# Roundtrip and make sure we get a lock object. |
| 584 |
json = pickler.flatten(obj) |
| 585 |
clone = unpickler.restore(json) |
| 586 |
assert isinstance(clone.lock, lock_class) |
| 587 |
assert not clone.lock.locked() |
| 588 |
# Serializing a locked lock should create a locked clone. |
| 589 |
assert obj.lock.acquire() |
| 590 |
json = pickler.flatten(obj) |
| 591 |
obj.lock.release() |
| 592 |
# Restore the locked lock state. |
| 593 |
clone = unpickler.restore(json) |
| 594 |
assert clone.lock.locked() |
| 595 |
clone.lock.release() |
| 596 |
|
| 597 |
|
| 598 |
def _test_array_roundtrip(pickler, unpickler, obj): |
| 599 |
"""Roundtrip an array and test invariants""" |
| 600 |
json = pickler.flatten(obj) |
| 601 |
clone = unpickler.restore(json) |
| 602 |
assert isinstance(clone, array.array) |
| 603 |
assert obj.typecode == clone.typecode |
| 604 |
assert len(obj) == len(clone) |
| 605 |
for j, k in zip(obj, clone): |
| 606 |
assert j == k |
| 607 |
assert obj == clone |
| 608 |
|
| 609 |
|
| 610 |
def test_array_handler_numeric(pickler, unpickler): |
| 611 |
"""Test numeric array.array typecodes that work in Python2+3""" |
| 612 |
typecodes = ('b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'f', 'd') |
| 613 |
for typecode in typecodes: |
| 614 |
obj = array.array(typecode, (1, 2, 3)) |
| 615 |
_test_array_roundtrip(pickler, unpickler, obj) |
| 616 |
|
| 617 |
|
| 618 |
def test_exceptions_with_arguments(pickler, unpickler): |
| 619 |
"""Ensure that we can roundtrip Exceptions that take arguments""" |
| 620 |
obj = ExceptionWithArguments('example') |
| 621 |
json = pickler.flatten(obj) |
| 622 |
clone = unpickler.restore(json) |
| 623 |
assert obj.value == clone.value |
| 624 |
assert obj.args == clone.args |
| 625 |
|
| 626 |
|
| 627 |
def test_getstate_does_not_recurse_infinitely(): |
| 628 |
"""Serialize an object with a __getstate__ that recurses forever""" |
| 629 |
obj = GetstateRecursesInfintely() |
| 630 |
pickler = jsonpickle.pickler.Pickler(max_depth=5) |
| 631 |
actual = pickler.flatten(obj) |
| 632 |
assert isinstance(actual, dict) |
| 633 |
assert tags.OBJECT in actual |
| 634 |
|
| 635 |
|
| 636 |
def test_defaultdict_roundtrip(): |
| 637 |
"""Make sure we can handle collections.defaultdict(list)""" |
| 638 |
# setup |
| 639 |
defaultdict = collections.defaultdict |
| 640 |
defdict = defaultdict(list) |
| 641 |
defdict['a'] = 1 |
| 642 |
defdict['b'].append(2) |
| 643 |
defdict['c'] = defaultdict(dict) |
| 644 |
# jsonpickle work your magic |
| 645 |
encoded = jsonpickle.encode(defdict) |
| 646 |
newdefdict = jsonpickle.decode(encoded) |
| 647 |
# jsonpickle never fails |
| 648 |
assert newdefdict['a'] == 1 |
| 649 |
assert newdefdict['b'] == [2] |
| 650 |
assert type(newdefdict['c']) is defaultdict |
| 651 |
assert defdict.default_factory == list |
| 652 |
assert newdefdict.default_factory == list |
| 653 |
|
| 654 |
|
| 655 |
def test_default_factory_initialization(): |
| 656 |
"""Ensure that ThingWithDefaultFactory()'s constructor is called""" |
| 657 |
thing = ThingWithDefaultFactory() |
| 658 |
assert ThingWithDefaultFactoryRegistry.count == 1 |
| 659 |
|
| 660 |
thing.is_awesome = True |
| 661 |
encoded = jsonpickle.encode(thing) |
| 662 |
new_thing = jsonpickle.decode(encoded) |
| 663 |
|
| 664 |
assert ThingWithDefaultFactoryRegistry.count == 2 |
| 665 |
assert new_thing.is_awesome |
| 666 |
|
| 667 |
|
| 668 |
def test_defaultdict_roundtrip_simple_lambda(): |
| 669 |
"""Make sure we can handle defaultdict(lambda: defaultdict(int))""" |
| 670 |
# setup a sparse collections.defaultdict with simple lambdas |
| 671 |
defaultdict = collections.defaultdict |
| 672 |
defdict = defaultdict(lambda: defaultdict(int)) |
| 673 |
defdict[0] = 'zero' |
| 674 |
defdict[1] = defaultdict(lambda: defaultdict(dict)) |
| 675 |
defdict[1][0] = 'zero' |
| 676 |
# roundtrip |
| 677 |
encoded = jsonpickle.encode(defdict, keys=True) |
| 678 |
newdefdict = jsonpickle.decode(encoded, keys=True) |
| 679 |
assert newdefdict[0] == 'zero' |
| 680 |
assert type(newdefdict[1]) is defaultdict |
| 681 |
assert newdefdict[1][0] == 'zero' |
| 682 |
assert newdefdict[1][1] == {} # inner defaultdict |
| 683 |
assert newdefdict[2][0] == 0 # outer defaultdict |
| 684 |
assert type(newdefdict[3]) is defaultdict |
| 685 |
# outer-most defaultdict |
| 686 |
assert newdefdict[3].default_factory == int |
| 687 |
|
| 688 |
|
| 689 |
def test_defaultdict_roundtrip_simple_lambda2(): |
| 690 |
"""Serialize a defaultdict that contains a lambda""" |
| 691 |
defaultdict = collections.defaultdict |
| 692 |
payload = {'a': defaultdict(lambda: 0)} |
| 693 |
defdict = defaultdict(lambda: 0, payload) |
| 694 |
# roundtrip |
| 695 |
encoded = jsonpickle.encode(defdict, keys=True) |
| 696 |
decoded = jsonpickle.decode(encoded, keys=True) |
| 697 |
assert type(decoded) is defaultdict |
| 698 |
assert type(decoded['a']) is defaultdict |
| 699 |
|
| 700 |
|
| 701 |
def test_defaultdict_and_things_roundtrip_simple_lambda(): |
| 702 |
"""Serialize a default dict that contains a lambda and objects""" |
| 703 |
thing = Thing('a') |
| 704 |
defaultdict = collections.defaultdict |
| 705 |
defdict = defaultdict(lambda: 0) |
| 706 |
obj = [defdict, thing, thing] |
| 707 |
# roundtrip |
| 708 |
encoded = jsonpickle.encode(obj, keys=True) |
| 709 |
decoded = jsonpickle.decode(encoded, keys=True) |
| 710 |
assert decoded[0].default_factory() == 0 |
| 711 |
assert decoded[1] is decoded[2] |
| 712 |
|
| 713 |
|
| 714 |
def _test_defaultdict_tree(tree, cls): |
| 715 |
tree['A']['B'] = 1 |
| 716 |
tree['A']['C'] = 2 |
| 717 |
# roundtrip |
| 718 |
encoded = jsonpickle.encode(tree) |
| 719 |
newtree = jsonpickle.decode(encoded) |
| 720 |
# make sure we didn't lose anything |
| 721 |
assert type(newtree) is cls |
| 722 |
assert type(newtree['A']) is cls |
| 723 |
assert newtree['A']['B'] == 1 |
| 724 |
assert newtree['A']['C'] == 2 |
| 725 |
# ensure that the resulting default_factory is callable and creates |
| 726 |
# a new instance of cls. |
| 727 |
assert type(newtree['A'].default_factory()) == cls |
| 728 |
# we've never seen 'D' before so the reconstructed defaultdict tree |
| 729 |
# should create an instance of cls. |
| 730 |
assert type(newtree['A']['D']) is cls |
| 731 |
# ensure that proxies do not escape into user code |
| 732 |
assert type(newtree.default_factory) is not jsonpickle.unpickler._Proxy |
| 733 |
assert type(newtree['A'].default_factory) is not jsonpickle.unpickler._Proxy |
| 734 |
assert type(newtree['A']['Z'].default_factory) is not jsonpickle.unpickler._Proxy |
| 735 |
return newtree |
| 736 |
|
| 737 |
|
| 738 |
def test_defaultdict_subclass_with_self_as_default_factory(): |
| 739 |
"""Serialize a defaultdict subclass with self as its default factory""" |
| 740 |
cls = ThingWithSelfAsDefaultFactory |
| 741 |
tree = cls() |
| 742 |
newtree = _test_defaultdict_tree(tree, cls) |
| 743 |
assert type(newtree['A'].default_factory) is cls |
| 744 |
assert newtree.default_factory is newtree |
| 745 |
assert newtree['A'].default_factory is newtree['A'] |
| 746 |
assert newtree['Z'].default_factory is newtree['Z'] |
| 747 |
|
| 748 |
|
| 749 |
def test_defaultdict_subclass_with_class_as_default_factory(): |
| 750 |
"""Serialize a defaultdict with a class as its default factory""" |
| 751 |
cls = ThingWithClassAsDefaultFactory |
| 752 |
tree = cls() |
| 753 |
newtree = _test_defaultdict_tree(tree, cls) |
| 754 |
assert newtree.default_factory is cls |
| 755 |
assert newtree['A'].default_factory is cls |
| 756 |
assert newtree['Z'].default_factory is cls |
| 757 |
|
| 758 |
|
| 759 |
def test_posix_stat_result(): |
| 760 |
"""Serialize a posix.stat() result""" |
| 761 |
try: |
| 762 |
import posix |
| 763 |
except ImportError: |
| 764 |
return |
| 765 |
expect = posix.stat(__file__) |
| 766 |
encoded = jsonpickle.encode(expect) |
| 767 |
actual = jsonpickle.decode(encoded) |
| 768 |
assert expect == actual |
| 769 |
|
| 770 |
|
| 771 |
def test_repr_using_jsonpickle(): |
| 772 |
"""Serialize an object that uses jsonpickle in its __repr__ definition""" |
| 773 |
thing = ObjWithJsonPickleRepr() |
| 774 |
thing.child = ObjWithJsonPickleRepr() |
| 775 |
thing.child.parent = thing |
| 776 |
encoded = jsonpickle.encode(thing) |
| 777 |
decoded = jsonpickle.decode(encoded) |
| 778 |
assert id(decoded) == id(decoded.child.parent) |
| 779 |
|
| 780 |
|
| 781 |
def test_broken_repr_dict_key(): |
| 782 |
"""Tests that we can pickle dictionaries with keys that have |
| 783 |
broken __repr__ implementations. |
| 784 |
""" |
| 785 |
br = BrokenReprThing('test') |
| 786 |
obj = {br: True} |
| 787 |
pickler = jsonpickle.pickler.Pickler() |
| 788 |
flattened = pickler.flatten(obj) |
| 789 |
assert '<BrokenReprThing "test">' in flattened |
| 790 |
assert flattened['<BrokenReprThing "test">'] |
| 791 |
|
| 792 |
|
| 793 |
def test_ordered_dict_python3(): |
| 794 |
"""Ensure that we preserve dict order on python3""" |
| 795 |
# Python3.6+ preserves dict order. |
| 796 |
obj = {'z': 'Z', 'x': 'X', 'y': 'Y'} |
| 797 |
clone = jsonpickle.decode(jsonpickle.encode(obj)) |
| 798 |
expect = ['z', 'x', 'y'] |
| 799 |
actual = list(clone.keys()) |
| 800 |
assert expect == actual |
| 801 |
|
| 802 |
|
| 803 |
def test_ordered_dict(): |
| 804 |
"""Serialize an OrderedDict""" |
| 805 |
d = collections.OrderedDict([('c', 3), ('a', 1), ('b', 2)]) |
| 806 |
encoded = jsonpickle.encode(d) |
| 807 |
decoded = jsonpickle.decode(encoded) |
| 808 |
assert d == decoded |
| 809 |
|
| 810 |
|
| 811 |
def test_ordered_dict_unpicklable(): |
| 812 |
"""Serialize an OrderedDict with unpicklable=False""" |
| 813 |
d = collections.OrderedDict([('c', 3), ('a', 1), ('b', 2)]) |
| 814 |
encoded = jsonpickle.encode(d, unpicklable=False) |
| 815 |
decoded = jsonpickle.decode(encoded) |
| 816 |
assert d == decoded |
| 817 |
|
| 818 |
|
| 819 |
def test_ordered_dict_reduces(): |
| 820 |
"""Ensure that OrderedDict is reduce()-able""" |
| 821 |
d = collections.OrderedDict([('c', 3), ('a', 1), ('b', 2)]) |
| 822 |
has_reduce, has_reduce_ex = util.has_reduce(d) |
| 823 |
assert util.is_reducible(d) |
| 824 |
assert has_reduce or has_reduce_ex |
| 825 |
|
| 826 |
|
| 827 |
def test_int_keys_in_object_with_getstate_only(): |
| 828 |
"""Serialize objects with dict keys that implement __getstate__ only""" |
| 829 |
obj = IntKeysObject() |
| 830 |
encoded = jsonpickle.encode(obj, keys=True) |
| 831 |
decoded = jsonpickle.decode(encoded, keys=True) |
| 832 |
assert obj.data == decoded.data |
| 833 |
|
| 834 |
|
| 835 |
def test_ordered_dict_int_keys(): |
| 836 |
"""Serialize dicts with int keys and OrderedDict values""" |
| 837 |
d = { |
| 838 |
1: collections.OrderedDict([(2, -2), (3, -3)]), |
| 839 |
4: collections.OrderedDict([(5, -5), (6, -6)]), |
| 840 |
} |
| 841 |
encoded = jsonpickle.encode(d, keys=True) |
| 842 |
decoded = jsonpickle.decode(encoded, keys=True) |
| 843 |
assert isinstance(decoded[1], collections.OrderedDict) |
| 844 |
assert isinstance(decoded[4], collections.OrderedDict) |
| 845 |
assert -2 == decoded[1][2] |
| 846 |
assert -3 == decoded[1][3] |
| 847 |
assert -5 == decoded[4][5] |
| 848 |
assert -6 == decoded[4][6] |
| 849 |
assert d == decoded |
| 850 |
|
| 851 |
|
| 852 |
def test_ordered_dict_nested(): |
| 853 |
"""Serialize nested dicts with OrderedDict values""" |
| 854 |
bottom = collections.OrderedDict([('z', 1), ('a', 2)]) |
| 855 |
middle = collections.OrderedDict([('c', bottom)]) |
| 856 |
top = collections.OrderedDict([('b', middle)]) |
| 857 |
encoded = jsonpickle.encode(top) |
| 858 |
decoded = jsonpickle.decode(encoded) |
| 859 |
assert top == decoded |
| 860 |
# test unpicklable=False |
| 861 |
encoded = jsonpickle.encode(top, unpicklable=False) |
| 862 |
decoded = jsonpickle.decode(encoded) |
| 863 |
assert top == decoded |
| 864 |
|
| 865 |
|
| 866 |
def test_deque_roundtrip(): |
| 867 |
"""Make sure we can handle collections.deque""" |
| 868 |
old_deque = collections.deque([0, 1, 2], maxlen=5) |
| 869 |
encoded = jsonpickle.encode(old_deque) |
| 870 |
new_deque = jsonpickle.decode(encoded) |
| 871 |
assert encoded != 'nil' |
| 872 |
assert old_deque[0] == 0 |
| 873 |
assert new_deque[0] == 0 |
| 874 |
assert old_deque[1] == 1 |
| 875 |
assert new_deque[1] == 1 |
| 876 |
assert old_deque[2] == 2 |
| 877 |
assert new_deque[2] == 2 |
| 878 |
assert old_deque.maxlen == 5 |
| 879 |
assert new_deque.maxlen == 5 |
| 880 |
|
| 881 |
|
| 882 |
def test_namedtuple_roundtrip(): |
| 883 |
"""Serialize a NamedTuple""" |
| 884 |
old_nt = NamedTuple(0, 1, 2) |
| 885 |
encoded = jsonpickle.encode(old_nt) |
| 886 |
new_nt = jsonpickle.decode(encoded) |
| 887 |
assert type(old_nt) is type(new_nt) |
| 888 |
assert old_nt is not new_nt |
| 889 |
assert old_nt.a == new_nt.a |
| 890 |
assert old_nt.b == new_nt.b |
| 891 |
assert old_nt.c == new_nt.c |
| 892 |
assert old_nt[0] == new_nt[0] |
| 893 |
assert old_nt[1] == new_nt[1] |
| 894 |
assert old_nt[2] == new_nt[2] |
| 895 |
|
| 896 |
|
| 897 |
def test_counter_roundtrip(): |
| 898 |
counter = collections.Counter({1: 2}) |
| 899 |
encoded = jsonpickle.encode(counter) |
| 900 |
decoded = jsonpickle.decode(encoded) |
| 901 |
assert type(decoded) is collections.Counter |
| 902 |
# the integer key becomes a string when keys=False |
| 903 |
assert decoded.get('1') == 2 |
| 904 |
|
| 905 |
|
| 906 |
def test_counter_roundtrip_with_keys(): |
| 907 |
counter = collections.Counter({1: 2}) |
| 908 |
encoded = jsonpickle.encode(counter, keys=True) |
| 909 |
decoded = jsonpickle.decode(encoded, keys=True) |
| 910 |
assert type(decoded) is collections.Counter |
| 911 |
assert decoded.get(1) == 2 |
| 912 |
|
| 913 |
|
| 914 |
def test_list_with_fd(): |
| 915 |
"""Serialize a list with an file descriptor""" |
| 916 |
with open(__file__) as fd: |
| 917 |
_test_list_with_fd(fd) |
| 918 |
_test_list_with_fd(fd) # fd is closed. |
| 919 |
|
| 920 |
|
| 921 |
def _test_list_with_fd(fd): |
| 922 |
"""Serialize a list with an file descriptor""" |
| 923 |
obj = [fd] |
| 924 |
jsonstr = jsonpickle.encode(obj) |
| 925 |
newobj = jsonpickle.decode(jsonstr) |
| 926 |
assert [None] == newobj |
| 927 |
|
| 928 |
|
| 929 |
def test_thing_with_fd(): |
| 930 |
"""Serialize an object with a file descriptor""" |
| 931 |
with open(__file__) as fd: |
| 932 |
_test_thing_with_fd(fd) |
| 933 |
_test_thing_with_fd(fd) # fd is closed. |
| 934 |
|
| 935 |
|
| 936 |
def _test_thing_with_fd(fd): |
| 937 |
"""Serialize an object with a file descriptor""" |
| 938 |
obj = Thing(fd) |
| 939 |
jsonstr = jsonpickle.encode(obj) |
| 940 |
newobj = jsonpickle.decode(jsonstr) |
| 941 |
assert newobj.name is None |
| 942 |
|
| 943 |
|
| 944 |
def test_dict_with_fd(): |
| 945 |
"""Serialize a dict with a file descriptor""" |
| 946 |
with open(__file__) as fd: |
| 947 |
_test_dict_with_fd(fd) |
| 948 |
_test_dict_with_fd(fd) |
| 949 |
|
| 950 |
|
| 951 |
def _test_dict_with_fd(fd): |
| 952 |
"""Serialize a dict with a file descriptor""" |
| 953 |
obj = {'fd': fd} |
| 954 |
jsonstr = jsonpickle.encode(obj) |
| 955 |
newobj = jsonpickle.decode(jsonstr) |
| 956 |
assert newobj['fd'] is None |
| 957 |
|
| 958 |
|
| 959 |
def test_thing_with_lamda(): |
| 960 |
"""Serialize an object with a lambda""" |
| 961 |
obj = Thing(lambda: True) |
| 962 |
jsonstr = jsonpickle.encode(obj) |
| 963 |
newobj = jsonpickle.decode(jsonstr) |
| 964 |
assert not hasattr(newobj, 'name') |
| 965 |
|
| 966 |
|
| 967 |
def test_newstyleslots(): |
| 968 |
"""Serialize an object with new-style slots""" |
| 969 |
obj = ThingWithSlots(True, False) |
| 970 |
jsonstr = jsonpickle.encode(obj) |
| 971 |
newobj = jsonpickle.decode(jsonstr) |
| 972 |
assert newobj.a |
| 973 |
assert not newobj.b |
| 974 |
|
| 975 |
|
| 976 |
def test_newstyleslots_inherited(): |
| 977 |
"""Serialize an object with inherited new-style slots""" |
| 978 |
obj = ThingWithInheritedSlots(True, False, None) |
| 979 |
jsonstr = jsonpickle.encode(obj) |
| 980 |
newobj = jsonpickle.decode(jsonstr) |
| 981 |
assert newobj.a |
| 982 |
assert not newobj.b |
| 983 |
assert newobj.c is None |
| 984 |
|
| 985 |
|
| 986 |
def test_newstyleslots_inherited_deleted_attr(): |
| 987 |
"""Serialize an object with inherited and deleted new-style slots""" |
| 988 |
obj = ThingWithInheritedSlots(True, False, None) |
| 989 |
del obj.c |
| 990 |
jsonstr = jsonpickle.encode(obj) |
| 991 |
newobj = jsonpickle.decode(jsonstr) |
| 992 |
assert newobj.a |
| 993 |
assert not newobj.b |
| 994 |
assert not hasattr(newobj, 'c') |
| 995 |
|
| 996 |
|
| 997 |
def test_newstyleslots_with_children(): |
| 998 |
"""Serialize an object with slots containing objects""" |
| 999 |
obj = ThingWithSlots(Thing('a'), Thing('b')) |
| 1000 |
jsonstr = jsonpickle.encode(obj) |
| 1001 |
newobj = jsonpickle.decode(jsonstr) |
| 1002 |
assert newobj.a.name == 'a' |
| 1003 |
assert newobj.b.name == 'b' |
| 1004 |
|
| 1005 |
|
| 1006 |
def test_newstyleslots_with_children_inherited(): |
| 1007 |
"""Serialize an object with inherited slots containing objects""" |
| 1008 |
obj = ThingWithInheritedSlots(Thing('a'), Thing('b'), Thing('c')) |
| 1009 |
jsonstr = jsonpickle.encode(obj) |
| 1010 |
newobj = jsonpickle.decode(jsonstr) |
| 1011 |
assert newobj.a.name == 'a' |
| 1012 |
assert newobj.b.name == 'b' |
| 1013 |
assert newobj.c.name == 'c' |
| 1014 |
|
| 1015 |
|
| 1016 |
def test_newstyleslots_iterable(): |
| 1017 |
"""Seriazlie an object with iterable slots""" |
| 1018 |
obj = ThingWithIterableSlots('alpha', 'bravo') |
| 1019 |
jsonstr = jsonpickle.encode(obj) |
| 1020 |
newobj = jsonpickle.decode(jsonstr) |
| 1021 |
assert newobj.a == 'alpha' |
| 1022 |
assert newobj.b == 'bravo' |
| 1023 |
|
| 1024 |
|
| 1025 |
def test_newstyleslots_string_slot(): |
| 1026 |
"""Serialize an object with string slots""" |
| 1027 |
obj = ThingWithStringSlots('a', 'b') |
| 1028 |
jsonstr = jsonpickle.encode(obj) |
| 1029 |
newobj = jsonpickle.decode(jsonstr) |
| 1030 |
assert newobj.ab == 'ab' |
| 1031 |
|
| 1032 |
|
| 1033 |
def test_enum34_nested(): |
| 1034 |
"""Serialize enums as nested member variables in an object""" |
| 1035 |
ec = EnumClass() |
| 1036 |
encoded = jsonpickle.encode(ec) |
| 1037 |
decoded = jsonpickle.decode(encoded) |
| 1038 |
assert ec.enum_a == decoded.enum_a |
| 1039 |
assert ec.enum_b == decoded.enum_b |
| 1040 |
|
| 1041 |
|
| 1042 |
def test_enum_references(): |
| 1043 |
"""Serialize duplicate enums so that reference IDs are used""" |
| 1044 |
a = IntEnumTest.X |
| 1045 |
b = IntEnumTest.X |
| 1046 |
enums_list = [a, b] |
| 1047 |
encoded = jsonpickle.encode(enums_list) |
| 1048 |
decoded = jsonpickle.decode(encoded) |
| 1049 |
assert enums_list == decoded |
| 1050 |
|
| 1051 |
|
| 1052 |
def test_enum_unpicklable(): |
| 1053 |
"""Serialize enums when unpicklable=False is specified""" |
| 1054 |
obj = Message(MessageTypes.STATUS, MessageCommands.STATUS_ALL) |
| 1055 |
encoded = jsonpickle.encode(obj, unpicklable=False) |
| 1056 |
decoded = jsonpickle.decode(encoded) |
| 1057 |
assert 'message_type' in decoded |
| 1058 |
assert 'command' in decoded |
| 1059 |
|
| 1060 |
|
| 1061 |
def test_enum_int_key_and_value(): |
| 1062 |
"""Serialize Integer enums as dict keys and values""" |
| 1063 |
thing = Thing('test') |
| 1064 |
value = IntEnumTest.X |
| 1065 |
value2 = IntEnumTest.Y |
| 1066 |
expect = { |
| 1067 |
'__first__': thing, |
| 1068 |
'thing': thing, |
| 1069 |
value: value, |
| 1070 |
value2: value2, |
| 1071 |
} |
| 1072 |
string = jsonpickle.encode(expect, keys=True) |
| 1073 |
actual = jsonpickle.decode(string, keys=True) |
| 1074 |
assert 'test' == actual['__first__'].name |
| 1075 |
assert value == actual[value] |
| 1076 |
assert value2 == actual[value2] |
| 1077 |
|
| 1078 |
actual_first = actual['__first__'] |
| 1079 |
actual_thing = actual['thing'] |
| 1080 |
assert actual_first is actual_thing |
| 1081 |
|
| 1082 |
|
| 1083 |
def test_enum_string_key_and_value(): |
| 1084 |
"""Encode enums dict keys and values""" |
| 1085 |
thing = Thing('test') |
| 1086 |
value = StringEnumTest.A |
| 1087 |
value2 = StringEnumTest.B |
| 1088 |
expect = { |
| 1089 |
value: value, |
| 1090 |
'__first__': thing, |
| 1091 |
value2: value2, |
| 1092 |
} |
| 1093 |
string = jsonpickle.encode(expect, keys=True) |
| 1094 |
actual = jsonpickle.decode(string, keys=True) |
| 1095 |
assert 'test' == actual['__first__'].name |
| 1096 |
assert value == actual[value] |
| 1097 |
assert value2 == actual[value2] |
| 1098 |
|
| 1099 |
|
| 1100 |
def test_multiple_string_enums_when_make_refs_is_false(): |
| 1101 |
"""Enums do not create cycles when make_refs=False""" |
| 1102 |
# The make_refs=False code path will fallback to repr() when encoding |
| 1103 |
# objects that it believes introduce a cycle. It does this to break |
| 1104 |
# out of what would be infinite recursion during traversal. |
| 1105 |
# This test ensures that enums do not trigger cycles and are properly |
| 1106 |
# encoded under make_refs=False. |
| 1107 |
expect = { |
| 1108 |
'a': StringEnumTest.A, |
| 1109 |
'aa': StringEnumTest.A, |
| 1110 |
} |
| 1111 |
string = jsonpickle.encode(expect, make_refs=False) |
| 1112 |
actual = jsonpickle.decode(string) |
| 1113 |
assert expect == actual |
| 1114 |
|
| 1115 |
|
| 1116 |
# Test classes for ExternalHandlerTestCase |
| 1117 |
class Mixin: |
| 1118 |
def ok(self): |
| 1119 |
return True |
| 1120 |
|
| 1121 |
|
| 1122 |
class UnicodeMixin(str, Mixin): |
| 1123 |
def __add__(self, rhs): |
| 1124 |
obj = super().__add__(rhs) |
| 1125 |
return UnicodeMixin(obj) |
| 1126 |
|
| 1127 |
|
| 1128 |
class UnicodeMixinHandler(handlers.BaseHandler): |
| 1129 |
def flatten(self, obj, data): |
| 1130 |
data['value'] = obj |
| 1131 |
return data |
| 1132 |
|
| 1133 |
def restore(self, obj): |
| 1134 |
return UnicodeMixin(obj['value']) |
| 1135 |
|
| 1136 |
|
| 1137 |
def test_unicode_mixin(): |
| 1138 |
obj = UnicodeMixin('test') |
| 1139 |
assert isinstance(obj, UnicodeMixin) |
| 1140 |
assert obj == 'test' |
| 1141 |
|
| 1142 |
# Encode into JSON |
| 1143 |
handlers.register(UnicodeMixin, UnicodeMixinHandler) |
| 1144 |
content = jsonpickle.encode(obj) |
| 1145 |
|
| 1146 |
# Resurrect from JSON |
| 1147 |
new_obj = jsonpickle.decode(content) |
| 1148 |
handlers.unregister(UnicodeMixin) |
| 1149 |
|
| 1150 |
new_obj += ' passed' |
| 1151 |
|
| 1152 |
assert new_obj == 'test passed' |
| 1153 |
assert isinstance(new_obj, UnicodeMixin) |
| 1154 |
assert new_obj.ok() |
| 1155 |
|
| 1156 |
|
| 1157 |
def test_datetime_with_tz_copies_refs(): |
| 1158 |
"""Ensure that we create copies of referenced objects""" |
| 1159 |
utc = datetime.timezone.utc |
| 1160 |
d0 = datetime.datetime(2020, 5, 5, 5, 5, 5, 5, tzinfo=utc) |
| 1161 |
d1 = datetime.datetime(2020, 5, 5, 5, 5, 5, 5, tzinfo=utc) |
| 1162 |
obj = [d0, d1] |
| 1163 |
encoded = jsonpickle.encode(obj, make_refs=False) |
| 1164 |
decoded = jsonpickle.decode(encoded) |
| 1165 |
assert len(decoded) == 2 |
| 1166 |
assert decoded[0] == d0 |
| 1167 |
assert decoded[1] == d1 |
| 1168 |
|
| 1169 |
|
| 1170 |
def test_with_exclude(): |
| 1171 |
"""Does the _jsonpickle_exclude work""" |
| 1172 |
obj = ThingWithExclusion('baz') |
| 1173 |
encoded = jsonpickle.encode(obj) |
| 1174 |
decoded = jsonpickle.decode(encoded) |
| 1175 |
assert decoded.bar == 'baz' |
| 1176 |
assert not hasattr(decoded, 'foo') |
| 1177 |
|
| 1178 |
|
| 1179 |
def test_contained_exclusion(): |
| 1180 |
"""_jsonpickle_exclude should work only on the class it is defined in""" |
| 1181 |
obj = ThingWithExcludeSubclass('alpha') |
| 1182 |
encoded = jsonpickle.encode(obj) |
| 1183 |
decoded = jsonpickle.decode(encoded) |
| 1184 |
assert decoded.foo == 'alpha' |
| 1185 |
assert not hasattr(decoded.thing, 'foo') |