Debian Codegraph @

lib-python/3/test/pickletester.py

raw symbols SCIP
1 import builtins
2 import collections
3 import copyreg
4 import dbm
5 import io
6 import functools
7 import os
8 import math
9 import pickle
10 import pickletools
11 import shutil
12 import struct
13 import sys
14 import threading
15 import types
16 import unittest
17 import weakref
18 from textwrap import dedent
19 from http.cookies import SimpleCookie
20
21 try:
22 import _testbuffer
23 except ImportError:
24 _testbuffer = None
25
26 from test import support
27 from test.support import os_helper
28 from test.support import (
29 TestFailed, run_with_locale, no_tracing,
30 _2G, _4G, bigmemtest,
31 impl_detail
32 )
33 from test.support.import_helper import forget
34 from test.support.os_helper import TESTFN
35 from test.support import threading_helper
36 from test.support.warnings_helper import save_restore_warnings_filters
37
38 from pickle import bytes_types
39
40
41 # bpo-41003: Save/restore warnings filters to leave them unchanged.
42 # Ignore filters installed by numpy.
43 try:
44 with save_restore_warnings_filters():
45 import numpy as np
46 except ImportError:
47 np = None
48
49
50 requires_32b = unittest.skipUnless(sys.maxsize < 2**32,
51 "test is only meaningful on 32-bit builds")
52
53 # Tests that try a number of pickle protocols should have a
54 # for proto in protocols:
55 # kind of outer loop.
56 protocols = range(2, pickle.HIGHEST_PROTOCOL + 1)
57
58
59 # Return True if opcode code appears in the pickle, else False.
60 def opcode_in_pickle(code, pickle):
61 for op, dummy, dummy in pickletools.genops(pickle):
62 if op.code == code.decode("latin-1"):
63 return True
64 return False
65
66 # Return the number of times opcode code appears in pickle.
67 def count_opcode(code, pickle):
68 n = 0
69 for op, dummy, dummy in pickletools.genops(pickle):
70 if op.code == code.decode("latin-1"):
71 n += 1
72 return n
73
74
75 def identity(x):
76 return x
77
78
79 class UnseekableIO(io.BytesIO):
80 def peek(self, *args):
81 raise NotImplementedError
82
83 def seekable(self):
84 return False
85
86 def seek(self, *args):
87 raise io.UnsupportedOperation
88
89 def tell(self):
90 raise io.UnsupportedOperation
91
92
93 class MinimalIO(object):
94 """
95 A file-like object that doesn't support readinto().
96 """
97 def __init__(self, *args):
98 self._bio = io.BytesIO(*args)
99 self.getvalue = self._bio.getvalue
100 self.read = self._bio.read
101 self.readline = self._bio.readline
102 self.write = self._bio.write
103
104
105 # We can't very well test the extension registry without putting known stuff
106 # in it, but we have to be careful to restore its original state. Code
107 # should do this:
108 #
109 # e = ExtensionSaver(extension_code)
110 # try:
111 # fiddle w/ the extension registry's stuff for extension_code
112 # finally:
113 # e.restore()
114
115 class ExtensionSaver:
116 # Remember current registration for code (if any), and remove it (if
117 # there is one).
118 def __init__(self, code):
119 self.code = code
120 if code in copyreg._inverted_registry:
121 self.pair = copyreg._inverted_registry[code]
122 copyreg.remove_extension(self.pair[0], self.pair[1], code)
123 else:
124 self.pair = None
125
126 # Restore previous registration for code.
127 def restore(self):
128 code = self.code
129 curpair = copyreg._inverted_registry.get(code)
130 if curpair is not None:
131 copyreg.remove_extension(curpair[0], curpair[1], code)
132 pair = self.pair
133 if pair is not None:
134 copyreg.add_extension(pair[0], pair[1], code)
135
136 class C:
137 def __eq__(self, other):
138 return self.__dict__ == other.__dict__
139
140 class D(C):
141 def __init__(self, arg):
142 pass
143
144 class E(C):
145 def __getinitargs__(self):
146 return ()
147
148 # Simple mutable object.
149 class Object:
150 pass
151
152 # Hashable immutable key object containing unheshable mutable data.
153 class K:
154 def __init__(self, value):
155 self.value = value
156
157 def __reduce__(self):
158 # Shouldn't support the recursion itself
159 return K, (self.value,)
160
161 import __main__
162 __main__.C = C
163 C.__module__ = "__main__"
164 __main__.D = D
165 D.__module__ = "__main__"
166 __main__.E = E
167 E.__module__ = "__main__"
168
169 class myint(int):
170 def __init__(self, x):
171 self.str = str(x)
172
173 class initarg(C):
174
175 def __init__(self, a, b):
176 self.a = a
177 self.b = b
178
179 def __getinitargs__(self):
180 return self.a, self.b
181
182 class metaclass(type):
183 pass
184
185 class use_metaclass(object, metaclass=metaclass):
186 pass
187
188 class pickling_metaclass(type):
189 def __eq__(self, other):
190 return (type(self) == type(other) and
191 self.reduce_args == other.reduce_args)
192
193 def __reduce__(self):
194 return (create_dynamic_class, self.reduce_args)
195
196 def create_dynamic_class(name, bases):
197 result = pickling_metaclass(name, bases, dict())
198 result.reduce_args = (name, bases)
199 return result
200
201
202 class ZeroCopyBytes(bytes):
203 readonly = True
204 c_contiguous = True
205 f_contiguous = True
206 zero_copy_reconstruct = True
207
208 def __reduce_ex__(self, protocol):
209 if protocol >= 5:
210 return type(self)._reconstruct, (pickle.PickleBuffer(self),), None
211 else:
212 return type(self)._reconstruct, (bytes(self),)
213
214 def __repr__(self):
215 return "{}({!r})".format(self.__class__.__name__, bytes(self))
216
217 __str__ = __repr__
218
219 @classmethod
220 def _reconstruct(cls, obj):
221 with memoryview(obj) as m:
222 obj = m.obj
223 if type(obj) is cls:
224 # Zero-copy
225 return obj
226 else:
227 return cls(obj)
228
229
230 class ZeroCopyBytearray(bytearray):
231 readonly = False
232 c_contiguous = True
233 f_contiguous = True
234 zero_copy_reconstruct = True
235
236 def __reduce_ex__(self, protocol):
237 if protocol >= 5:
238 return type(self)._reconstruct, (pickle.PickleBuffer(self),), None
239 else:
240 return type(self)._reconstruct, (bytes(self),)
241
242 def __repr__(self):
243 return "{}({!r})".format(self.__class__.__name__, bytes(self))
244
245 __str__ = __repr__
246
247 @classmethod
248 def _reconstruct(cls, obj):
249 with memoryview(obj) as m:
250 obj = m.obj
251 if type(obj) is cls:
252 # Zero-copy
253 return obj
254 else:
255 return cls(obj)
256
257
258 if _testbuffer is not None:
259
260 class PicklableNDArray:
261 # A not-really-zero-copy picklable ndarray, as the ndarray()
262 # constructor doesn't allow for it
263
264 zero_copy_reconstruct = False
265
266 def __init__(self, *args, **kwargs):
267 self.array = _testbuffer.ndarray(*args, **kwargs)
268
269 def __getitem__(self, idx):
270 cls = type(self)
271 new = cls.__new__(cls)
272 new.array = self.array[idx]
273 return new
274
275 @property
276 def readonly(self):
277 return self.array.readonly
278
279 @property
280 def c_contiguous(self):
281 return self.array.c_contiguous
282
283 @property
284 def f_contiguous(self):
285 return self.array.f_contiguous
286
287 def __eq__(self, other):
288 if not isinstance(other, PicklableNDArray):
289 return NotImplemented
290 return (other.array.format == self.array.format and
291 other.array.shape == self.array.shape and
292 other.array.strides == self.array.strides and
293 other.array.readonly == self.array.readonly and
294 other.array.tobytes() == self.array.tobytes())
295
296 def __ne__(self, other):
297 if not isinstance(other, PicklableNDArray):
298 return NotImplemented
299 return not (self == other)
300
301 def __repr__(self):
302 return (f"{type(self)}(shape={self.array.shape},"
303 f"strides={self.array.strides}, "
304 f"bytes={self.array.tobytes()})")
305
306 def __reduce_ex__(self, protocol):
307 if not self.array.contiguous:
308 raise NotImplementedError("Reconstructing a non-contiguous "
309 "ndarray does not seem possible")
310 ndarray_kwargs = {"shape": self.array.shape,
311 "strides": self.array.strides,
312 "format": self.array.format,
313 "flags": (0 if self.readonly
314 else _testbuffer.ND_WRITABLE)}
315 pb = pickle.PickleBuffer(self.array)
316 if protocol >= 5:
317 return (type(self)._reconstruct,
318 (pb, ndarray_kwargs))
319 else:
320 # Need to serialize the bytes in physical order
321 with pb.raw() as m:
322 return (type(self)._reconstruct,
323 (m.tobytes(), ndarray_kwargs))
324
325 @classmethod
326 def _reconstruct(cls, obj, kwargs):
327 with memoryview(obj) as m:
328 # For some reason, ndarray() wants a list of integers...
329 # XXX This only works if format == 'B'
330 items = list(m.tobytes())
331 return cls(items, **kwargs)
332
333
334 # DATA0 .. DATA4 are the pickles we expect under the various protocols, for
335 # the object returned by create_data().
336
337 DATA0 = (
338 b'(lp0\nL0L\naL1L\naF2.0\n'
339 b'ac__builtin__\ncomple'
340 b'x\np1\n(F3.0\nF0.0\ntp2\n'
341 b'Rp3\naL1L\naL-1L\naL255'
342 b'L\naL-255L\naL-256L\naL'
343 b'65535L\naL-65535L\naL-'
344 b'65536L\naL2147483647L'
345 b'\naL-2147483647L\naL-2'
346 b'147483648L\na(Vabc\np4'
347 b'\ng4\nccopy_reg\n_recon'
348 b'structor\np5\n(c__main'
349 b'__\nC\np6\nc__builtin__'
350 b'\nobject\np7\nNtp8\nRp9\n'
351 b'(dp10\nVfoo\np11\nL1L\ns'
352 b'Vbar\np12\nL2L\nsbg9\ntp'
353 b'13\nag13\naL5L\na.'
354 )
355
356 # Disassembly of DATA0
357 DATA0_DIS = """\
358 0: ( MARK
359 1: l LIST (MARK at 0)
360 2: p PUT 0
361 5: L LONG 0
362 9: a APPEND
363 10: L LONG 1
364 14: a APPEND
365 15: F FLOAT 2.0
366 20: a APPEND
367 21: c GLOBAL '__builtin__ complex'
368 42: p PUT 1
369 45: ( MARK
370 46: F FLOAT 3.0
371 51: F FLOAT 0.0
372 56: t TUPLE (MARK at 45)
373 57: p PUT 2
374 60: R REDUCE
375 61: p PUT 3
376 64: a APPEND
377 65: L LONG 1
378 69: a APPEND
379 70: L LONG -1
380 75: a APPEND
381 76: L LONG 255
382 82: a APPEND
383 83: L LONG -255
384 90: a APPEND
385 91: L LONG -256
386 98: a APPEND
387 99: L LONG 65535
388 107: a APPEND
389 108: L LONG -65535
390 117: a APPEND
391 118: L LONG -65536
392 127: a APPEND
393 128: L LONG 2147483647
394 141: a APPEND
395 142: L LONG -2147483647
396 156: a APPEND
397 157: L LONG -2147483648
398 171: a APPEND
399 172: ( MARK
400 173: V UNICODE 'abc'
401 178: p PUT 4
402 181: g GET 4
403 184: c GLOBAL 'copy_reg _reconstructor'
404 209: p PUT 5
405 212: ( MARK
406 213: c GLOBAL '__main__ C'
407 225: p PUT 6
408 228: c GLOBAL '__builtin__ object'
409 248: p PUT 7
410 251: N NONE
411 252: t TUPLE (MARK at 212)
412 253: p PUT 8
413 256: R REDUCE
414 257: p PUT 9
415 260: ( MARK
416 261: d DICT (MARK at 260)
417 262: p PUT 10
418 266: V UNICODE 'foo'
419 271: p PUT 11
420 275: L LONG 1
421 279: s SETITEM
422 280: V UNICODE 'bar'
423 285: p PUT 12
424 289: L LONG 2
425 293: s SETITEM
426 294: b BUILD
427 295: g GET 9
428 298: t TUPLE (MARK at 172)
429 299: p PUT 13
430 303: a APPEND
431 304: g GET 13
432 308: a APPEND
433 309: L LONG 5
434 313: a APPEND
435 314: . STOP
436 highest protocol among opcodes = 0
437 """
438
439 DATA1 = (
440 b']q\x00(K\x00K\x01G@\x00\x00\x00\x00\x00\x00\x00c__'
441 b'builtin__\ncomplex\nq\x01'
442 b'(G@\x08\x00\x00\x00\x00\x00\x00G\x00\x00\x00\x00\x00\x00\x00\x00t'
443 b'q\x02Rq\x03K\x01J\xff\xff\xff\xffK\xffJ\x01\xff\xff\xffJ'
444 b'\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff\xff'
445 b'\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00\x80(X\x03\x00\x00\x00ab'
446 b'cq\x04h\x04ccopy_reg\n_reco'
447 b'nstructor\nq\x05(c__main'
448 b'__\nC\nq\x06c__builtin__\n'
449 b'object\nq\x07Ntq\x08Rq\t}q\n('
450 b'X\x03\x00\x00\x00fooq\x0bK\x01X\x03\x00\x00\x00bar'
451 b'q\x0cK\x02ubh\ttq\rh\rK\x05e.'
452 )
453
454 # Disassembly of DATA1
455 DATA1_DIS = """\
456 0: ] EMPTY_LIST
457 1: q BINPUT 0
458 3: ( MARK
459 4: K BININT1 0
460 6: K BININT1 1
461 8: G BINFLOAT 2.0
462 17: c GLOBAL '__builtin__ complex'
463 38: q BINPUT 1
464 40: ( MARK
465 41: G BINFLOAT 3.0
466 50: G BINFLOAT 0.0
467 59: t TUPLE (MARK at 40)
468 60: q BINPUT 2
469 62: R REDUCE
470 63: q BINPUT 3
471 65: K BININT1 1
472 67: J BININT -1
473 72: K BININT1 255
474 74: J BININT -255
475 79: J BININT -256
476 84: M BININT2 65535
477 87: J BININT -65535
478 92: J BININT -65536
479 97: J BININT 2147483647
480 102: J BININT -2147483647
481 107: J BININT -2147483648
482 112: ( MARK
483 113: X BINUNICODE 'abc'
484 121: q BINPUT 4
485 123: h BINGET 4
486 125: c GLOBAL 'copy_reg _reconstructor'
487 150: q BINPUT 5
488 152: ( MARK
489 153: c GLOBAL '__main__ C'
490 165: q BINPUT 6
491 167: c GLOBAL '__builtin__ object'
492 187: q BINPUT 7
493 189: N NONE
494 190: t TUPLE (MARK at 152)
495 191: q BINPUT 8
496 193: R REDUCE
497 194: q BINPUT 9
498 196: } EMPTY_DICT
499 197: q BINPUT 10
500 199: ( MARK
501 200: X BINUNICODE 'foo'
502 208: q BINPUT 11
503 210: K BININT1 1
504 212: X BINUNICODE 'bar'
505 220: q BINPUT 12
506 222: K BININT1 2
507 224: u SETITEMS (MARK at 199)
508 225: b BUILD
509 226: h BINGET 9
510 228: t TUPLE (MARK at 112)
511 229: q BINPUT 13
512 231: h BINGET 13
513 233: K BININT1 5
514 235: e APPENDS (MARK at 3)
515 236: . STOP
516 highest protocol among opcodes = 1
517 """
518
519 DATA2 = (
520 b'\x80\x02]q\x00(K\x00K\x01G@\x00\x00\x00\x00\x00\x00\x00c'
521 b'__builtin__\ncomplex\n'
522 b'q\x01G@\x08\x00\x00\x00\x00\x00\x00G\x00\x00\x00\x00\x00\x00\x00\x00'
523 b'\x86q\x02Rq\x03K\x01J\xff\xff\xff\xffK\xffJ\x01\xff\xff\xff'
524 b'J\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff'
525 b'\xff\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00\x80(X\x03\x00\x00\x00a'
526 b'bcq\x04h\x04c__main__\nC\nq\x05'
527 b')\x81q\x06}q\x07(X\x03\x00\x00\x00fooq\x08K\x01'
528 b'X\x03\x00\x00\x00barq\tK\x02ubh\x06tq\nh'
529 b'\nK\x05e.'
530 )
531
532 # Disassembly of DATA2
533 DATA2_DIS = """\
534 0: \x80 PROTO 2
535 2: ] EMPTY_LIST
536 3: q BINPUT 0
537 5: ( MARK
538 6: K BININT1 0
539 8: K BININT1 1
540 10: G BINFLOAT 2.0
541 19: c GLOBAL '__builtin__ complex'
542 40: q BINPUT 1
543 42: G BINFLOAT 3.0
544 51: G BINFLOAT 0.0
545 60: \x86 TUPLE2
546 61: q BINPUT 2
547 63: R REDUCE
548 64: q BINPUT 3
549 66: K BININT1 1
550 68: J BININT -1
551 73: K BININT1 255
552 75: J BININT -255
553 80: J BININT -256
554 85: M BININT2 65535
555 88: J BININT -65535
556 93: J BININT -65536
557 98: J BININT 2147483647
558 103: J BININT -2147483647
559 108: J BININT -2147483648
560 113: ( MARK
561 114: X BINUNICODE 'abc'
562 122: q BINPUT 4
563 124: h BINGET 4
564 126: c GLOBAL '__main__ C'
565 138: q BINPUT 5
566 140: ) EMPTY_TUPLE
567 141: \x81 NEWOBJ
568 142: q BINPUT 6
569 144: } EMPTY_DICT
570 145: q BINPUT 7
571 147: ( MARK
572 148: X BINUNICODE 'foo'
573 156: q BINPUT 8
574 158: K BININT1 1
575 160: X BINUNICODE 'bar'
576 168: q BINPUT 9
577 170: K BININT1 2
578 172: u SETITEMS (MARK at 147)
579 173: b BUILD
580 174: h BINGET 6
581 176: t TUPLE (MARK at 113)
582 177: q BINPUT 10
583 179: h BINGET 10
584 181: K BININT1 5
585 183: e APPENDS (MARK at 5)
586 184: . STOP
587 highest protocol among opcodes = 2
588 """
589
590 DATA3 = (
591 b'\x80\x03]q\x00(K\x00K\x01G@\x00\x00\x00\x00\x00\x00\x00c'
592 b'builtins\ncomplex\nq\x01G'
593 b'@\x08\x00\x00\x00\x00\x00\x00G\x00\x00\x00\x00\x00\x00\x00\x00\x86q\x02'
594 b'Rq\x03K\x01J\xff\xff\xff\xffK\xffJ\x01\xff\xff\xffJ\x00\xff'
595 b'\xff\xffM\xff\xffJ\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff\xff\xff\x7f'
596 b'J\x01\x00\x00\x80J\x00\x00\x00\x80(X\x03\x00\x00\x00abcq'
597 b'\x04h\x04c__main__\nC\nq\x05)\x81q'
598 b'\x06}q\x07(X\x03\x00\x00\x00barq\x08K\x02X\x03\x00'
599 b'\x00\x00fooq\tK\x01ubh\x06tq\nh\nK\x05'
600 b'e.'
601 )
602
603 # Disassembly of DATA3
604 DATA3_DIS = """\
605 0: \x80 PROTO 3
606 2: ] EMPTY_LIST
607 3: q BINPUT 0
608 5: ( MARK
609 6: K BININT1 0
610 8: K BININT1 1
611 10: G BINFLOAT 2.0
612 19: c GLOBAL 'builtins complex'
613 37: q BINPUT 1
614 39: G BINFLOAT 3.0
615 48: G BINFLOAT 0.0
616 57: \x86 TUPLE2
617 58: q BINPUT 2
618 60: R REDUCE
619 61: q BINPUT 3
620 63: K BININT1 1
621 65: J BININT -1
622 70: K BININT1 255
623 72: J BININT -255
624 77: J BININT -256
625 82: M BININT2 65535
626 85: J BININT -65535
627 90: J BININT -65536
628 95: J BININT 2147483647
629 100: J BININT -2147483647
630 105: J BININT -2147483648
631 110: ( MARK
632 111: X BINUNICODE 'abc'
633 119: q BINPUT 4
634 121: h BINGET 4
635 123: c GLOBAL '__main__ C'
636 135: q BINPUT 5
637 137: ) EMPTY_TUPLE
638 138: \x81 NEWOBJ
639 139: q BINPUT 6
640 141: } EMPTY_DICT
641 142: q BINPUT 7
642 144: ( MARK
643 145: X BINUNICODE 'bar'
644 153: q BINPUT 8
645 155: K BININT1 2
646 157: X BINUNICODE 'foo'
647 165: q BINPUT 9
648 167: K BININT1 1
649 169: u SETITEMS (MARK at 144)
650 170: b BUILD
651 171: h BINGET 6
652 173: t TUPLE (MARK at 110)
653 174: q BINPUT 10
654 176: h BINGET 10
655 178: K BININT1 5
656 180: e APPENDS (MARK at 5)
657 181: . STOP
658 highest protocol among opcodes = 2
659 """
660
661 DATA4 = (
662 b'\x80\x04\x95\xa8\x00\x00\x00\x00\x00\x00\x00]\x94(K\x00K\x01G@'
663 b'\x00\x00\x00\x00\x00\x00\x00\x8c\x08builtins\x94\x8c\x07'
664 b'complex\x94\x93\x94G@\x08\x00\x00\x00\x00\x00\x00G'
665 b'\x00\x00\x00\x00\x00\x00\x00\x00\x86\x94R\x94K\x01J\xff\xff\xff\xffK'
666 b'\xffJ\x01\xff\xff\xffJ\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xffJ'
667 b'\x00\x00\xff\xffJ\xff\xff\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00\x80('
668 b'\x8c\x03abc\x94h\x06\x8c\x08__main__\x94\x8c'
669 b'\x01C\x94\x93\x94)\x81\x94}\x94(\x8c\x03bar\x94K\x02\x8c'
670 b'\x03foo\x94K\x01ubh\nt\x94h\x0eK\x05e.'
671 )
672
673 # Disassembly of DATA4
674 DATA4_DIS = """\
675 0: \x80 PROTO 4
676 2: \x95 FRAME 168
677 11: ] EMPTY_LIST
678 12: \x94 MEMOIZE
679 13: ( MARK
680 14: K BININT1 0
681 16: K BININT1 1
682 18: G BINFLOAT 2.0
683 27: \x8c SHORT_BINUNICODE 'builtins'
684 37: \x94 MEMOIZE
685 38: \x8c SHORT_BINUNICODE 'complex'
686 47: \x94 MEMOIZE
687 48: \x93 STACK_GLOBAL
688 49: \x94 MEMOIZE
689 50: G BINFLOAT 3.0
690 59: G BINFLOAT 0.0
691 68: \x86 TUPLE2
692 69: \x94 MEMOIZE
693 70: R REDUCE
694 71: \x94 MEMOIZE
695 72: K BININT1 1
696 74: J BININT -1
697 79: K BININT1 255
698 81: J BININT -255
699 86: J BININT -256
700 91: M BININT2 65535
701 94: J BININT -65535
702 99: J BININT -65536
703 104: J BININT 2147483647
704 109: J BININT -2147483647
705 114: J BININT -2147483648
706 119: ( MARK
707 120: \x8c SHORT_BINUNICODE 'abc'
708 125: \x94 MEMOIZE
709 126: h BINGET 6
710 128: \x8c SHORT_BINUNICODE '__main__'
711 138: \x94 MEMOIZE
712 139: \x8c SHORT_BINUNICODE 'C'
713 142: \x94 MEMOIZE
714 143: \x93 STACK_GLOBAL
715 144: \x94 MEMOIZE
716 145: ) EMPTY_TUPLE
717 146: \x81 NEWOBJ
718 147: \x94 MEMOIZE
719 148: } EMPTY_DICT
720 149: \x94 MEMOIZE
721 150: ( MARK
722 151: \x8c SHORT_BINUNICODE 'bar'
723 156: \x94 MEMOIZE
724 157: K BININT1 2
725 159: \x8c SHORT_BINUNICODE 'foo'
726 164: \x94 MEMOIZE
727 165: K BININT1 1
728 167: u SETITEMS (MARK at 150)
729 168: b BUILD
730 169: h BINGET 10
731 171: t TUPLE (MARK at 119)
732 172: \x94 MEMOIZE
733 173: h BINGET 14
734 175: K BININT1 5
735 177: e APPENDS (MARK at 13)
736 178: . STOP
737 highest protocol among opcodes = 4
738 """
739
740 # set([1,2]) pickled from 2.x with protocol 2
741 DATA_SET = b'\x80\x02c__builtin__\nset\nq\x00]q\x01(K\x01K\x02e\x85q\x02Rq\x03.'
742
743 # xrange(5) pickled from 2.x with protocol 2
744 DATA_XRANGE = b'\x80\x02c__builtin__\nxrange\nq\x00K\x00K\x05K\x01\x87q\x01Rq\x02.'
745
746 # a SimpleCookie() object pickled from 2.x with protocol 2
747 DATA_COOKIE = (b'\x80\x02cCookie\nSimpleCookie\nq\x00)\x81q\x01U\x03key'
748 b'q\x02cCookie\nMorsel\nq\x03)\x81q\x04(U\x07commentq\x05U'
749 b'\x00q\x06U\x06domainq\x07h\x06U\x06secureq\x08h\x06U\x07'
750 b'expiresq\th\x06U\x07max-ageq\nh\x06U\x07versionq\x0bh\x06U'
751 b'\x04pathq\x0ch\x06U\x08httponlyq\rh\x06u}q\x0e(U\x0b'
752 b'coded_valueq\x0fU\x05valueq\x10h\x10h\x10h\x02h\x02ubs}q\x11b.')
753
754 # set([3]) pickled from 2.x with protocol 2
755 DATA_SET2 = b'\x80\x02c__builtin__\nset\nq\x00]q\x01K\x03a\x85q\x02Rq\x03.'
756
757 python2_exceptions_without_args = (
758 ArithmeticError,
759 AssertionError,
760 AttributeError,
761 BaseException,
762 BufferError,
763 BytesWarning,
764 DeprecationWarning,
765 EOFError,
766 EnvironmentError,
767 Exception,
768 FloatingPointError,
769 FutureWarning,
770 GeneratorExit,
771 IOError,
772 ImportError,
773 ImportWarning,
774 IndentationError,
775 IndexError,
776 KeyError,
777 KeyboardInterrupt,
778 LookupError,
779 MemoryError,
780 NameError,
781 NotImplementedError,
782 OSError,
783 OverflowError,
784 PendingDeprecationWarning,
785 ReferenceError,
786 RuntimeError,
787 RuntimeWarning,
788 # StandardError is gone in Python 3, we map it to Exception
789 StopIteration,
790 SyntaxError,
791 SyntaxWarning,
792 SystemError,
793 SystemExit,
794 TabError,
795 TypeError,
796 UnboundLocalError,
797 UnicodeError,
798 UnicodeWarning,
799 UserWarning,
800 ValueError,
801 Warning,
802 ZeroDivisionError,
803 )
804
805 exception_pickle = b'\x80\x02cexceptions\n?\nq\x00)Rq\x01.'
806
807 # UnicodeEncodeError object pickled from 2.x with protocol 2
808 DATA_UEERR = (b'\x80\x02cexceptions\nUnicodeEncodeError\n'
809 b'q\x00(U\x05asciiq\x01X\x03\x00\x00\x00fooq\x02K\x00K\x01'
810 b'U\x03badq\x03tq\x04Rq\x05.')
811
812
813 def create_data():
814 c = C()
815 c.foo = 1
816 c.bar = 2
817 x = [0, 1, 2.0, 3.0+0j]
818 # Append some integer test cases at cPickle.c's internal size
819 # cutoffs.
820 uint1max = 0xff
821 uint2max = 0xffff
822 int4max = 0x7fffffff
823 x.extend([1, -1,
824 uint1max, -uint1max, -uint1max-1,
825 uint2max, -uint2max, -uint2max-1,
826 int4max, -int4max, -int4max-1])
827 y = ('abc', 'abc', c, c)
828 x.append(y)
829 x.append(y)
830 x.append(5)
831 return x
832
833
834 class AbstractUnpickleTests:
835 # Subclass must define self.loads.
836
837 _testdata = create_data()
838
839 def assert_is_copy(self, obj, objcopy, msg=None):
840 """Utility method to verify if two objects are copies of each others.
841 """
842 if msg is None:
843 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
844 self.assertEqual(obj, objcopy, msg=msg)
845 self.assertIs(type(obj), type(objcopy), msg=msg)
846 if hasattr(obj, '__dict__'):
847 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
848 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
849 if hasattr(obj, '__slots__'):
850 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
851 for slot in obj.__slots__:
852 self.assertEqual(
853 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
854 self.assertEqual(getattr(obj, slot, None),
855 getattr(objcopy, slot, None), msg=msg)
856
857 def check_unpickling_error(self, errors, data):
858 with self.subTest(data=data), \
859 self.assertRaises(errors):
860 try:
861 self.loads(data)
862 except BaseException as exc:
863 if support.verbose > 1:
864 print('%-32r - %s: %s' %
865 (data, exc.__class__.__name__, exc))
866 raise
867
868 def test_load_from_data0(self):
869 self.assert_is_copy(self._testdata, self.loads(DATA0))
870
871 def test_load_from_data1(self):
872 self.assert_is_copy(self._testdata, self.loads(DATA1))
873
874 def test_load_from_data2(self):
875 self.assert_is_copy(self._testdata, self.loads(DATA2))
876
877 def test_load_from_data3(self):
878 self.assert_is_copy(self._testdata, self.loads(DATA3))
879
880 def test_load_from_data4(self):
881 self.assert_is_copy(self._testdata, self.loads(DATA4))
882
883 def test_load_classic_instance(self):
884 # See issue5180. Test loading 2.x pickles that
885 # contain an instance of old style class.
886 for X, args in [(C, ()), (D, ('x',)), (E, ())]:
887 xname = X.__name__.encode('ascii')
888 # Protocol 0 (text mode pickle):
889 """
890 0: ( MARK
891 1: i INST '__main__ X' (MARK at 0)
892 13: p PUT 0
893 16: ( MARK
894 17: d DICT (MARK at 16)
895 18: p PUT 1
896 21: b BUILD
897 22: . STOP
898 """
899 pickle0 = (b"(i__main__\n"
900 b"X\n"
901 b"p0\n"
902 b"(dp1\nb.").replace(b'X', xname)
903 self.assert_is_copy(X(*args), self.loads(pickle0))
904
905 # Protocol 1 (binary mode pickle)
906 """
907 0: ( MARK
908 1: c GLOBAL '__main__ X'
909 13: q BINPUT 0
910 15: o OBJ (MARK at 0)
911 16: q BINPUT 1
912 18: } EMPTY_DICT
913 19: q BINPUT 2
914 21: b BUILD
915 22: . STOP
916 """
917 pickle1 = (b'(c__main__\n'
918 b'X\n'
919 b'q\x00oq\x01}q\x02b.').replace(b'X', xname)
920 self.assert_is_copy(X(*args), self.loads(pickle1))
921
922 # Protocol 2 (pickle2 = b'\x80\x02' + pickle1)
923 """
924 0: \x80 PROTO 2
925 2: ( MARK
926 3: c GLOBAL '__main__ X'
927 15: q BINPUT 0
928 17: o OBJ (MARK at 2)
929 18: q BINPUT 1
930 20: } EMPTY_DICT
931 21: q BINPUT 2
932 23: b BUILD
933 24: . STOP
934 """
935 pickle2 = (b'\x80\x02(c__main__\n'
936 b'X\n'
937 b'q\x00oq\x01}q\x02b.').replace(b'X', xname)
938 self.assert_is_copy(X(*args), self.loads(pickle2))
939
940 def test_maxint64(self):
941 maxint64 = (1 << 63) - 1
942 data = b'I' + str(maxint64).encode("ascii") + b'\n.'
943 got = self.loads(data)
944 self.assert_is_copy(maxint64, got)
945
946 # Try too with a bogus literal.
947 data = b'I' + str(maxint64).encode("ascii") + b'JUNK\n.'
948 self.check_unpickling_error(ValueError, data)
949
950 def test_unpickle_from_2x(self):
951 # Unpickle non-trivial data from Python 2.x.
952 loaded = self.loads(DATA_SET)
953 self.assertEqual(loaded, set([1, 2]))
954 loaded = self.loads(DATA_XRANGE)
955 self.assertEqual(type(loaded), type(range(0)))
956 self.assertEqual(list(loaded), list(range(5)))
957 loaded = self.loads(DATA_COOKIE)
958 self.assertEqual(type(loaded), SimpleCookie)
959 self.assertEqual(list(loaded.keys()), ["key"])
960 self.assertEqual(loaded["key"].value, "value")
961
962 # Exception objects without arguments pickled from 2.x with protocol 2
963 for exc in python2_exceptions_without_args:
964 data = exception_pickle.replace(b'?', exc.__name__.encode("ascii"))
965 loaded = self.loads(data)
966 self.assertIs(type(loaded), exc)
967
968 # StandardError is mapped to Exception, test that separately
969 loaded = self.loads(exception_pickle.replace(b'?', b'StandardError'))
970 self.assertIs(type(loaded), Exception)
971
972 loaded = self.loads(DATA_UEERR)
973 self.assertIs(type(loaded), UnicodeEncodeError)
974 self.assertEqual(loaded.object, "foo")
975 self.assertEqual(loaded.encoding, "ascii")
976 self.assertEqual(loaded.start, 0)
977 self.assertEqual(loaded.end, 1)
978 self.assertEqual(loaded.reason, "bad")
979
980 def test_load_python2_str_as_bytes(self):
981 # From Python 2: pickle.dumps('a\x00\xa0', protocol=0)
982 self.assertEqual(self.loads(b"S'a\\x00\\xa0'\n.",
983 encoding="bytes"), b'a\x00\xa0')
984 # From Python 2: pickle.dumps('a\x00\xa0', protocol=1)
985 self.assertEqual(self.loads(b'U\x03a\x00\xa0.',
986 encoding="bytes"), b'a\x00\xa0')
987 # From Python 2: pickle.dumps('a\x00\xa0', protocol=2)
988 self.assertEqual(self.loads(b'\x80\x02U\x03a\x00\xa0.',
989 encoding="bytes"), b'a\x00\xa0')
990
991 def test_load_python2_unicode_as_str(self):
992 # From Python 2: pickle.dumps(u'Ï€', protocol=0)
993 self.assertEqual(self.loads(b'V\\u03c0\n.',
994 encoding='bytes'), 'Ï€')
995 # From Python 2: pickle.dumps(u'Ï€', protocol=1)
996 self.assertEqual(self.loads(b'X\x02\x00\x00\x00\xcf\x80.',
997 encoding="bytes"), 'Ï€')
998 # From Python 2: pickle.dumps(u'Ï€', protocol=2)
999 self.assertEqual(self.loads(b'\x80\x02X\x02\x00\x00\x00\xcf\x80.',
1000 encoding="bytes"), 'Ï€')
1001
1002 def test_load_long_python2_str_as_bytes(self):
1003 # From Python 2: pickle.dumps('x' * 300, protocol=1)
1004 self.assertEqual(self.loads(pickle.BINSTRING +
1005 struct.pack("<I", 300) +
1006 b'x' * 300 + pickle.STOP,
1007 encoding='bytes'), b'x' * 300)
1008
1009 def test_constants(self):
1010 self.assertIsNone(self.loads(b'N.'))
1011 self.assertIs(self.loads(b'\x88.'), True)
1012 self.assertIs(self.loads(b'\x89.'), False)
1013 self.assertIs(self.loads(b'I01\n.'), True)
1014 self.assertIs(self.loads(b'I00\n.'), False)
1015
1016 def test_empty_bytestring(self):
1017 # issue 11286
1018 empty = self.loads(b'\x80\x03U\x00q\x00.', encoding='koi8-r')
1019 self.assertEqual(empty, '')
1020
1021 def test_short_binbytes(self):
1022 dumped = b'\x80\x03C\x04\xe2\x82\xac\x00.'
1023 self.assertEqual(self.loads(dumped), b'\xe2\x82\xac\x00')
1024
1025 def test_binbytes(self):
1026 dumped = b'\x80\x03B\x04\x00\x00\x00\xe2\x82\xac\x00.'
1027 self.assertEqual(self.loads(dumped), b'\xe2\x82\xac\x00')
1028
1029 @requires_32b
1030 def test_negative_32b_binbytes(self):
1031 # On 32-bit builds, a BINBYTES of 2**31 or more is refused
1032 dumped = b'\x80\x03B\xff\xff\xff\xffxyzq\x00.'
1033 self.check_unpickling_error((pickle.UnpicklingError, OverflowError),
1034 dumped)
1035
1036 @requires_32b
1037 def test_negative_32b_binunicode(self):
1038 # On 32-bit builds, a BINUNICODE of 2**31 or more is refused
1039 dumped = b'\x80\x03X\xff\xff\xff\xffxyzq\x00.'
1040 self.check_unpickling_error((pickle.UnpicklingError, OverflowError),
1041 dumped)
1042
1043 def test_short_binunicode(self):
1044 dumped = b'\x80\x04\x8c\x04\xe2\x82\xac\x00.'
1045 self.assertEqual(self.loads(dumped), '\u20ac\x00')
1046
1047 def test_misc_get(self):
1048 self.check_unpickling_error(pickle.UnpicklingError, b'g0\np0')
1049 self.check_unpickling_error(pickle.UnpicklingError, b'jens:')
1050 self.check_unpickling_error(pickle.UnpicklingError, b'hens:')
1051 self.assert_is_copy([(100,), (100,)],
1052 self.loads(b'((Kdtp0\nh\x00l.))'))
1053
1054 def test_binbytes8(self):
1055 dumped = b'\x80\x04\x8e\4\0\0\0\0\0\0\0\xe2\x82\xac\x00.'
1056 self.assertEqual(self.loads(dumped), b'\xe2\x82\xac\x00')
1057
1058 def test_binunicode8(self):
1059 dumped = b'\x80\x04\x8d\4\0\0\0\0\0\0\0\xe2\x82\xac\x00.'
1060 self.assertEqual(self.loads(dumped), '\u20ac\x00')
1061
1062 def test_bytearray8(self):
1063 dumped = b'\x80\x05\x96\x03\x00\x00\x00\x00\x00\x00\x00xxx.'
1064 self.assertEqual(self.loads(dumped), bytearray(b'xxx'))
1065
1066 @requires_32b
1067 def test_large_32b_binbytes8(self):
1068 dumped = b'\x80\x04\x8e\4\0\0\0\1\0\0\0\xe2\x82\xac\x00.'
1069 self.check_unpickling_error((pickle.UnpicklingError, OverflowError),
1070 dumped)
1071
1072 @requires_32b
1073 def test_large_32b_bytearray8(self):
1074 dumped = b'\x80\x05\x96\4\0\0\0\1\0\0\0\xe2\x82\xac\x00.'
1075 self.check_unpickling_error((pickle.UnpicklingError, OverflowError),
1076 dumped)
1077
1078 @requires_32b
1079 def test_large_32b_binunicode8(self):
1080 dumped = b'\x80\x04\x8d\4\0\0\0\1\0\0\0\xe2\x82\xac\x00.'
1081 self.check_unpickling_error((pickle.UnpicklingError, OverflowError),
1082 dumped)
1083
1084 def test_get(self):
1085 pickled = b'((lp100000\ng100000\nt.'
1086 unpickled = self.loads(pickled)
1087 self.assertEqual(unpickled, ([],)*2)
1088 self.assertIs(unpickled[0], unpickled[1])
1089
1090 def test_binget(self):
1091 pickled = b'(]q\xffh\xfft.'
1092 unpickled = self.loads(pickled)
1093 self.assertEqual(unpickled, ([],)*2)
1094 self.assertIs(unpickled[0], unpickled[1])
1095
1096 def test_long_binget(self):
1097 pickled = b'(]r\x00\x00\x01\x00j\x00\x00\x01\x00t.'
1098 unpickled = self.loads(pickled)
1099 self.assertEqual(unpickled, ([],)*2)
1100 self.assertIs(unpickled[0], unpickled[1])
1101
1102 def test_dup(self):
1103 pickled = b'((l2t.'
1104 unpickled = self.loads(pickled)
1105 self.assertEqual(unpickled, ([],)*2)
1106 self.assertIs(unpickled[0], unpickled[1])
1107
1108 def test_negative_put(self):
1109 # Issue #12847
1110 dumped = b'Va\np-1\n.'
1111 self.check_unpickling_error(ValueError, dumped)
1112
1113 @requires_32b
1114 def test_negative_32b_binput(self):
1115 # Issue #12847
1116 dumped = b'\x80\x03X\x01\x00\x00\x00ar\xff\xff\xff\xff.'
1117 self.check_unpickling_error(ValueError, dumped)
1118
1119 def test_badly_escaped_string(self):
1120 self.check_unpickling_error(ValueError, b"S'\\'\n.")
1121
1122 def test_badly_quoted_string(self):
1123 # Issue #17710
1124 badpickles = [b"S'\n.",
1125 b'S"\n.',
1126 b'S\' \n.',
1127 b'S" \n.',
1128 b'S\'"\n.',
1129 b'S"\'\n.',
1130 b"S' ' \n.",
1131 b'S" " \n.',
1132 b"S ''\n.",
1133 b'S ""\n.',
1134 b'S \n.',
1135 b'S\n.',
1136 b'S.']
1137 for p in badpickles:
1138 self.check_unpickling_error(pickle.UnpicklingError, p)
1139
1140 def test_correctly_quoted_string(self):
1141 goodpickles = [(b"S''\n.", ''),
1142 (b'S""\n.', ''),
1143 (b'S"\\n"\n.', '\n'),
1144 (b"S'\\n'\n.", '\n')]
1145 for p, expected in goodpickles:
1146 self.assertEqual(self.loads(p), expected)
1147
1148 def test_frame_readline(self):
1149 pickled = b'\x80\x04\x95\x05\x00\x00\x00\x00\x00\x00\x00I42\n.'
1150 # 0: \x80 PROTO 4
1151 # 2: \x95 FRAME 5
1152 # 11: I INT 42
1153 # 15: . STOP
1154 self.assertEqual(self.loads(pickled), 42)
1155
1156 def test_compat_unpickle(self):
1157 # xrange(1, 7)
1158 pickled = b'\x80\x02c__builtin__\nxrange\nK\x01K\x07K\x01\x87R.'
1159 unpickled = self.loads(pickled)
1160 self.assertIs(type(unpickled), range)
1161 self.assertEqual(unpickled, range(1, 7))
1162 self.assertEqual(list(unpickled), [1, 2, 3, 4, 5, 6])
1163 # reduce
1164 pickled = b'\x80\x02c__builtin__\nreduce\n.'
1165 self.assertIs(self.loads(pickled), functools.reduce)
1166 # whichdb.whichdb
1167 pickled = b'\x80\x02cwhichdb\nwhichdb\n.'
1168 self.assertIs(self.loads(pickled), dbm.whichdb)
1169 # Exception(), StandardError()
1170 for name in (b'Exception', b'StandardError'):
1171 pickled = (b'\x80\x02cexceptions\n' + name + b'\nU\x03ugh\x85R.')
1172 unpickled = self.loads(pickled)
1173 self.assertIs(type(unpickled), Exception)
1174 self.assertEqual(str(unpickled), 'ugh')
1175 # UserDict.UserDict({1: 2}), UserDict.IterableUserDict({1: 2})
1176 for name in (b'UserDict', b'IterableUserDict'):
1177 pickled = (b'\x80\x02(cUserDict\n' + name +
1178 b'\no}U\x04data}K\x01K\x02ssb.')
1179 unpickled = self.loads(pickled)
1180 self.assertIs(type(unpickled), collections.UserDict)
1181 self.assertEqual(unpickled, collections.UserDict({1: 2}))
1182
1183 def test_bad_reduce(self):
1184 self.assertEqual(self.loads(b'cbuiltins\nint\n)R.'), 0)
1185 self.check_unpickling_error(TypeError, b'N)R.')
1186 self.check_unpickling_error(TypeError, b'cbuiltins\nint\nNR.')
1187
1188 def test_bad_newobj(self):
1189 error = (pickle.UnpicklingError, TypeError)
1190 self.assertEqual(self.loads(b'cbuiltins\nint\n)\x81.'), 0)
1191 self.check_unpickling_error(error, b'cbuiltins\nlen\n)\x81.')
1192 self.check_unpickling_error(error, b'cbuiltins\nint\nN\x81.')
1193
1194 def test_bad_newobj_ex(self):
1195 error = (pickle.UnpicklingError, TypeError)
1196 self.assertEqual(self.loads(b'cbuiltins\nint\n)}\x92.'), 0)
1197 self.check_unpickling_error(error, b'cbuiltins\nlen\n)}\x92.')
1198 self.check_unpickling_error(error, b'cbuiltins\nint\nN}\x92.')
1199 self.check_unpickling_error(error, b'cbuiltins\nint\n)N\x92.')
1200
1201 def test_bad_stack(self):
1202 badpickles = [
1203 b'.', # STOP
1204 b'0', # POP
1205 b'1', # POP_MARK
1206 b'2', # DUP
1207 b'(2',
1208 b'R', # REDUCE
1209 b')R',
1210 b'a', # APPEND
1211 b'Na',
1212 b'b', # BUILD
1213 b'Nb',
1214 b'd', # DICT
1215 b'e', # APPENDS
1216 b'(e',
1217 b'ibuiltins\nlist\n', # INST
1218 b'l', # LIST
1219 b'o', # OBJ
1220 b'(o',
1221 b'p1\n', # PUT
1222 b'q\x00', # BINPUT
1223 b'r\x00\x00\x00\x00', # LONG_BINPUT
1224 b's', # SETITEM
1225 b'Ns',
1226 b'NNs',
1227 b't', # TUPLE
1228 b'u', # SETITEMS
1229 b'(u',
1230 b'}(Nu',
1231 b'\x81', # NEWOBJ
1232 b')\x81',
1233 b'\x85', # TUPLE1
1234 b'\x86', # TUPLE2
1235 b'N\x86',
1236 b'\x87', # TUPLE3
1237 b'N\x87',
1238 b'NN\x87',
1239 b'\x90', # ADDITEMS
1240 b'(\x90',
1241 b'\x91', # FROZENSET
1242 b'\x92', # NEWOBJ_EX
1243 b')}\x92',
1244 b'\x93', # STACK_GLOBAL
1245 b'Vlist\n\x93',
1246 b'\x94', # MEMOIZE
1247 ]
1248 for p in badpickles:
1249 self.check_unpickling_error(self.bad_stack_errors, p)
1250
1251 def test_bad_mark(self):
1252 badpickles = [
1253 b'N(.', # STOP
1254 b'N(2', # DUP
1255 b'cbuiltins\nlist\n)(R', # REDUCE
1256 b'cbuiltins\nlist\n()R',
1257 b']N(a', # APPEND
1258 # BUILD
1259 b'cbuiltins\nValueError\n)R}(b',
1260 b'cbuiltins\nValueError\n)R(}b',
1261 b'(Nd', # DICT
1262 b'N(p1\n', # PUT
1263 b'N(q\x00', # BINPUT
1264 b'N(r\x00\x00\x00\x00', # LONG_BINPUT
1265 b'}NN(s', # SETITEM
1266 b'}N(Ns',
1267 b'}(NNs',
1268 b'}((u', # SETITEMS
1269 b'cbuiltins\nlist\n)(\x81', # NEWOBJ
1270 b'cbuiltins\nlist\n()\x81',
1271 b'N(\x85', # TUPLE1
1272 b'NN(\x86', # TUPLE2
1273 b'N(N\x86',
1274 b'NNN(\x87', # TUPLE3
1275 b'NN(N\x87',
1276 b'N(NN\x87',
1277 b']((\x90', # ADDITEMS
1278 # NEWOBJ_EX
1279 b'cbuiltins\nlist\n)}(\x92',
1280 b'cbuiltins\nlist\n)(}\x92',
1281 b'cbuiltins\nlist\n()}\x92',
1282 # STACK_GLOBAL
1283 b'Vbuiltins\n(Vlist\n\x93',
1284 b'Vbuiltins\nVlist\n(\x93',
1285 b'N(\x94', # MEMOIZE
1286 ]
1287 for p in badpickles:
1288 self.check_unpickling_error(self.bad_stack_errors, p)
1289
1290 def test_truncated_data(self):
1291 self.check_unpickling_error(EOFError, b'')
1292 self.check_unpickling_error(EOFError, b'N')
1293 badpickles = [
1294 b'B', # BINBYTES
1295 b'B\x03\x00\x00',
1296 b'B\x03\x00\x00\x00',
1297 b'B\x03\x00\x00\x00ab',
1298 b'C', # SHORT_BINBYTES
1299 b'C\x03',
1300 b'C\x03ab',
1301 b'F', # FLOAT
1302 b'F0.0',
1303 b'F0.00',
1304 b'G', # BINFLOAT
1305 b'G\x00\x00\x00\x00\x00\x00\x00',
1306 b'I', # INT
1307 b'I0',
1308 b'J', # BININT
1309 b'J\x00\x00\x00',
1310 b'K', # BININT1
1311 b'L', # LONG
1312 b'L0',
1313 b'L10',
1314 b'L0L',
1315 b'L10L',
1316 b'M', # BININT2
1317 b'M\x00',
1318 # b'P', # PERSID
1319 # b'Pabc',
1320 b'S', # STRING
1321 b"S'abc'",
1322 b'T', # BINSTRING
1323 b'T\x03\x00\x00',
1324 b'T\x03\x00\x00\x00',
1325 b'T\x03\x00\x00\x00ab',
1326 b'U', # SHORT_BINSTRING
1327 b'U\x03',
1328 b'U\x03ab',
1329 b'V', # UNICODE
1330 b'Vabc',
1331 b'X', # BINUNICODE
1332 b'X\x03\x00\x00',
1333 b'X\x03\x00\x00\x00',
1334 b'X\x03\x00\x00\x00ab',
1335 b'(c', # GLOBAL
1336 b'(cbuiltins',
1337 b'(cbuiltins\n',
1338 b'(cbuiltins\nlist',
1339 b'Ng', # GET
1340 b'Ng0',
1341 b'(i', # INST
1342 b'(ibuiltins',
1343 b'(ibuiltins\n',
1344 b'(ibuiltins\nlist',
1345 b'Nh', # BINGET
1346 b'Nj', # LONG_BINGET
1347 b'Nj\x00\x00\x00',
1348 b'Np', # PUT
1349 b'Np0',
1350 b'Nq', # BINPUT
1351 b'Nr', # LONG_BINPUT
1352 b'Nr\x00\x00\x00',
1353 b'\x80', # PROTO
1354 b'\x82', # EXT1
1355 b'\x83', # EXT2
1356 b'\x84\x01',
1357 b'\x84', # EXT4
1358 b'\x84\x01\x00\x00',
1359 b'\x8a', # LONG1
1360 b'\x8b', # LONG4
1361 b'\x8b\x00\x00\x00',
1362 b'\x8c', # SHORT_BINUNICODE
1363 b'\x8c\x03',
1364 b'\x8c\x03ab',
1365 b'\x8d', # BINUNICODE8
1366 b'\x8d\x03\x00\x00\x00\x00\x00\x00',
1367 b'\x8d\x03\x00\x00\x00\x00\x00\x00\x00',
1368 b'\x8d\x03\x00\x00\x00\x00\x00\x00\x00ab',
1369 b'\x8e', # BINBYTES8
1370 b'\x8e\x03\x00\x00\x00\x00\x00\x00',
1371 b'\x8e\x03\x00\x00\x00\x00\x00\x00\x00',
1372 b'\x8e\x03\x00\x00\x00\x00\x00\x00\x00ab',
1373 b'\x96', # BYTEARRAY8
1374 b'\x96\x03\x00\x00\x00\x00\x00\x00',
1375 b'\x96\x03\x00\x00\x00\x00\x00\x00\x00',
1376 b'\x96\x03\x00\x00\x00\x00\x00\x00\x00ab',
1377 b'\x95', # FRAME
1378 b'\x95\x02\x00\x00\x00\x00\x00\x00',
1379 b'\x95\x02\x00\x00\x00\x00\x00\x00\x00',
1380 b'\x95\x02\x00\x00\x00\x00\x00\x00\x00N',
1381 ]
1382 for p in badpickles:
1383 self.check_unpickling_error(self.truncated_errors, p)
1384
1385 @threading_helper.reap_threads
1386 @threading_helper.requires_working_threading()
1387 def test_unpickle_module_race(self):
1388 # https://bugs.python.org/issue34572
1389 locker_module = dedent("""
1390 import threading
1391 barrier = threading.Barrier(2)
1392 """)
1393 locking_import_module = dedent("""
1394 import locker
1395 locker.barrier.wait()
1396 class ToBeUnpickled(object):
1397 pass
1398 """)
1399
1400 os.mkdir(TESTFN)
1401 self.addCleanup(shutil.rmtree, TESTFN)
1402 sys.path.insert(0, TESTFN)
1403 self.addCleanup(sys.path.remove, TESTFN)
1404 with open(os.path.join(TESTFN, "locker.py"), "wb") as f:
1405 f.write(locker_module.encode('utf-8'))
1406 with open(os.path.join(TESTFN, "locking_import.py"), "wb") as f:
1407 f.write(locking_import_module.encode('utf-8'))
1408 self.addCleanup(forget, "locker")
1409 self.addCleanup(forget, "locking_import")
1410
1411 import locker
1412
1413 pickle_bytes = (
1414 b'\x80\x03clocking_import\nToBeUnpickled\nq\x00)\x81q\x01.')
1415
1416 # Then try to unpickle two of these simultaneously
1417 # One of them will cause the module import, and we want it to block
1418 # until the other one either:
1419 # - fails (before the patch for this issue)
1420 # - blocks on the import lock for the module, as it should
1421 results = []
1422 barrier = threading.Barrier(3)
1423 def t():
1424 # This ensures the threads have all started
1425 # presumably barrier release is faster than thread startup
1426 barrier.wait()
1427 results.append(pickle.loads(pickle_bytes))
1428
1429 t1 = threading.Thread(target=t)
1430 t2 = threading.Thread(target=t)
1431 t1.start()
1432 t2.start()
1433
1434 barrier.wait()
1435 # could have delay here
1436 locker.barrier.wait()
1437
1438 t1.join()
1439 t2.join()
1440
1441 from locking_import import ToBeUnpickled
1442 self.assertEqual(
1443 [type(x) for x in results],
1444 [ToBeUnpickled] * 2)
1445
1446
1447
1448 class AbstractPickleTests:
1449 # Subclass must define self.dumps, self.loads.
1450
1451 optimized = False
1452
1453 _testdata = AbstractUnpickleTests._testdata
1454
1455 def setUp(self):
1456 pass
1457
1458 assert_is_copy = AbstractUnpickleTests.assert_is_copy
1459
1460 def test_misc(self):
1461 # test various datatypes not tested by testdata
1462 for proto in protocols:
1463 x = myint(4)
1464 s = self.dumps(x, proto)
1465 y = self.loads(s)
1466 self.assert_is_copy(x, y)
1467
1468 x = (1, ())
1469 s = self.dumps(x, proto)
1470 y = self.loads(s)
1471 self.assert_is_copy(x, y)
1472
1473 x = initarg(1, x)
1474 s = self.dumps(x, proto)
1475 y = self.loads(s)
1476 self.assert_is_copy(x, y)
1477
1478 # XXX test __reduce__ protocol?
1479
1480 def test_roundtrip_equality(self):
1481 expected = self._testdata
1482 for proto in protocols:
1483 s = self.dumps(expected, proto)
1484 got = self.loads(s)
1485 self.assert_is_copy(expected, got)
1486
1487 # There are gratuitous differences between pickles produced by
1488 # pickle and cPickle, largely because cPickle starts PUT indices at
1489 # 1 and pickle starts them at 0. See XXX comment in cPickle's put2() --
1490 # there's a comment with an exclamation point there whose meaning
1491 # is a mystery. cPickle also suppresses PUT for objects with a refcount
1492 # of 1.
1493 def dont_test_disassembly(self):
1494 from io import StringIO
1495 from pickletools import dis
1496
1497 for proto, expected in (0, DATA0_DIS), (1, DATA1_DIS):
1498 s = self.dumps(self._testdata, proto)
1499 filelike = StringIO()
1500 dis(s, out=filelike)
1501 got = filelike.getvalue()
1502 self.assertEqual(expected, got)
1503
1504 def _test_recursive_list(self, cls, aslist=identity, minprotocol=0):
1505 # List containing itself.
1506 l = cls()
1507 l.append(l)
1508 for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
1509 s = self.dumps(l, proto)
1510 x = self.loads(s)
1511 self.assertIsInstance(x, cls)
1512 y = aslist(x)
1513 self.assertEqual(len(y), 1)
1514 self.assertIs(y[0], x)
1515
1516 def test_recursive_list(self):
1517 self._test_recursive_list(list)
1518
1519 def test_recursive_list_subclass(self):
1520 self._test_recursive_list(MyList, minprotocol=2)
1521
1522 def test_recursive_list_like(self):
1523 self._test_recursive_list(REX_six, aslist=lambda x: x.items)
1524
1525 def _test_recursive_tuple_and_list(self, cls, aslist=identity, minprotocol=0):
1526 # Tuple containing a list containing the original tuple.
1527 t = (cls(),)
1528 t[0].append(t)
1529 for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
1530 s = self.dumps(t, proto)
1531 x = self.loads(s)
1532 self.assertIsInstance(x, tuple)
1533 self.assertEqual(len(x), 1)
1534 self.assertIsInstance(x[0], cls)
1535 y = aslist(x[0])
1536 self.assertEqual(len(y), 1)
1537 self.assertIs(y[0], x)
1538
1539 # List containing a tuple containing the original list.
1540 t, = t
1541 for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
1542 s = self.dumps(t, proto)
1543 x = self.loads(s)
1544 self.assertIsInstance(x, cls)
1545 y = aslist(x)
1546 self.assertEqual(len(y), 1)
1547 self.assertIsInstance(y[0], tuple)
1548 self.assertEqual(len(y[0]), 1)
1549 self.assertIs(y[0][0], x)
1550
1551 def test_recursive_tuple_and_list(self):
1552 self._test_recursive_tuple_and_list(list)
1553
1554 def test_recursive_tuple_and_list_subclass(self):
1555 self._test_recursive_tuple_and_list(MyList, minprotocol=2)
1556
1557 def test_recursive_tuple_and_list_like(self):
1558 self._test_recursive_tuple_and_list(REX_six, aslist=lambda x: x.items)
1559
1560 def _test_recursive_dict(self, cls, asdict=identity, minprotocol=0):
1561 # Dict containing itself.
1562 d = cls()
1563 d[1] = d
1564 for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
1565 s = self.dumps(d, proto)
1566 x = self.loads(s)
1567 self.assertIsInstance(x, cls)
1568 y = asdict(x)
1569 self.assertEqual(list(y.keys()), [1])
1570 self.assertIs(y[1], x)
1571
1572 def test_recursive_dict(self):
1573 self._test_recursive_dict(dict)
1574
1575 def test_recursive_dict_subclass(self):
1576 self._test_recursive_dict(MyDict, minprotocol=2)
1577
1578 def test_recursive_dict_like(self):
1579 self._test_recursive_dict(REX_seven, asdict=lambda x: x.table)
1580
1581 def _test_recursive_tuple_and_dict(self, cls, asdict=identity, minprotocol=0):
1582 # Tuple containing a dict containing the original tuple.
1583 t = (cls(),)
1584 t[0][1] = t
1585 for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
1586 s = self.dumps(t, proto)
1587 x = self.loads(s)
1588 self.assertIsInstance(x, tuple)
1589 self.assertEqual(len(x), 1)
1590 self.assertIsInstance(x[0], cls)
1591 y = asdict(x[0])
1592 self.assertEqual(list(y), [1])
1593 self.assertIs(y[1], x)
1594
1595 # Dict containing a tuple containing the original dict.
1596 t, = t
1597 for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
1598 s = self.dumps(t, proto)
1599 x = self.loads(s)
1600 self.assertIsInstance(x, cls)
1601 y = asdict(x)
1602 self.assertEqual(list(y), [1])
1603 self.assertIsInstance(y[1], tuple)
1604 self.assertEqual(len(y[1]), 1)
1605 self.assertIs(y[1][0], x)
1606
1607 def test_recursive_tuple_and_dict(self):
1608 self._test_recursive_tuple_and_dict(dict)
1609
1610 def test_recursive_tuple_and_dict_subclass(self):
1611 self._test_recursive_tuple_and_dict(MyDict, minprotocol=2)
1612
1613 def test_recursive_tuple_and_dict_like(self):
1614 self._test_recursive_tuple_and_dict(REX_seven, asdict=lambda x: x.table)
1615
1616 def _test_recursive_dict_key(self, cls, asdict=identity, minprotocol=0):
1617 # Dict containing an immutable object (as key) containing the original
1618 # dict.
1619 d = cls()
1620 d[K(d)] = 1
1621 for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
1622 s = self.dumps(d, proto)
1623 x = self.loads(s)
1624 self.assertIsInstance(x, cls)
1625 y = asdict(x)
1626 self.assertEqual(len(y.keys()), 1)
1627 self.assertIsInstance(list(y.keys())[0], K)
1628 self.assertIs(list(y.keys())[0].value, x)
1629
1630 def test_recursive_dict_key(self):
1631 self._test_recursive_dict_key(dict)
1632
1633 def test_recursive_dict_subclass_key(self):
1634 self._test_recursive_dict_key(MyDict, minprotocol=2)
1635
1636 def test_recursive_dict_like_key(self):
1637 self._test_recursive_dict_key(REX_seven, asdict=lambda x: x.table)
1638
1639 def _test_recursive_tuple_and_dict_key(self, cls, asdict=identity, minprotocol=0):
1640 # Tuple containing a dict containing an immutable object (as key)
1641 # containing the original tuple.
1642 t = (cls(),)
1643 t[0][K(t)] = 1
1644 for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
1645 s = self.dumps(t, proto)
1646 x = self.loads(s)
1647 self.assertIsInstance(x, tuple)
1648 self.assertEqual(len(x), 1)
1649 self.assertIsInstance(x[0], cls)
1650 y = asdict(x[0])
1651 self.assertEqual(len(y), 1)
1652 self.assertIsInstance(list(y.keys())[0], K)
1653 self.assertIs(list(y.keys())[0].value, x)
1654
1655 # Dict containing an immutable object (as key) containing a tuple
1656 # containing the original dict.
1657 t, = t
1658 for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
1659 s = self.dumps(t, proto)
1660 x = self.loads(s)
1661 self.assertIsInstance(x, cls)
1662 y = asdict(x)
1663 self.assertEqual(len(y), 1)
1664 self.assertIsInstance(list(y.keys())[0], K)
1665 self.assertIs(list(y.keys())[0].value[0], x)
1666
1667 def test_recursive_tuple_and_dict_key(self):
1668 self._test_recursive_tuple_and_dict_key(dict)
1669
1670 def test_recursive_tuple_and_dict_subclass_key(self):
1671 self._test_recursive_tuple_and_dict_key(MyDict, minprotocol=2)
1672
1673 def test_recursive_tuple_and_dict_like_key(self):
1674 self._test_recursive_tuple_and_dict_key(REX_seven, asdict=lambda x: x.table)
1675
1676 def test_recursive_set(self):
1677 # Set containing an immutable object containing the original set.
1678 y = set()
1679 y.add(K(y))
1680 for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
1681 s = self.dumps(y, proto)
1682 x = self.loads(s)
1683 self.assertIsInstance(x, set)
1684 self.assertEqual(len(x), 1)
1685 self.assertIsInstance(list(x)[0], K)
1686 self.assertIs(list(x)[0].value, x)
1687
1688 # Immutable object containing a set containing the original object.
1689 y, = y
1690 for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
1691 s = self.dumps(y, proto)
1692 x = self.loads(s)
1693 self.assertIsInstance(x, K)
1694 self.assertIsInstance(x.value, set)
1695 self.assertEqual(len(x.value), 1)
1696 self.assertIs(list(x.value)[0], x)
1697
1698 def test_recursive_inst(self):
1699 # Mutable object containing itself.
1700 i = Object()
1701 i.attr = i
1702 for proto in protocols:
1703 s = self.dumps(i, proto)
1704 x = self.loads(s)
1705 self.assertIsInstance(x, Object)
1706 self.assertEqual(dir(x), dir(i))
1707 self.assertIs(x.attr, x)
1708
1709 def test_recursive_multi(self):
1710 l = []
1711 d = {1:l}
1712 i = Object()
1713 i.attr = d
1714 l.append(i)
1715 for proto in protocols:
1716 s = self.dumps(l, proto)
1717 x = self.loads(s)
1718 self.assertIsInstance(x, list)
1719 self.assertEqual(len(x), 1)
1720 self.assertEqual(dir(x[0]), dir(i))
1721 self.assertEqual(list(x[0].attr.keys()), [1])
1722 self.assertIs(x[0].attr[1], x)
1723
1724 def _test_recursive_collection_and_inst(self, factory):
1725 # Mutable object containing a collection containing the original
1726 # object.
1727 o = Object()
1728 o.attr = factory([o])
1729 t = type(o.attr)
1730 for proto in protocols:
1731 s = self.dumps(o, proto)
1732 x = self.loads(s)
1733 self.assertIsInstance(x.attr, t)
1734 self.assertEqual(len(x.attr), 1)
1735 self.assertIsInstance(list(x.attr)[0], Object)
1736 self.assertIs(list(x.attr)[0], x)
1737
1738 # Collection containing a mutable object containing the original
1739 # collection.
1740 o = o.attr
1741 for proto in protocols:
1742 s = self.dumps(o, proto)
1743 x = self.loads(s)
1744 self.assertIsInstance(x, t)
1745 self.assertEqual(len(x), 1)
1746 self.assertIsInstance(list(x)[0], Object)
1747 self.assertIs(list(x)[0].attr, x)
1748
1749 def test_recursive_list_and_inst(self):
1750 self._test_recursive_collection_and_inst(list)
1751
1752 def test_recursive_tuple_and_inst(self):
1753 self._test_recursive_collection_and_inst(tuple)
1754
1755 def test_recursive_dict_and_inst(self):
1756 self._test_recursive_collection_and_inst(dict.fromkeys)
1757
1758 def test_recursive_set_and_inst(self):
1759 self._test_recursive_collection_and_inst(set)
1760
1761 def test_recursive_frozenset_and_inst(self):
1762 self._test_recursive_collection_and_inst(frozenset)
1763
1764 def test_recursive_list_subclass_and_inst(self):
1765 self._test_recursive_collection_and_inst(MyList)
1766
1767 def test_recursive_tuple_subclass_and_inst(self):
1768 self._test_recursive_collection_and_inst(MyTuple)
1769
1770 def test_recursive_dict_subclass_and_inst(self):
1771 self._test_recursive_collection_and_inst(MyDict.fromkeys)
1772
1773 def test_recursive_set_subclass_and_inst(self):
1774 self._test_recursive_collection_and_inst(MySet)
1775
1776 def test_recursive_frozenset_subclass_and_inst(self):
1777 self._test_recursive_collection_and_inst(MyFrozenSet)
1778
1779 def test_recursive_inst_state(self):
1780 # Mutable object containing itself.
1781 y = REX_state()
1782 y.state = y
1783 for proto in protocols:
1784 s = self.dumps(y, proto)
1785 x = self.loads(s)
1786 self.assertIsInstance(x, REX_state)
1787 self.assertIs(x.state, x)
1788
1789 def test_recursive_tuple_and_inst_state(self):
1790 # Tuple containing a mutable object containing the original tuple.
1791 t = (REX_state(),)
1792 t[0].state = t
1793 for proto in protocols:
1794 s = self.dumps(t, proto)
1795 x = self.loads(s)
1796 self.assertIsInstance(x, tuple)
1797 self.assertEqual(len(x), 1)
1798 self.assertIsInstance(x[0], REX_state)
1799 self.assertIs(x[0].state, x)
1800
1801 # Mutable object containing a tuple containing the object.
1802 t, = t
1803 for proto in protocols:
1804 s = self.dumps(t, proto)
1805 x = self.loads(s)
1806 self.assertIsInstance(x, REX_state)
1807 self.assertIsInstance(x.state, tuple)
1808 self.assertEqual(len(x.state), 1)
1809 self.assertIs(x.state[0], x)
1810
1811 def test_unicode(self):
1812 endcases = ['', '<\\u>', '<\\\u1234>', '<\n>',
1813 '<\\>', '<\\\U00012345>',
1814 # surrogates
1815 '<\udc80>']
1816 for proto in protocols:
1817 for u in endcases:
1818 p = self.dumps(u, proto)
1819 u2 = self.loads(p)
1820 self.assert_is_copy(u, u2)
1821
1822 def test_unicode_high_plane(self):
1823 t = '\U00012345'
1824 for proto in protocols:
1825 p = self.dumps(t, proto)
1826 t2 = self.loads(p)
1827 self.assert_is_copy(t, t2)
1828
1829 def test_unicode_memoization(self):
1830 # Repeated str is re-used (even when escapes added).
1831 for proto in protocols:
1832 for s in '', 'xyz', 'xyz\n', 'x\\yz', 'x\xa1yz\r':
1833 p = self.dumps((s, s), proto)
1834 s1, s2 = self.loads(p)
1835 self.assertIs(s1, s2)
1836
1837 def test_bytes(self):
1838 for proto in protocols:
1839 for s in b'', b'xyz', b'xyz'*100:
1840 p = self.dumps(s, proto)
1841 self.assert_is_copy(s, self.loads(p))
1842 for s in [bytes([i]) for i in range(256)]:
1843 p = self.dumps(s, proto)
1844 self.assert_is_copy(s, self.loads(p))
1845 for s in [bytes([i, i]) for i in range(256)]:
1846 p = self.dumps(s, proto)
1847 self.assert_is_copy(s, self.loads(p))
1848
1849 def test_bytearray(self):
1850 for proto in protocols:
1851 for s in b'', b'xyz', b'xyz'*100:
1852 b = bytearray(s)
1853 p = self.dumps(b, proto)
1854 bb = self.loads(p)
1855 self.assertIsNot(bb, b)
1856 self.assert_is_copy(b, bb)
1857 if proto <= 3:
1858 # bytearray is serialized using a global reference
1859 self.assertIn(b'bytearray', p)
1860 self.assertTrue(opcode_in_pickle(pickle.GLOBAL, p))
1861 elif proto == 4:
1862 self.assertIn(b'bytearray', p)
1863 self.assertTrue(opcode_in_pickle(pickle.STACK_GLOBAL, p))
1864 elif proto == 5:
1865 self.assertNotIn(b'bytearray', p)
1866 self.assertTrue(opcode_in_pickle(pickle.BYTEARRAY8, p))
1867
1868 def test_bytearray_memoization_bug(self):
1869 for proto in protocols:
1870 for s in b'', b'xyz', b'xyz'*100:
1871 b = bytearray(s)
1872 p = self.dumps((b, b), proto)
1873 b1, b2 = self.loads(p)
1874 self.assertIs(b1, b2)
1875
1876 def test_ints(self):
1877 for proto in protocols:
1878 n = sys.maxsize
1879 while n:
1880 for expected in (-n, n):
1881 s = self.dumps(expected, proto)
1882 n2 = self.loads(s)
1883 self.assert_is_copy(expected, n2)
1884 n = n >> 1
1885
1886 def test_long(self):
1887 for proto in protocols:
1888 # 256 bytes is where LONG4 begins.
1889 for nbits in 1, 8, 8*254, 8*255, 8*256, 8*257:
1890 nbase = 1 << nbits
1891 for npos in nbase-1, nbase, nbase+1:
1892 for n in npos, -npos:
1893 pickle = self.dumps(n, proto)
1894 got = self.loads(pickle)
1895 self.assert_is_copy(n, got)
1896 # Try a monster. This is quadratic-time in protos 0 & 1, so don't
1897 # bother with those.
1898 nbase = int("deadbeeffeedface", 16)
1899 nbase += nbase << 1000000
1900 for n in nbase, -nbase:
1901 p = self.dumps(n, 2)
1902 got = self.loads(p)
1903 # assert_is_copy is very expensive here as it precomputes
1904 # a failure message by computing the repr() of n and got,
1905 # we just do the check ourselves.
1906 self.assertIs(type(got), int)
1907 self.assertEqual(n, got)
1908
1909 def test_float(self):
1910 test_values = [0.0, 4.94e-324, 1e-310, 7e-308, 6.626e-34, 0.1, 0.5,
1911 3.14, 263.44582062374053, 6.022e23, 1e30]
1912 test_values = test_values + [-x for x in test_values]
1913 for proto in protocols:
1914 for value in test_values:
1915 pickle = self.dumps(value, proto)
1916 got = self.loads(pickle)
1917 self.assert_is_copy(value, got)
1918
1919 @run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
1920 def test_float_format(self):
1921 # make sure that floats are formatted locale independent with proto 0
1922 self.assertEqual(self.dumps(1.2, 0)[0:3], b'F1.')
1923
1924 def test_reduce(self):
1925 for proto in protocols:
1926 inst = AAA()
1927 dumped = self.dumps(inst, proto)
1928 loaded = self.loads(dumped)
1929 self.assertEqual(loaded, REDUCE_A)
1930
1931 def test_getinitargs(self):
1932 for proto in protocols:
1933 inst = initarg(1, 2)
1934 dumped = self.dumps(inst, proto)
1935 loaded = self.loads(dumped)
1936 self.assert_is_copy(inst, loaded)
1937
1938 def test_metaclass(self):
1939 a = use_metaclass()
1940 for proto in protocols:
1941 s = self.dumps(a, proto)
1942 b = self.loads(s)
1943 self.assertEqual(a.__class__, b.__class__)
1944
1945 def test_dynamic_class(self):
1946 a = create_dynamic_class("my_dynamic_class", (object,))
1947 copyreg.pickle(pickling_metaclass, pickling_metaclass.__reduce__)
1948 for proto in protocols:
1949 s = self.dumps(a, proto)
1950 b = self.loads(s)
1951 self.assertEqual(a, b)
1952 self.assertIs(type(a), type(b))
1953
1954 def test_structseq(self):
1955 import time
1956 import os
1957
1958 t = time.localtime()
1959 for proto in protocols:
1960 s = self.dumps(t, proto)
1961 u = self.loads(s)
1962 self.assert_is_copy(t, u)
1963 t = os.stat(os.curdir)
1964 s = self.dumps(t, proto)
1965 u = self.loads(s)
1966 self.assert_is_copy(t, u)
1967 if hasattr(os, "statvfs"):
1968 t = os.statvfs(os.curdir)
1969 s = self.dumps(t, proto)
1970 u = self.loads(s)
1971 self.assert_is_copy(t, u)
1972
1973 def test_ellipsis(self):
1974 for proto in protocols:
1975 s = self.dumps(..., proto)
1976 u = self.loads(s)
1977 self.assertIs(..., u)
1978
1979 def test_notimplemented(self):
1980 for proto in protocols:
1981 s = self.dumps(NotImplemented, proto)
1982 u = self.loads(s)
1983 self.assertIs(NotImplemented, u)
1984
1985 def test_singleton_types(self):
1986 # Issue #6477: Test that types of built-in singletons can be pickled.
1987 singletons = [None, ..., NotImplemented]
1988 for singleton in singletons:
1989 for proto in protocols:
1990 s = self.dumps(type(singleton), proto)
1991 u = self.loads(s)
1992 self.assertIs(type(singleton), u)
1993
1994 def test_builtin_types(self):
1995 for t in builtins.__dict__.values():
1996 if isinstance(t, type) and not issubclass(t, BaseException):
1997 for proto in protocols:
1998 s = self.dumps(t, proto)
1999 self.assertIs(self.loads(s), t)
2000
2001 def test_builtin_exceptions(self):
2002 for t in builtins.__dict__.values():
2003 if isinstance(t, type) and issubclass(t, BaseException):
2004 for proto in protocols:
2005 s = self.dumps(t, proto)
2006 u = self.loads(s)
2007 if proto <= 2 and issubclass(t, OSError) and t is not BlockingIOError:
2008 self.assertIs(u, OSError)
2009 elif proto <= 2 and issubclass(t, ImportError):
2010 self.assertIs(u, ImportError)
2011 else:
2012 self.assertIs(u, t)
2013
2014 def test_builtin_functions(self):
2015 for t in builtins.__dict__.values():
2016 if isinstance(t, types.BuiltinFunctionType):
2017 for proto in protocols:
2018 s = self.dumps(t, proto)
2019 self.assertIs(self.loads(s), t)
2020
2021 # Tests for protocol 2
2022
2023 def test_proto(self):
2024 for proto in protocols:
2025 pickled = self.dumps(None, proto)
2026 if proto >= 2:
2027 proto_header = pickle.PROTO + bytes([proto])
2028 self.assertTrue(pickled.startswith(proto_header))
2029 else:
2030 self.assertEqual(count_opcode(pickle.PROTO, pickled), 0)
2031
2032 oob = protocols[-1] + 1 # a future protocol
2033 build_none = pickle.NONE + pickle.STOP
2034 badpickle = pickle.PROTO + bytes([oob]) + build_none
2035 try:
2036 self.loads(badpickle)
2037 except ValueError as err:
2038 self.assertIn("unsupported pickle protocol", str(err))
2039 else:
2040 self.fail("expected bad protocol number to raise ValueError")
2041
2042 def test_long1(self):
2043 x = 12345678910111213141516178920
2044 for proto in protocols:
2045 s = self.dumps(x, proto)
2046 y = self.loads(s)
2047 self.assert_is_copy(x, y)
2048 self.assertEqual(opcode_in_pickle(pickle.LONG1, s), proto >= 2)
2049
2050 def test_long4(self):
2051 x = 12345678910111213141516178920 << (256*8)
2052 for proto in protocols:
2053 s = self.dumps(x, proto)
2054 y = self.loads(s)
2055 self.assert_is_copy(x, y)
2056 self.assertEqual(opcode_in_pickle(pickle.LONG4, s), proto >= 2)
2057
2058 def test_short_tuples(self):
2059 # Map (proto, len(tuple)) to expected opcode.
2060 expected_opcode = {(0, 0): pickle.TUPLE,
2061 (0, 1): pickle.TUPLE,
2062 (0, 2): pickle.TUPLE,
2063 (0, 3): pickle.TUPLE,
2064 (0, 4): pickle.TUPLE,
2065
2066 (1, 0): pickle.EMPTY_TUPLE,
2067 (1, 1): pickle.TUPLE,
2068 (1, 2): pickle.TUPLE,
2069 (1, 3): pickle.TUPLE,
2070 (1, 4): pickle.TUPLE,
2071
2072 (2, 0): pickle.EMPTY_TUPLE,
2073 (2, 1): pickle.TUPLE1,
2074 (2, 2): pickle.TUPLE2,
2075 (2, 3): pickle.TUPLE3,
2076 (2, 4): pickle.TUPLE,
2077
2078 (3, 0): pickle.EMPTY_TUPLE,
2079 (3, 1): pickle.TUPLE1,
2080 (3, 2): pickle.TUPLE2,
2081 (3, 3): pickle.TUPLE3,
2082 (3, 4): pickle.TUPLE,
2083 }
2084 a = ()
2085 b = (1,)
2086 c = (1, 2)
2087 d = (1, 2, 3)
2088 e = (1, 2, 3, 4)
2089 for proto in protocols:
2090 for x in a, b, c, d, e:
2091 s = self.dumps(x, proto)
2092 y = self.loads(s)
2093 self.assert_is_copy(x, y)
2094 expected = expected_opcode[min(proto, 3), len(x)]
2095 self.assertTrue(opcode_in_pickle(expected, s))
2096
2097 def test_singletons(self):
2098 # Map (proto, singleton) to expected opcode.
2099 expected_opcode = {(0, None): pickle.NONE,
2100 (1, None): pickle.NONE,
2101 (2, None): pickle.NONE,
2102 (3, None): pickle.NONE,
2103
2104 (0, True): pickle.INT,
2105 (1, True): pickle.INT,
2106 (2, True): pickle.NEWTRUE,
2107 (3, True): pickle.NEWTRUE,
2108
2109 (0, False): pickle.INT,
2110 (1, False): pickle.INT,
2111 (2, False): pickle.NEWFALSE,
2112 (3, False): pickle.NEWFALSE,
2113 }
2114 for proto in protocols:
2115 for x in None, False, True:
2116 s = self.dumps(x, proto)
2117 y = self.loads(s)
2118 self.assertTrue(x is y, (proto, x, s, y))
2119 expected = expected_opcode[min(proto, 3), x]
2120 self.assertTrue(opcode_in_pickle(expected, s))
2121
2122 def test_newobj_tuple(self):
2123 x = MyTuple([1, 2, 3])
2124 x.foo = 42
2125 x.bar = "hello"
2126 for proto in protocols:
2127 s = self.dumps(x, proto)
2128 y = self.loads(s)
2129 self.assert_is_copy(x, y)
2130
2131 def test_newobj_list(self):
2132 x = MyList([1, 2, 3])
2133 x.foo = 42
2134 x.bar = "hello"
2135 for proto in protocols:
2136 s = self.dumps(x, proto)
2137 y = self.loads(s)
2138 self.assert_is_copy(x, y)
2139
2140 def test_newobj_generic(self):
2141 for proto in protocols:
2142 for C in myclasses:
2143 B = C.__base__
2144 x = C(C.sample)
2145 x.foo = 42
2146 s = self.dumps(x, proto)
2147 y = self.loads(s)
2148 detail = (proto, C, B, x, y, type(y))
2149 self.assert_is_copy(x, y) # XXX revisit
2150 self.assertEqual(B(x), B(y), detail)
2151 self.assertEqual(x.__dict__, y.__dict__, detail)
2152
2153 def test_newobj_proxies(self):
2154 # NEWOBJ should use the __class__ rather than the raw type
2155 classes = myclasses[:]
2156 # Cannot create weakproxies to these classes
2157 for c in (MyInt, MyTuple):
2158 classes.remove(c)
2159 for proto in protocols:
2160 for C in classes:
2161 B = C.__base__
2162 x = C(C.sample)
2163 x.foo = 42
2164 p = weakref.proxy(x)
2165 s = self.dumps(p, proto)
2166 y = self.loads(s)
2167 self.assertEqual(type(y), type(x)) # rather than type(p)
2168 detail = (proto, C, B, x, y, type(y))
2169 self.assertEqual(B(x), B(y), detail)
2170 self.assertEqual(x.__dict__, y.__dict__, detail)
2171
2172 def test_newobj_overridden_new(self):
2173 # Test that Python class with C implemented __new__ is pickleable
2174 for proto in protocols:
2175 x = MyIntWithNew2(1)
2176 x.foo = 42
2177 s = self.dumps(x, proto)
2178 y = self.loads(s)
2179 self.assertIs(type(y), MyIntWithNew2)
2180 self.assertEqual(int(y), 1)
2181 self.assertEqual(y.foo, 42)
2182
2183 def test_newobj_not_class(self):
2184 # Issue 24552
2185 global SimpleNewObj
2186 save = SimpleNewObj
2187 o = SimpleNewObj.__new__(SimpleNewObj)
2188 b = self.dumps(o, 4)
2189 try:
2190 SimpleNewObj = 42
2191 self.assertRaises((TypeError, pickle.UnpicklingError), self.loads, b)
2192 finally:
2193 SimpleNewObj = save
2194
2195 # Register a type with copyreg, with extension code extcode. Pickle
2196 # an object of that type. Check that the resulting pickle uses opcode
2197 # (EXT[124]) under proto 2, and not in proto 1.
2198
2199 def produce_global_ext(self, extcode, opcode):
2200 e = ExtensionSaver(extcode)
2201 try:
2202 copyreg.add_extension(__name__, "MyList", extcode)
2203 x = MyList([1, 2, 3])
2204 x.foo = 42
2205 x.bar = "hello"
2206
2207 # Dump using protocol 1 for comparison.
2208 s1 = self.dumps(x, 1)
2209 self.assertIn(__name__.encode("utf-8"), s1)
2210 self.assertIn(b"MyList", s1)
2211 self.assertFalse(opcode_in_pickle(opcode, s1))
2212
2213 y = self.loads(s1)
2214 self.assert_is_copy(x, y)
2215
2216 # Dump using protocol 2 for test.
2217 s2 = self.dumps(x, 2)
2218 self.assertNotIn(__name__.encode("utf-8"), s2)
2219 self.assertNotIn(b"MyList", s2)
2220 self.assertEqual(opcode_in_pickle(opcode, s2), True, repr(s2))
2221
2222 y = self.loads(s2)
2223 self.assert_is_copy(x, y)
2224 finally:
2225 e.restore()
2226
2227 def test_global_ext1(self):
2228 self.produce_global_ext(0x00000001, pickle.EXT1) # smallest EXT1 code
2229 self.produce_global_ext(0x000000ff, pickle.EXT1) # largest EXT1 code
2230
2231 def test_global_ext2(self):
2232 self.produce_global_ext(0x00000100, pickle.EXT2) # smallest EXT2 code
2233 self.produce_global_ext(0x0000ffff, pickle.EXT2) # largest EXT2 code
2234 self.produce_global_ext(0x0000abcd, pickle.EXT2) # check endianness
2235
2236 def test_global_ext4(self):
2237 self.produce_global_ext(0x00010000, pickle.EXT4) # smallest EXT4 code
2238 self.produce_global_ext(0x7fffffff, pickle.EXT4) # largest EXT4 code
2239 self.produce_global_ext(0x12abcdef, pickle.EXT4) # check endianness
2240
2241 def test_list_chunking(self):
2242 n = 10 # too small to chunk
2243 x = list(range(n))
2244 for proto in protocols:
2245 s = self.dumps(x, proto)
2246 y = self.loads(s)
2247 self.assert_is_copy(x, y)
2248 num_appends = count_opcode(pickle.APPENDS, s)
2249 self.assertEqual(num_appends, proto > 0)
2250
2251 n = 2500 # expect at least two chunks when proto > 0
2252 x = list(range(n))
2253 for proto in protocols:
2254 s = self.dumps(x, proto)
2255 y = self.loads(s)
2256 self.assert_is_copy(x, y)
2257 num_appends = count_opcode(pickle.APPENDS, s)
2258 if proto == 0:
2259 self.assertEqual(num_appends, 0)
2260 else:
2261 self.assertTrue(num_appends >= 2)
2262
2263 def test_dict_chunking(self):
2264 n = 10 # too small to chunk
2265 x = dict.fromkeys(range(n))
2266 for proto in protocols:
2267 s = self.dumps(x, proto)
2268 self.assertIsInstance(s, bytes_types)
2269 y = self.loads(s)
2270 self.assert_is_copy(x, y)
2271 num_setitems = count_opcode(pickle.SETITEMS, s)
2272 self.assertEqual(num_setitems, proto > 0)
2273
2274 n = 2500 # expect at least two chunks when proto > 0
2275 x = dict.fromkeys(range(n))
2276 for proto in protocols:
2277 s = self.dumps(x, proto)
2278 y = self.loads(s)
2279 self.assert_is_copy(x, y)
2280 num_setitems = count_opcode(pickle.SETITEMS, s)
2281 if proto == 0:
2282 self.assertEqual(num_setitems, 0)
2283 else:
2284 self.assertTrue(num_setitems >= 2)
2285
2286 def test_set_chunking(self):
2287 n = 10 # too small to chunk
2288 x = set(range(n))
2289 for proto in protocols:
2290 s = self.dumps(x, proto)
2291 y = self.loads(s)
2292 self.assert_is_copy(x, y)
2293 num_additems = count_opcode(pickle.ADDITEMS, s)
2294 if proto < 4:
2295 self.assertEqual(num_additems, 0)
2296 else:
2297 self.assertEqual(num_additems, 1)
2298
2299 n = 2500 # expect at least two chunks when proto >= 4
2300 x = set(range(n))
2301 for proto in protocols:
2302 s = self.dumps(x, proto)
2303 y = self.loads(s)
2304 self.assert_is_copy(x, y)
2305 num_additems = count_opcode(pickle.ADDITEMS, s)
2306 if proto < 4:
2307 self.assertEqual(num_additems, 0)
2308 else:
2309 self.assertGreaterEqual(num_additems, 2)
2310
2311 def test_simple_newobj(self):
2312 x = SimpleNewObj.__new__(SimpleNewObj, 0xface) # avoid __init__
2313 x.abc = 666
2314 for proto in protocols:
2315 with self.subTest(proto=proto):
2316 s = self.dumps(x, proto)
2317 if proto < 1:
2318 self.assertIn(b'\nI64206', s) # INT
2319 else:
2320 self.assertIn(b'M\xce\xfa', s) # BININT2
2321 self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s),
2322 2 <= proto)
2323 self.assertFalse(opcode_in_pickle(pickle.NEWOBJ_EX, s))
2324 y = self.loads(s) # will raise TypeError if __init__ called
2325 self.assert_is_copy(x, y)
2326
2327 def test_complex_newobj(self):
2328 x = ComplexNewObj.__new__(ComplexNewObj, 0xface) # avoid __init__
2329 x.abc = 666
2330 for proto in protocols:
2331 with self.subTest(proto=proto):
2332 s = self.dumps(x, proto)
2333 if proto < 1:
2334 self.assertIn(b'\nI64206', s) # INT
2335 elif proto < 2:
2336 self.assertIn(b'M\xce\xfa', s) # BININT2
2337 elif proto < 4:
2338 self.assertIn(b'X\x04\x00\x00\x00FACE', s) # BINUNICODE
2339 else:
2340 self.assertIn(b'\x8c\x04FACE', s) # SHORT_BINUNICODE
2341 self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s),
2342 2 <= proto)
2343 self.assertFalse(opcode_in_pickle(pickle.NEWOBJ_EX, s))
2344 y = self.loads(s) # will raise TypeError if __init__ called
2345 self.assert_is_copy(x, y)
2346
2347 def test_complex_newobj_ex(self):
2348 x = ComplexNewObjEx.__new__(ComplexNewObjEx, 0xface) # avoid __init__
2349 x.abc = 666
2350 for proto in protocols:
2351 with self.subTest(proto=proto):
2352 s = self.dumps(x, proto)
2353 if proto < 1:
2354 self.assertIn(b'\nI64206', s) # INT
2355 elif proto < 2:
2356 self.assertIn(b'M\xce\xfa', s) # BININT2
2357 elif proto < 4:
2358 self.assertIn(b'X\x04\x00\x00\x00FACE', s) # BINUNICODE
2359 else:
2360 self.assertIn(b'\x8c\x04FACE', s) # SHORT_BINUNICODE
2361 self.assertFalse(opcode_in_pickle(pickle.NEWOBJ, s))
2362 self.assertEqual(opcode_in_pickle(pickle.NEWOBJ_EX, s),
2363 4 <= proto)
2364 y = self.loads(s) # will raise TypeError if __init__ called
2365 self.assert_is_copy(x, y)
2366
2367 def test_newobj_list_slots(self):
2368 x = SlotList([1, 2, 3])
2369 x.foo = 42
2370 x.bar = "hello"
2371 s = self.dumps(x, 2)
2372 y = self.loads(s)
2373 self.assert_is_copy(x, y)
2374
2375 def test_reduce_overrides_default_reduce_ex(self):
2376 for proto in protocols:
2377 x = REX_one()
2378 self.assertEqual(x._reduce_called, 0)
2379 s = self.dumps(x, proto)
2380 self.assertEqual(x._reduce_called, 1)
2381 y = self.loads(s)
2382 self.assertEqual(y._reduce_called, 0)
2383
2384 def test_reduce_ex_called(self):
2385 for proto in protocols:
2386 x = REX_two()
2387 self.assertEqual(x._proto, None)
2388 s = self.dumps(x, proto)
2389 self.assertEqual(x._proto, proto)
2390 y = self.loads(s)
2391 self.assertEqual(y._proto, None)
2392
2393 def test_reduce_ex_overrides_reduce(self):
2394 for proto in protocols:
2395 x = REX_three()
2396 self.assertEqual(x._proto, None)
2397 s = self.dumps(x, proto)
2398 self.assertEqual(x._proto, proto)
2399 y = self.loads(s)
2400 self.assertEqual(y._proto, None)
2401
2402 def test_reduce_ex_calls_base(self):
2403 for proto in protocols:
2404 x = REX_four()
2405 self.assertEqual(x._proto, None)
2406 s = self.dumps(x, proto)
2407 self.assertEqual(x._proto, proto)
2408 y = self.loads(s)
2409 self.assertEqual(y._proto, proto)
2410
2411 def test_reduce_calls_base(self):
2412 for proto in protocols:
2413 x = REX_five()
2414 self.assertEqual(x._reduce_called, 0)
2415 s = self.dumps(x, proto)
2416 self.assertEqual(x._reduce_called, 1)
2417 y = self.loads(s)
2418 self.assertEqual(y._reduce_called, 1)
2419
2420 @no_tracing
2421 def test_bad_getattr(self):
2422 # Issue #3514: crash when there is an infinite loop in __getattr__
2423 x = BadGetattr()
2424 for proto in range(2):
2425 with support.infinite_recursion():
2426 self.assertRaises(RuntimeError, self.dumps, x, proto)
2427 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
2428 s = self.dumps(x, proto)
2429
2430 def test_reduce_bad_iterator(self):
2431 # Issue4176: crash when 4th and 5th items of __reduce__()
2432 # are not iterators
2433 class C(object):
2434 def __reduce__(self):
2435 # 4th item is not an iterator
2436 return list, (), None, [], None
2437 class D(object):
2438 def __reduce__(self):
2439 # 5th item is not an iterator
2440 return dict, (), None, None, []
2441
2442 # Python implementation is less strict and also accepts iterables.
2443 for proto in protocols:
2444 try:
2445 self.dumps(C(), proto)
2446 except pickle.PicklingError:
2447 pass
2448 try:
2449 self.dumps(D(), proto)
2450 except pickle.PicklingError:
2451 pass
2452
2453 def test_many_puts_and_gets(self):
2454 # Test that internal data structures correctly deal with lots of
2455 # puts/gets.
2456 keys = ("aaa" + str(i) for i in range(100))
2457 large_dict = dict((k, [4, 5, 6]) for k in keys)
2458 obj = [dict(large_dict), dict(large_dict), dict(large_dict)]
2459
2460 for proto in protocols:
2461 with self.subTest(proto=proto):
2462 dumped = self.dumps(obj, proto)
2463 loaded = self.loads(dumped)
2464 self.assert_is_copy(obj, loaded)
2465
2466 @impl_detail("pypy does not store attribute names", pypy=False)
2467 def test_attribute_name_interning(self):
2468 # Test that attribute names of pickled objects are interned when
2469 # unpickling.
2470 for proto in protocols:
2471 x = C()
2472 x.foo = 42
2473 x.bar = "hello"
2474 s = self.dumps(x, proto)
2475 y = self.loads(s)
2476 x_keys = sorted(x.__dict__)
2477 y_keys = sorted(y.__dict__)
2478 for x_key, y_key in zip(x_keys, y_keys):
2479 self.assertIs(x_key, y_key)
2480
2481 @impl_detail("This test is too strong indeed", pypy=False)
2482 def test_pickle_to_2x(self):
2483 # Pickle non-trivial data with protocol 2, expecting that it yields
2484 # the same result as Python 2.x did.
2485 # NOTE: this test is a bit too strong since we can produce different
2486 # bytecode that 2.x will still understand.
2487 dumped = self.dumps(range(5), 2)
2488 self.assertEqual(dumped, DATA_XRANGE)
2489 dumped = self.dumps(set([3]), 2)
2490 self.assertEqual(dumped, DATA_SET2)
2491
2492 def test_large_pickles(self):
2493 # Test the correctness of internal buffering routines when handling
2494 # large data.
2495 for proto in protocols:
2496 data = (1, min, b'xy' * (30 * 1024), len)
2497 dumped = self.dumps(data, proto)
2498 loaded = self.loads(dumped)
2499 self.assertEqual(len(loaded), len(data))
2500 self.assertEqual(loaded, data)
2501
2502 def test_int_pickling_efficiency(self):
2503 # Test compacity of int representation (see issue #12744)
2504 for proto in protocols:
2505 with self.subTest(proto=proto):
2506 pickles = [self.dumps(2**n, proto) for n in range(70)]
2507 sizes = list(map(len, pickles))
2508 # the size function is monotonic
2509 self.assertEqual(sorted(sizes), sizes)
2510 if proto >= 2:
2511 for p in pickles:
2512 self.assertFalse(opcode_in_pickle(pickle.LONG, p))
2513
2514 def _check_pickling_with_opcode(self, obj, opcode, proto):
2515 pickled = self.dumps(obj, proto)
2516 self.assertTrue(opcode_in_pickle(opcode, pickled))
2517 unpickled = self.loads(pickled)
2518 self.assertEqual(obj, unpickled)
2519
2520 def test_appends_on_non_lists(self):
2521 # Issue #17720
2522 obj = REX_six([1, 2, 3])
2523 for proto in protocols:
2524 if proto == 0:
2525 self._check_pickling_with_opcode(obj, pickle.APPEND, proto)
2526 else:
2527 self._check_pickling_with_opcode(obj, pickle.APPENDS, proto)
2528
2529 def test_setitems_on_non_dicts(self):
2530 obj = REX_seven({1: -1, 2: -2, 3: -3})
2531 for proto in protocols:
2532 if proto == 0:
2533 self._check_pickling_with_opcode(obj, pickle.SETITEM, proto)
2534 else:
2535 self._check_pickling_with_opcode(obj, pickle.SETITEMS, proto)
2536
2537 # Exercise framing (proto >= 4) for significant workloads
2538
2539 FRAME_SIZE_MIN = 4
2540 FRAME_SIZE_TARGET = 64 * 1024
2541
2542 def check_frame_opcodes(self, pickled):
2543 """
2544 Check the arguments of FRAME opcodes in a protocol 4+ pickle.
2545
2546 Note that binary objects that are larger than FRAME_SIZE_TARGET are not
2547 framed by default and are therefore considered a frame by themselves in
2548 the following consistency check.
2549 """
2550 frame_end = frameless_start = None
2551 frameless_opcodes = {'BINBYTES', 'BINUNICODE', 'BINBYTES8',
2552 'BINUNICODE8', 'BYTEARRAY8'}
2553 for op, arg, pos in pickletools.genops(pickled):
2554 if frame_end is not None:
2555 self.assertLessEqual(pos, frame_end)
2556 if pos == frame_end:
2557 frame_end = None
2558
2559 if frame_end is not None: # framed
2560 self.assertNotEqual(op.name, 'FRAME')
2561 if op.name in frameless_opcodes:
2562 # Only short bytes and str objects should be written
2563 # in a frame
2564 self.assertLessEqual(len(arg), self.FRAME_SIZE_TARGET)
2565
2566 else: # not framed
2567 if (op.name == 'FRAME' or
2568 (op.name in frameless_opcodes and
2569 len(arg) > self.FRAME_SIZE_TARGET)):
2570 # Frame or large bytes or str object
2571 if frameless_start is not None:
2572 # Only short data should be written outside of a frame
2573 self.assertLess(pos - frameless_start,
2574 self.FRAME_SIZE_MIN)
2575 frameless_start = None
2576 elif frameless_start is None and op.name != 'PROTO':
2577 frameless_start = pos
2578
2579 if op.name == 'FRAME':
2580 self.assertGreaterEqual(arg, self.FRAME_SIZE_MIN)
2581 frame_end = pos + 9 + arg
2582
2583 pos = len(pickled)
2584 if frame_end is not None:
2585 self.assertEqual(frame_end, pos)
2586 elif frameless_start is not None:
2587 self.assertLess(pos - frameless_start, self.FRAME_SIZE_MIN)
2588
2589 @support.skip_if_pgo_task
2590 @support.requires_resource('cpu')
2591 def test_framing_many_objects(self):
2592 obj = list(range(10**5))
2593 for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
2594 with self.subTest(proto=proto):
2595 pickled = self.dumps(obj, proto)
2596 unpickled = self.loads(pickled)
2597 self.assertEqual(obj, unpickled)
2598 bytes_per_frame = (len(pickled) /
2599 count_opcode(pickle.FRAME, pickled))
2600 self.assertGreater(bytes_per_frame,
2601 self.FRAME_SIZE_TARGET / 2)
2602 self.assertLessEqual(bytes_per_frame,
2603 self.FRAME_SIZE_TARGET * 1)
2604 self.check_frame_opcodes(pickled)
2605
2606 def test_framing_large_objects(self):
2607 N = 1024 * 1024
2608 small_items = [[i] for i in range(10)]
2609 obj = [b'x' * N, *small_items, b'y' * N, 'z' * N]
2610 for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
2611 for fast in [False, True]:
2612 with self.subTest(proto=proto, fast=fast):
2613 if not fast:
2614 # fast=False by default.
2615 # This covers in-memory pickling with pickle.dumps().
2616 pickled = self.dumps(obj, proto)
2617 else:
2618 # Pickler is required when fast=True.
2619 if not hasattr(self, 'pickler'):
2620 continue
2621 buf = io.BytesIO()
2622 pickler = self.pickler(buf, protocol=proto)
2623 pickler.fast = fast
2624 pickler.dump(obj)
2625 pickled = buf.getvalue()
2626 unpickled = self.loads(pickled)
2627 # More informative error message in case of failure.
2628 self.assertEqual([len(x) for x in obj],
2629 [len(x) for x in unpickled])
2630 # Perform full equality check if the lengths match.
2631 self.assertEqual(obj, unpickled)
2632 n_frames = count_opcode(pickle.FRAME, pickled)
2633 # A single frame for small objects between
2634 # first two large objects.
2635 self.assertEqual(n_frames, 1)
2636 self.check_frame_opcodes(pickled)
2637
2638 def test_optional_frames(self):
2639 if pickle.HIGHEST_PROTOCOL < 4:
2640 return
2641
2642 def remove_frames(pickled, keep_frame=None):
2643 """Remove frame opcodes from the given pickle."""
2644 frame_starts = []
2645 # 1 byte for the opcode and 8 for the argument
2646 frame_opcode_size = 9
2647 for opcode, _, pos in pickletools.genops(pickled):
2648 if opcode.name == 'FRAME':
2649 frame_starts.append(pos)
2650
2651 newpickle = bytearray()
2652 last_frame_end = 0
2653 for i, pos in enumerate(frame_starts):
2654 if keep_frame and keep_frame(i):
2655 continue
2656 newpickle += pickled[last_frame_end:pos]
2657 last_frame_end = pos + frame_opcode_size
2658 newpickle += pickled[last_frame_end:]
2659 return newpickle
2660
2661 frame_size = self.FRAME_SIZE_TARGET
2662 num_frames = 20
2663 # Large byte objects (dict values) intermittent with small objects
2664 # (dict keys)
2665 for bytes_type in (bytes, bytearray):
2666 obj = {i: bytes_type([i]) * frame_size for i in range(num_frames)}
2667
2668 for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
2669 pickled = self.dumps(obj, proto)
2670
2671 frameless_pickle = remove_frames(pickled)
2672 self.assertEqual(count_opcode(pickle.FRAME, frameless_pickle), 0)
2673 self.assertEqual(obj, self.loads(frameless_pickle))
2674
2675 some_frames_pickle = remove_frames(pickled, lambda i: i % 2)
2676 self.assertLess(count_opcode(pickle.FRAME, some_frames_pickle),
2677 count_opcode(pickle.FRAME, pickled))
2678 self.assertEqual(obj, self.loads(some_frames_pickle))
2679
2680 @support.skip_if_pgo_task
2681 def test_framed_write_sizes_with_delayed_writer(self):
2682 class ChunkAccumulator:
2683 """Accumulate pickler output in a list of raw chunks."""
2684 def __init__(self):
2685 self.chunks = []
2686 def write(self, chunk):
2687 self.chunks.append(chunk)
2688 def concatenate_chunks(self):
2689 return b"".join(self.chunks)
2690
2691 for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
2692 objects = [(str(i).encode('ascii'), i % 42, {'i': str(i)})
2693 for i in range(int(1e4))]
2694 # Add a large unique ASCII string
2695 objects.append('0123456789abcdef' *
2696 (self.FRAME_SIZE_TARGET // 16 + 1))
2697
2698 # Protocol 4 packs groups of small objects into frames and issues
2699 # calls to write only once or twice per frame:
2700 # The C pickler issues one call to write per-frame (header and
2701 # contents) while Python pickler issues two calls to write: one for
2702 # the frame header and one for the frame binary contents.
2703 writer = ChunkAccumulator()
2704 self.pickler(writer, proto).dump(objects)
2705
2706 # Actually read the binary content of the chunks after the end
2707 # of the call to dump: any memoryview passed to write should not
2708 # be released otherwise this delayed access would not be possible.
2709 pickled = writer.concatenate_chunks()
2710 reconstructed = self.loads(pickled)
2711 self.assertEqual(reconstructed, objects)
2712 self.assertGreater(len(writer.chunks), 1)
2713
2714 # memoryviews should own the memory.
2715 del objects
2716 support.gc_collect()
2717 self.assertEqual(writer.concatenate_chunks(), pickled)
2718
2719 n_frames = (len(pickled) - 1) // self.FRAME_SIZE_TARGET + 1
2720 # There should be at least one call to write per frame
2721 self.assertGreaterEqual(len(writer.chunks), n_frames)
2722
2723 # but not too many either: there can be one for the proto,
2724 # one per-frame header, one per frame for the actual contents,
2725 # and two for the header.
2726 self.assertLessEqual(len(writer.chunks), 2 * n_frames + 3)
2727
2728 chunk_sizes = [len(c) for c in writer.chunks]
2729 large_sizes = [s for s in chunk_sizes
2730 if s >= self.FRAME_SIZE_TARGET]
2731 medium_sizes = [s for s in chunk_sizes
2732 if 9 < s < self.FRAME_SIZE_TARGET]
2733 small_sizes = [s for s in chunk_sizes if s <= 9]
2734
2735 # Large chunks should not be too large:
2736 for chunk_size in large_sizes:
2737 self.assertLess(chunk_size, 2 * self.FRAME_SIZE_TARGET,
2738 chunk_sizes)
2739 # There shouldn't bee too many small chunks: the protocol header,
2740 # the frame headers and the large string headers are written
2741 # in small chunks.
2742 self.assertLessEqual(len(small_sizes),
2743 len(large_sizes) + len(medium_sizes) + 3,
2744 chunk_sizes)
2745
2746 def test_nested_names(self):
2747 global Nested
2748 class Nested:
2749 class A:
2750 class B:
2751 class C:
2752 pass
2753 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2754 for obj in [Nested.A, Nested.A.B, Nested.A.B.C]:
2755 with self.subTest(proto=proto, obj=obj):
2756 unpickled = self.loads(self.dumps(obj, proto))
2757 self.assertIs(obj, unpickled)
2758
2759 def test_recursive_nested_names(self):
2760 global Recursive
2761 class Recursive:
2762 pass
2763 Recursive.mod = sys.modules[Recursive.__module__]
2764 Recursive.__qualname__ = 'Recursive.mod.Recursive'
2765 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2766 with self.subTest(proto=proto):
2767 unpickled = self.loads(self.dumps(Recursive, proto))
2768 self.assertIs(unpickled, Recursive)
2769 del Recursive.mod # break reference loop
2770
2771 def test_py_methods(self):
2772 global PyMethodsTest
2773 class PyMethodsTest:
2774 @staticmethod
2775 def cheese():
2776 return "cheese"
2777 @classmethod
2778 def wine(cls):
2779 assert cls is PyMethodsTest
2780 return "wine"
2781 def biscuits(self):
2782 assert isinstance(self, PyMethodsTest)
2783 return "biscuits"
2784 class Nested:
2785 "Nested class"
2786 @staticmethod
2787 def ketchup():
2788 return "ketchup"
2789 @classmethod
2790 def maple(cls):
2791 assert cls is PyMethodsTest.Nested
2792 return "maple"
2793 def pie(self):
2794 assert isinstance(self, PyMethodsTest.Nested)
2795 return "pie"
2796
2797 py_methods = (
2798 PyMethodsTest.cheese,
2799 PyMethodsTest.wine,
2800 PyMethodsTest().biscuits,
2801 PyMethodsTest.Nested.ketchup,
2802 PyMethodsTest.Nested.maple,
2803 PyMethodsTest.Nested().pie
2804 )
2805 py_unbound_methods = (
2806 (PyMethodsTest.biscuits, PyMethodsTest),
2807 (PyMethodsTest.Nested.pie, PyMethodsTest.Nested)
2808 )
2809 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2810 for method in py_methods:
2811 with self.subTest(proto=proto, method=method):
2812 unpickled = self.loads(self.dumps(method, proto))
2813 self.assertEqual(method(), unpickled())
2814 for method, cls in py_unbound_methods:
2815 obj = cls()
2816 with self.subTest(proto=proto, method=method):
2817 unpickled = self.loads(self.dumps(method, proto))
2818 self.assertEqual(method(obj), unpickled(obj))
2819
2820 descriptors = (
2821 PyMethodsTest.__dict__['cheese'], # static method descriptor
2822 PyMethodsTest.__dict__['wine'], # class method descriptor
2823 )
2824 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2825 for descr in descriptors:
2826 with self.subTest(proto=proto, descr=descr):
2827 self.assertRaises(TypeError, self.dumps, descr, proto)
2828
2829 def test_c_methods(self):
2830 global Subclass
2831 class Subclass(tuple):
2832 class Nested(str):
2833 pass
2834
2835 c_methods = (
2836 # bound built-in method
2837 ("abcd".index, ("c",)),
2838 # unbound built-in method
2839 (str.index, ("abcd", "c")),
2840 # bound "slot" method
2841 ([1, 2, 3].__len__, ()),
2842 # unbound "slot" method
2843 (list.__len__, ([1, 2, 3],)),
2844 # bound "coexist" method
2845 ({1, 2}.__contains__, (2,)),
2846 # unbound "coexist" method
2847 (set.__contains__, ({1, 2}, 2)),
2848 # built-in class method
2849 (dict.fromkeys, (("a", 1), ("b", 2))),
2850 # built-in static method
2851 (bytearray.maketrans, (b"abc", b"xyz")),
2852 # subclass methods
2853 (Subclass([1,2,2]).count, (2,)),
2854 (Subclass.count, (Subclass([1,2,2]), 2)),
2855 (Subclass.Nested("sweet").count, ("e",)),
2856 (Subclass.Nested.count, (Subclass.Nested("sweet"), "e")),
2857 )
2858 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2859 for method, args in c_methods:
2860 with self.subTest(proto=proto, method=method):
2861 unpickled = self.loads(self.dumps(method, proto))
2862 self.assertEqual(method(*args), unpickled(*args))
2863
2864 descriptors = (
2865 bytearray.__dict__['maketrans'], # built-in static method descriptor
2866 dict.__dict__['fromkeys'], # built-in class method descriptor
2867 )
2868 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2869 for descr in descriptors:
2870 with self.subTest(proto=proto, descr=descr):
2871 self.assertRaises(TypeError, self.dumps, descr, proto)
2872
2873 def test_compat_pickle(self):
2874 tests = [
2875 (range(1, 7), '__builtin__', 'xrange'),
2876 (map(int, '123'), 'itertools', 'imap'),
2877 (functools.reduce, '__builtin__', 'reduce'),
2878 (dbm.whichdb, 'whichdb', 'whichdb'),
2879 (Exception(), 'exceptions', 'Exception'),
2880 (collections.UserDict(), 'UserDict', 'IterableUserDict'),
2881 (collections.UserList(), 'UserList', 'UserList'),
2882 (collections.defaultdict(), 'collections', 'defaultdict'),
2883 ]
2884 for val, mod, name in tests:
2885 for proto in range(3):
2886 with self.subTest(type=type(val), proto=proto):
2887 pickled = self.dumps(val, proto)
2888 self.assertIn(('c%s\n%s' % (mod, name)).encode(), pickled)
2889 self.assertIs(type(self.loads(pickled)), type(val))
2890
2891 def test_local_lookup_error(self):
2892 # Test that whichmodule() errors out cleanly when looking up
2893 # an assumed globally-reachable object fails.
2894 def f():
2895 pass
2896 # Since the function is local, lookup will fail
2897 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
2898 with self.assertRaises((AttributeError, pickle.PicklingError)):
2899 pickletools.dis(self.dumps(f, proto))
2900 # Same without a __module__ attribute (exercises a different path
2901 # in _pickle.c).
2902 del f.__module__
2903 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
2904 with self.assertRaises((AttributeError, pickle.PicklingError)):
2905 pickletools.dis(self.dumps(f, proto))
2906 # Yet a different path.
2907 f.__name__ = f.__qualname__
2908 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
2909 with self.assertRaises((AttributeError, pickle.PicklingError)):
2910 pickletools.dis(self.dumps(f, proto))
2911
2912 #
2913 # PEP 574 tests below
2914 #
2915
2916 def buffer_like_objects(self):
2917 # Yield buffer-like objects with the bytestring "abcdef" in them
2918 bytestring = b"abcdefgh"
2919 yield ZeroCopyBytes(bytestring)
2920 yield ZeroCopyBytearray(bytestring)
2921 if _testbuffer is not None:
2922 items = list(bytestring)
2923 value = int.from_bytes(bytestring, byteorder='little')
2924 for flags in (0, _testbuffer.ND_WRITABLE):
2925 # 1-D, contiguous
2926 yield PicklableNDArray(items, format='B', shape=(8,),
2927 flags=flags)
2928 # 2-D, C-contiguous
2929 yield PicklableNDArray(items, format='B', shape=(4, 2),
2930 strides=(2, 1), flags=flags)
2931 # 2-D, Fortran-contiguous
2932 yield PicklableNDArray(items, format='B',
2933 shape=(4, 2), strides=(1, 4),
2934 flags=flags)
2935
2936 def test_in_band_buffers(self):
2937 # Test in-band buffers (PEP 574)
2938 for obj in self.buffer_like_objects():
2939 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
2940 data = self.dumps(obj, proto)
2941 if obj.c_contiguous and proto >= 5:
2942 # The raw memory bytes are serialized in physical order
2943 self.assertIn(b"abcdefgh", data)
2944 self.assertEqual(count_opcode(pickle.NEXT_BUFFER, data), 0)
2945 if proto >= 5:
2946 self.assertEqual(count_opcode(pickle.SHORT_BINBYTES, data),
2947 1 if obj.readonly else 0)
2948 self.assertEqual(count_opcode(pickle.BYTEARRAY8, data),
2949 0 if obj.readonly else 1)
2950 # Return a true value from buffer_callback should have
2951 # the same effect
2952 def buffer_callback(obj):
2953 return True
2954 data2 = self.dumps(obj, proto,
2955 buffer_callback=buffer_callback)
2956 self.assertEqual(data2, data)
2957
2958 new = self.loads(data)
2959 # It's a copy
2960 self.assertIsNot(new, obj)
2961 self.assertIs(type(new), type(obj))
2962 self.assertEqual(new, obj)
2963
2964 # XXX Unfortunately cannot test non-contiguous array
2965 # (see comment in PicklableNDArray.__reduce_ex__)
2966
2967 def test_oob_buffers(self):
2968 # Test out-of-band buffers (PEP 574)
2969 for obj in self.buffer_like_objects():
2970 for proto in range(0, 5):
2971 # Need protocol >= 5 for buffer_callback
2972 with self.assertRaises(ValueError):
2973 self.dumps(obj, proto,
2974 buffer_callback=[].append)
2975 for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
2976 buffers = []
2977 buffer_callback = lambda pb: buffers.append(pb.raw())
2978 data = self.dumps(obj, proto,
2979 buffer_callback=buffer_callback)
2980 self.assertNotIn(b"abcdefgh", data)
2981 self.assertEqual(count_opcode(pickle.SHORT_BINBYTES, data), 0)
2982 self.assertEqual(count_opcode(pickle.BYTEARRAY8, data), 0)
2983 self.assertEqual(count_opcode(pickle.NEXT_BUFFER, data), 1)
2984 self.assertEqual(count_opcode(pickle.READONLY_BUFFER, data),
2985 1 if obj.readonly else 0)
2986
2987 if obj.c_contiguous:
2988 self.assertEqual(bytes(buffers[0]), b"abcdefgh")
2989 # Need buffers argument to unpickle properly
2990 with self.assertRaises(pickle.UnpicklingError):
2991 self.loads(data)
2992
2993 new = self.loads(data, buffers=buffers)
2994 if obj.zero_copy_reconstruct:
2995 # Zero-copy achieved
2996 self.assertIs(new, obj)
2997 else:
2998 self.assertIs(type(new), type(obj))
2999 self.assertEqual(new, obj)
3000 # Non-sequence buffers accepted too
3001 new = self.loads(data, buffers=iter(buffers))
3002 if obj.zero_copy_reconstruct:
3003 # Zero-copy achieved
3004 self.assertIs(new, obj)
3005 else:
3006 self.assertIs(type(new), type(obj))
3007 self.assertEqual(new, obj)
3008
3009 def test_oob_buffers_writable_to_readonly(self):
3010 # Test reconstructing readonly object from writable buffer
3011 obj = ZeroCopyBytes(b"foobar")
3012 for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
3013 buffers = []
3014 buffer_callback = buffers.append
3015 data = self.dumps(obj, proto, buffer_callback=buffer_callback)
3016
3017 buffers = map(bytearray, buffers)
3018 new = self.loads(data, buffers=buffers)
3019 self.assertIs(type(new), type(obj))
3020 self.assertEqual(new, obj)
3021
3022 def test_picklebuffer_error(self):
3023 # PickleBuffer forbidden with protocol < 5
3024 pb = pickle.PickleBuffer(b"foobar")
3025 for proto in range(0, 5):
3026 with self.assertRaises(pickle.PickleError):
3027 self.dumps(pb, proto)
3028
3029 def test_buffer_callback_error(self):
3030 def buffer_callback(buffers):
3031 1/0
3032 pb = pickle.PickleBuffer(b"foobar")
3033 with self.assertRaises(ZeroDivisionError):
3034 self.dumps(pb, 5, buffer_callback=buffer_callback)
3035
3036 def test_buffers_error(self):
3037 pb = pickle.PickleBuffer(b"foobar")
3038 for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
3039 data = self.dumps(pb, proto, buffer_callback=[].append)
3040 # Non iterable buffers
3041 with self.assertRaises(TypeError):
3042 self.loads(data, buffers=object())
3043 # Buffer iterable exhausts too early
3044 with self.assertRaises(pickle.UnpicklingError):
3045 self.loads(data, buffers=[])
3046
3047 def test_inband_accept_default_buffers_argument(self):
3048 for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
3049 data_pickled = self.dumps(1, proto, buffer_callback=None)
3050 data = self.loads(data_pickled, buffers=None)
3051
3052 @unittest.skipIf(np is None, "Test needs Numpy")
3053 def test_buffers_numpy(self):
3054 def check_no_copy(x, y):
3055 np.testing.assert_equal(x, y)
3056 self.assertEqual(x.ctypes.data, y.ctypes.data)
3057
3058 def check_copy(x, y):
3059 np.testing.assert_equal(x, y)
3060 self.assertNotEqual(x.ctypes.data, y.ctypes.data)
3061
3062 def check_array(arr):
3063 # In-band
3064 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
3065 data = self.dumps(arr, proto)
3066 new = self.loads(data)
3067 check_copy(arr, new)
3068 for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
3069 buffer_callback = lambda _: True
3070 data = self.dumps(arr, proto, buffer_callback=buffer_callback)
3071 new = self.loads(data)
3072 check_copy(arr, new)
3073 # Out-of-band
3074 for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
3075 buffers = []
3076 buffer_callback = buffers.append
3077 data = self.dumps(arr, proto, buffer_callback=buffer_callback)
3078 new = self.loads(data, buffers=buffers)
3079 if arr.flags.c_contiguous or arr.flags.f_contiguous:
3080 check_no_copy(arr, new)
3081 else:
3082 check_copy(arr, new)
3083
3084 # 1-D
3085 arr = np.arange(6)
3086 check_array(arr)
3087 # 1-D, non-contiguous
3088 check_array(arr[::2])
3089 # 2-D, C-contiguous
3090 arr = np.arange(12).reshape((3, 4))
3091 check_array(arr)
3092 # 2-D, F-contiguous
3093 check_array(arr.T)
3094 # 2-D, non-contiguous
3095 check_array(arr[::2])
3096
3097 def test_evil_class_mutating_dict(self):
3098 # https://github.com/python/cpython/issues/92930
3099 from random import getrandbits
3100
3101 global Bad
3102 class Bad:
3103 def __eq__(self, other):
3104 return ENABLED
3105 def __hash__(self):
3106 return 42
3107 def __reduce__(self):
3108 if getrandbits(6) == 0:
3109 collection.clear()
3110 return (Bad, ())
3111
3112 for proto in protocols:
3113 for _ in range(20):
3114 ENABLED = False
3115 collection = {Bad(): Bad() for _ in range(20)}
3116 for bad in collection:
3117 bad.bad = bad
3118 bad.collection = collection
3119 ENABLED = True
3120 try:
3121 data = self.dumps(collection, proto)
3122 self.loads(data)
3123 except RuntimeError as e:
3124 expected = "changed size during iteration"
3125 self.assertIn(expected, str(e))
3126
3127 def test_evil_pickler_mutating_collection(self):
3128 # https://github.com/python/cpython/issues/92930
3129 if not hasattr(self, "pickler"):
3130 raise self.skipTest(f"{type(self)} has no associated pickler type")
3131
3132 global Clearer
3133 class Clearer:
3134 pass
3135
3136 def check(collection):
3137 class EvilPickler(self.pickler):
3138 def persistent_id(self, obj):
3139 if isinstance(obj, Clearer):
3140 collection.clear()
3141 return None
3142 pickler = EvilPickler(io.BytesIO(), proto)
3143 try:
3144 pickler.dump(collection)
3145 except RuntimeError as e:
3146 expected = "changed size during iteration"
3147 self.assertIn(expected, str(e))
3148
3149 for proto in protocols:
3150 check([Clearer()])
3151 check([Clearer(), Clearer()])
3152 check({Clearer()})
3153 check({Clearer(), Clearer()})
3154 check({Clearer(): 1})
3155 check({Clearer(): 1, Clearer(): 2})
3156 check({1: Clearer(), 2: Clearer()})
3157
3158
3159 class BigmemPickleTests:
3160
3161 # Binary protocols can serialize longs of up to 2 GiB-1
3162
3163 @bigmemtest(size=_2G, memuse=3.6, dry_run=False)
3164 def test_huge_long_32b(self, size):
3165 data = 1 << (8 * size)
3166 try:
3167 for proto in protocols:
3168 if proto < 2:
3169 continue
3170 with self.subTest(proto=proto):
3171 with self.assertRaises((ValueError, OverflowError)):
3172 self.dumps(data, protocol=proto)
3173 finally:
3174 data = None
3175
3176 # Protocol 3 can serialize up to 4 GiB-1 as a bytes object
3177 # (older protocols don't have a dedicated opcode for bytes and are
3178 # too inefficient)
3179
3180 @bigmemtest(size=_2G, memuse=2.5, dry_run=False)
3181 def test_huge_bytes_32b(self, size):
3182 data = b"abcd" * (size // 4)
3183 try:
3184 for proto in protocols:
3185 if proto < 3:
3186 continue
3187 with self.subTest(proto=proto):
3188 try:
3189 pickled = self.dumps(data, protocol=proto)
3190 header = (pickle.BINBYTES +
3191 struct.pack("<I", len(data)))
3192 data_start = pickled.index(data)
3193 self.assertEqual(
3194 header,
3195 pickled[data_start-len(header):data_start])
3196 finally:
3197 pickled = None
3198 finally:
3199 data = None
3200
3201 @bigmemtest(size=_4G, memuse=2.5, dry_run=False)
3202 def test_huge_bytes_64b(self, size):
3203 data = b"acbd" * (size // 4)
3204 try:
3205 for proto in protocols:
3206 if proto < 3:
3207 continue
3208 with self.subTest(proto=proto):
3209 if proto == 3:
3210 # Protocol 3 does not support large bytes objects.
3211 # Verify that we do not crash when processing one.
3212 with self.assertRaises((ValueError, OverflowError)):
3213 self.dumps(data, protocol=proto)
3214 continue
3215 try:
3216 pickled = self.dumps(data, protocol=proto)
3217 header = (pickle.BINBYTES8 +
3218 struct.pack("<Q", len(data)))
3219 data_start = pickled.index(data)
3220 self.assertEqual(
3221 header,
3222 pickled[data_start-len(header):data_start])
3223 finally:
3224 pickled = None
3225 finally:
3226 data = None
3227
3228 # All protocols use 1-byte per printable ASCII character; we add another
3229 # byte because the encoded form has to be copied into the internal buffer.
3230
3231 @bigmemtest(size=_2G, memuse=8, dry_run=False)
3232 def test_huge_str_32b(self, size):
3233 data = "abcd" * (size // 4)
3234 try:
3235 for proto in protocols:
3236 if proto == 0:
3237 continue
3238 with self.subTest(proto=proto):
3239 try:
3240 pickled = self.dumps(data, protocol=proto)
3241 header = (pickle.BINUNICODE +
3242 struct.pack("<I", len(data)))
3243 data_start = pickled.index(b'abcd')
3244 self.assertEqual(
3245 header,
3246 pickled[data_start-len(header):data_start])
3247 self.assertEqual((pickled.rindex(b"abcd") + len(b"abcd") -
3248 pickled.index(b"abcd")), len(data))
3249 finally:
3250 pickled = None
3251 finally:
3252 data = None
3253
3254 # BINUNICODE (protocols 1, 2 and 3) cannot carry more than 2**32 - 1 bytes
3255 # of utf-8 encoded unicode. BINUNICODE8 (protocol 4) supports these huge
3256 # unicode strings however.
3257
3258 @bigmemtest(size=_4G, memuse=8, dry_run=False)
3259 def test_huge_str_64b(self, size):
3260 data = "abcd" * (size // 4)
3261 try:
3262 for proto in protocols:
3263 if proto == 0:
3264 continue
3265 with self.subTest(proto=proto):
3266 if proto < 4:
3267 with self.assertRaises((ValueError, OverflowError)):
3268 self.dumps(data, protocol=proto)
3269 continue
3270 try:
3271 pickled = self.dumps(data, protocol=proto)
3272 header = (pickle.BINUNICODE8 +
3273 struct.pack("<Q", len(data)))
3274 data_start = pickled.index(b'abcd')
3275 self.assertEqual(
3276 header,
3277 pickled[data_start-len(header):data_start])
3278 self.assertEqual((pickled.rindex(b"abcd") + len(b"abcd") -
3279 pickled.index(b"abcd")), len(data))
3280 finally:
3281 pickled = None
3282 finally:
3283 data = None
3284
3285
3286 # Test classes for reduce_ex
3287
3288 class REX_one(object):
3289 """No __reduce_ex__ here, but inheriting it from object"""
3290 _reduce_called = 0
3291 def __reduce__(self):
3292 self._reduce_called = 1
3293 return REX_one, ()
3294
3295 class REX_two(object):
3296 """No __reduce__ here, but inheriting it from object"""
3297 _proto = None
3298 def __reduce_ex__(self, proto):
3299 self._proto = proto
3300 return REX_two, ()
3301
3302 class REX_three(object):
3303 _proto = None
3304 def __reduce_ex__(self, proto):
3305 self._proto = proto
3306 return REX_two, ()
3307 def __reduce__(self):
3308 raise TestFailed("This __reduce__ shouldn't be called")
3309
3310 class REX_four(object):
3311 """Calling base class method should succeed"""
3312 _proto = None
3313 def __reduce_ex__(self, proto):
3314 self._proto = proto
3315 return object.__reduce_ex__(self, proto)
3316
3317 class REX_five(object):
3318 """This one used to fail with infinite recursion"""
3319 _reduce_called = 0
3320 def __reduce__(self):
3321 self._reduce_called = 1
3322 return object.__reduce__(self)
3323
3324 class REX_six(object):
3325 """This class is used to check the 4th argument (list iterator) of
3326 the reduce protocol.
3327 """
3328 def __init__(self, items=None):
3329 self.items = items if items is not None else []
3330 def __eq__(self, other):
3331 return type(self) is type(other) and self.items == other.items
3332 def append(self, item):
3333 self.items.append(item)
3334 def __reduce__(self):
3335 return type(self), (), None, iter(self.items), None
3336
3337 class REX_seven(object):
3338 """This class is used to check the 5th argument (dict iterator) of
3339 the reduce protocol.
3340 """
3341 def __init__(self, table=None):
3342 self.table = table if table is not None else {}
3343 def __eq__(self, other):
3344 return type(self) is type(other) and self.table == other.table
3345 def __setitem__(self, key, value):
3346 self.table[key] = value
3347 def __reduce__(self):
3348 return type(self), (), None, None, iter(self.table.items())
3349
3350 class REX_state(object):
3351 """This class is used to check the 3th argument (state) of
3352 the reduce protocol.
3353 """
3354 def __init__(self, state=None):
3355 self.state = state
3356 def __eq__(self, other):
3357 return type(self) is type(other) and self.state == other.state
3358 def __setstate__(self, state):
3359 self.state = state
3360 def __reduce__(self):
3361 return type(self), (), self.state
3362
3363
3364 # Test classes for newobj
3365
3366 class MyInt(int):
3367 sample = 1
3368
3369 class MyFloat(float):
3370 sample = 1.0
3371
3372 class MyComplex(complex):
3373 sample = 1.0 + 0.0j
3374
3375 class MyStr(str):
3376 sample = "hello"
3377
3378 class MyUnicode(str):
3379 sample = "hello \u1234"
3380
3381 class MyTuple(tuple):
3382 sample = (1, 2, 3)
3383
3384 class MyList(list):
3385 sample = [1, 2, 3]
3386
3387 class MyDict(dict):
3388 sample = {"a": 1, "b": 2}
3389
3390 class MySet(set):
3391 sample = {"a", "b"}
3392
3393 class MyFrozenSet(frozenset):
3394 sample = frozenset({"a", "b"})
3395
3396 myclasses = [MyInt, MyFloat,
3397 MyComplex,
3398 MyStr, MyUnicode,
3399 MyTuple, MyList, MyDict, MySet, MyFrozenSet]
3400
3401 class MyIntWithNew(int):
3402 def __new__(cls, value):
3403 raise AssertionError
3404
3405 class MyIntWithNew2(MyIntWithNew):
3406 __new__ = int.__new__
3407
3408
3409 class SlotList(MyList):
3410 __slots__ = ["foo"]
3411
3412 class SimpleNewObj(int):
3413 def __init__(self, *args, **kwargs):
3414 # raise an error, to make sure this isn't called
3415 raise TypeError("SimpleNewObj.__init__() didn't expect to get called")
3416 def __eq__(self, other):
3417 return int(self) == int(other) and self.__dict__ == other.__dict__
3418
3419 class ComplexNewObj(SimpleNewObj):
3420 def __getnewargs__(self):
3421 return ('%X' % self, 16)
3422
3423 class ComplexNewObjEx(SimpleNewObj):
3424 def __getnewargs_ex__(self):
3425 return ('%X' % self,), {'base': 16}
3426
3427 class BadGetattr:
3428 def __getattr__(self, key):
3429 self.foo
3430
3431
3432 class AbstractPickleModuleTests:
3433
3434 def test_dump_closed_file(self):
3435 f = open(TESTFN, "wb")
3436 try:
3437 f.close()
3438 self.assertRaises(ValueError, self.dump, 123, f)
3439 finally:
3440 os_helper.unlink(TESTFN)
3441
3442 def test_load_closed_file(self):
3443 f = open(TESTFN, "wb")
3444 try:
3445 f.close()
3446 self.assertRaises(ValueError, self.dump, 123, f)
3447 finally:
3448 os_helper.unlink(TESTFN)
3449
3450 def test_load_from_and_dump_to_file(self):
3451 stream = io.BytesIO()
3452 data = [123, {}, 124]
3453 self.dump(data, stream)
3454 stream.seek(0)
3455 unpickled = self.load(stream)
3456 self.assertEqual(unpickled, data)
3457
3458 def test_highest_protocol(self):
3459 # Of course this needs to be changed when HIGHEST_PROTOCOL changes.
3460 self.assertEqual(pickle.HIGHEST_PROTOCOL, 5)
3461
3462 def test_callapi(self):
3463 f = io.BytesIO()
3464 # With and without keyword arguments
3465 self.dump(123, f, -1)
3466 self.dump(123, file=f, protocol=-1)
3467 self.dumps(123, -1)
3468 self.dumps(123, protocol=-1)
3469 self.Pickler(f, -1)
3470 self.Pickler(f, protocol=-1)
3471
3472 def test_dump_text_file(self):
3473 f = open(TESTFN, "w")
3474 try:
3475 for proto in protocols:
3476 self.assertRaises(TypeError, self.dump, 123, f, proto)
3477 finally:
3478 f.close()
3479 os_helper.unlink(TESTFN)
3480
3481 def test_incomplete_input(self):
3482 s = io.BytesIO(b"X''.")
3483 self.assertRaises((EOFError, struct.error, pickle.UnpicklingError), self.load, s)
3484
3485 def test_bad_init(self):
3486 # Test issue3664 (pickle can segfault from a badly initialized Pickler).
3487 # Override initialization without calling __init__() of the superclass.
3488 class BadPickler(self.Pickler):
3489 def __init__(self): pass
3490
3491 class BadUnpickler(self.Unpickler):
3492 def __init__(self): pass
3493
3494 self.assertRaises(pickle.PicklingError, BadPickler().dump, 0)
3495 self.assertRaises(pickle.UnpicklingError, BadUnpickler().load)
3496
3497 def test_unpickler_bad_file(self):
3498 # bpo-38384: Crash in _pickle if the read attribute raises an error.
3499 def raises_oserror(self, *args, **kwargs):
3500 raise OSError
3501 @property
3502 def bad_property(self):
3503 1/0
3504
3505 # File without read and readline
3506 class F:
3507 pass
3508 self.assertRaises((AttributeError, TypeError), self.Unpickler, F())
3509
3510 # File without read
3511 class F:
3512 readline = raises_oserror
3513 self.assertRaises((AttributeError, TypeError), self.Unpickler, F())
3514
3515 # File without readline
3516 class F:
3517 read = raises_oserror
3518 self.assertRaises((AttributeError, TypeError), self.Unpickler, F())
3519
3520 # File with bad read
3521 class F:
3522 read = bad_property
3523 readline = raises_oserror
3524 self.assertRaises(ZeroDivisionError, self.Unpickler, F())
3525
3526 # File with bad readline
3527 class F:
3528 readline = bad_property
3529 read = raises_oserror
3530 self.assertRaises(ZeroDivisionError, self.Unpickler, F())
3531
3532 # File with bad readline, no read
3533 class F:
3534 readline = bad_property
3535 self.assertRaises(ZeroDivisionError, self.Unpickler, F())
3536
3537 # File with bad read, no readline
3538 class F:
3539 read = bad_property
3540 self.assertRaises((AttributeError, ZeroDivisionError), self.Unpickler, F())
3541
3542 # File with bad peek
3543 class F:
3544 peek = bad_property
3545 read = raises_oserror
3546 readline = raises_oserror
3547 try:
3548 self.Unpickler(F())
3549 except ZeroDivisionError:
3550 pass
3551
3552 # File with bad readinto
3553 class F:
3554 readinto = bad_property
3555 read = raises_oserror
3556 readline = raises_oserror
3557 try:
3558 self.Unpickler(F())
3559 except ZeroDivisionError:
3560 pass
3561
3562 def test_pickler_bad_file(self):
3563 # File without write
3564 class F:
3565 pass
3566 self.assertRaises(TypeError, self.Pickler, F())
3567
3568 # File with bad write
3569 class F:
3570 @property
3571 def write(self):
3572 1/0
3573 self.assertRaises(ZeroDivisionError, self.Pickler, F())
3574
3575 def check_dumps_loads_oob_buffers(self, dumps, loads):
3576 # No need to do the full gamut of tests here, just enough to
3577 # check that dumps() and loads() redirect their arguments
3578 # to the underlying Pickler and Unpickler, respectively.
3579 obj = ZeroCopyBytes(b"foo")
3580
3581 for proto in range(0, 5):
3582 # Need protocol >= 5 for buffer_callback
3583 with self.assertRaises(ValueError):
3584 dumps(obj, protocol=proto,
3585 buffer_callback=[].append)
3586 for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
3587 buffers = []
3588 buffer_callback = buffers.append
3589 data = dumps(obj, protocol=proto,
3590 buffer_callback=buffer_callback)
3591 self.assertNotIn(b"foo", data)
3592 self.assertEqual(bytes(buffers[0]), b"foo")
3593 # Need buffers argument to unpickle properly
3594 with self.assertRaises(pickle.UnpicklingError):
3595 loads(data)
3596 new = loads(data, buffers=buffers)
3597 self.assertIs(new, obj)
3598
3599 def test_dumps_loads_oob_buffers(self):
3600 # Test out-of-band buffers (PEP 574) with top-level dumps() and loads()
3601 self.check_dumps_loads_oob_buffers(self.dumps, self.loads)
3602
3603 def test_dump_load_oob_buffers(self):
3604 # Test out-of-band buffers (PEP 574) with top-level dump() and load()
3605 def dumps(obj, **kwargs):
3606 f = io.BytesIO()
3607 self.dump(obj, f, **kwargs)
3608 return f.getvalue()
3609
3610 def loads(data, **kwargs):
3611 f = io.BytesIO(data)
3612 return self.load(f, **kwargs)
3613
3614 self.check_dumps_loads_oob_buffers(dumps, loads)
3615
3616
3617 class AbstractPersistentPicklerTests:
3618
3619 # This class defines persistent_id() and persistent_load()
3620 # functions that should be used by the pickler. All even integers
3621 # are pickled using persistent ids.
3622
3623 def persistent_id(self, object):
3624 if isinstance(object, int) and object % 2 == 0:
3625 self.id_count += 1
3626 return str(object)
3627 elif object == "test_false_value":
3628 self.false_count += 1
3629 return ""
3630 else:
3631 return None
3632
3633 def persistent_load(self, oid):
3634 if not oid:
3635 self.load_false_count += 1
3636 return "test_false_value"
3637 else:
3638 self.load_count += 1
3639 object = int(oid)
3640 assert object % 2 == 0
3641 return object
3642
3643 def test_persistence(self):
3644 L = list(range(10)) + ["test_false_value"]
3645 for proto in protocols:
3646 self.id_count = 0
3647 self.false_count = 0
3648 self.load_false_count = 0
3649 self.load_count = 0
3650 self.assertEqual(self.loads(self.dumps(L, proto)), L)
3651 self.assertEqual(self.id_count, 5)
3652 self.assertEqual(self.false_count, 1)
3653 self.assertEqual(self.load_count, 5)
3654 self.assertEqual(self.load_false_count, 1)
3655
3656
3657 class AbstractIdentityPersistentPicklerTests:
3658
3659 def persistent_id(self, obj):
3660 return obj
3661
3662 def persistent_load(self, pid):
3663 return pid
3664
3665 def _check_return_correct_type(self, obj, proto):
3666 unpickled = self.loads(self.dumps(obj, proto))
3667 self.assertIsInstance(unpickled, type(obj))
3668 self.assertEqual(unpickled, obj)
3669
3670 def test_return_correct_type(self):
3671 for proto in protocols:
3672 # Protocol 0 supports only ASCII strings.
3673 if proto == 0:
3674 self._check_return_correct_type("abc", 0)
3675 else:
3676 for obj in [b"abc\n", "abc\n", -1, -1.1 * 0.1, str]:
3677 self._check_return_correct_type(obj, proto)
3678
3679 def test_protocol0_is_ascii_only(self):
3680 non_ascii_str = "\N{EMPTY SET}"
3681 self.assertRaises(pickle.PicklingError, self.dumps, non_ascii_str, 0)
3682 pickled = pickle.PERSID + non_ascii_str.encode('utf-8') + b'\n.'
3683 self.assertRaises(pickle.UnpicklingError, self.loads, pickled)
3684
3685
3686 class AbstractPicklerUnpicklerObjectTests:
3687
3688 pickler_class = None
3689 unpickler_class = None
3690
3691 def setUp(self):
3692 assert self.pickler_class
3693 assert self.unpickler_class
3694
3695 def test_clear_pickler_memo(self):
3696 # To test whether clear_memo() has any effect, we pickle an object,
3697 # then pickle it again without clearing the memo; the two serialized
3698 # forms should be different. If we clear_memo() and then pickle the
3699 # object again, the third serialized form should be identical to the
3700 # first one we obtained.
3701 data = ["abcdefg", "abcdefg", 44]
3702 for proto in protocols:
3703 f = io.BytesIO()
3704 pickler = self.pickler_class(f, proto)
3705
3706 pickler.dump(data)
3707 first_pickled = f.getvalue()
3708
3709 # Reset BytesIO object.
3710 f.seek(0)
3711 f.truncate()
3712
3713 pickler.dump(data)
3714 second_pickled = f.getvalue()
3715
3716 # Reset the Pickler and BytesIO objects.
3717 pickler.clear_memo()
3718 f.seek(0)
3719 f.truncate()
3720
3721 pickler.dump(data)
3722 third_pickled = f.getvalue()
3723
3724 self.assertNotEqual(first_pickled, second_pickled)
3725 self.assertEqual(first_pickled, third_pickled)
3726
3727 def test_priming_pickler_memo(self):
3728 # Verify that we can set the Pickler's memo attribute.
3729 data = ["abcdefg", "abcdefg", 44]
3730 f = io.BytesIO()
3731 pickler = self.pickler_class(f)
3732
3733 pickler.dump(data)
3734 first_pickled = f.getvalue()
3735
3736 f = io.BytesIO()
3737 primed = self.pickler_class(f)
3738 primed.memo = pickler.memo
3739
3740 primed.dump(data)
3741 primed_pickled = f.getvalue()
3742
3743 self.assertNotEqual(first_pickled, primed_pickled)
3744
3745 def test_priming_unpickler_memo(self):
3746 # Verify that we can set the Unpickler's memo attribute.
3747 data = ["abcdefg", "abcdefg", 44]
3748 f = io.BytesIO()
3749 pickler = self.pickler_class(f)
3750
3751 pickler.dump(data)
3752 first_pickled = f.getvalue()
3753
3754 f = io.BytesIO()
3755 primed = self.pickler_class(f)
3756 primed.memo = pickler.memo
3757
3758 primed.dump(data)
3759 primed_pickled = f.getvalue()
3760
3761 unpickler = self.unpickler_class(io.BytesIO(first_pickled))
3762 unpickled_data1 = unpickler.load()
3763
3764 self.assertEqual(unpickled_data1, data)
3765
3766 primed = self.unpickler_class(io.BytesIO(primed_pickled))
3767 primed.memo = unpickler.memo
3768 unpickled_data2 = primed.load()
3769
3770 primed.memo.clear()
3771
3772 self.assertEqual(unpickled_data2, data)
3773 self.assertTrue(unpickled_data2 is unpickled_data1)
3774
3775 def test_reusing_unpickler_objects(self):
3776 data1 = ["abcdefg", "abcdefg", 44]
3777 f = io.BytesIO()
3778 pickler = self.pickler_class(f)
3779 pickler.dump(data1)
3780 pickled1 = f.getvalue()
3781
3782 data2 = ["abcdefg", 44, 44]
3783 f = io.BytesIO()
3784 pickler = self.pickler_class(f)
3785 pickler.dump(data2)
3786 pickled2 = f.getvalue()
3787
3788 f = io.BytesIO()
3789 f.write(pickled1)
3790 f.seek(0)
3791 unpickler = self.unpickler_class(f)
3792 self.assertEqual(unpickler.load(), data1)
3793
3794 f.seek(0)
3795 f.truncate()
3796 f.write(pickled2)
3797 f.seek(0)
3798 self.assertEqual(unpickler.load(), data2)
3799
3800 def _check_multiple_unpicklings(self, ioclass, *, seekable=True):
3801 for proto in protocols:
3802 with self.subTest(proto=proto):
3803 data1 = [(x, str(x)) for x in range(2000)] + [b"abcde", len]
3804 f = ioclass()
3805 pickler = self.pickler_class(f, protocol=proto)
3806 pickler.dump(data1)
3807 pickled = f.getvalue()
3808
3809 N = 5
3810 f = ioclass(pickled * N)
3811 unpickler = self.unpickler_class(f)
3812 for i in range(N):
3813 if seekable:
3814 pos = f.tell()
3815 self.assertEqual(unpickler.load(), data1)
3816 if seekable:
3817 self.assertEqual(f.tell(), pos + len(pickled))
3818 self.assertRaises(EOFError, unpickler.load)
3819
3820 def test_multiple_unpicklings_seekable(self):
3821 self._check_multiple_unpicklings(io.BytesIO)
3822
3823 def test_multiple_unpicklings_unseekable(self):
3824 self._check_multiple_unpicklings(UnseekableIO, seekable=False)
3825
3826 def test_multiple_unpicklings_minimal(self):
3827 # File-like object that doesn't support peek() and readinto()
3828 # (bpo-39681)
3829 self._check_multiple_unpicklings(MinimalIO, seekable=False)
3830
3831 def test_unpickling_buffering_readline(self):
3832 # Issue #12687: the unpickler's buffering logic could fail with
3833 # text mode opcodes.
3834 data = list(range(10))
3835 for proto in protocols:
3836 for buf_size in range(1, 11):
3837 f = io.BufferedRandom(io.BytesIO(), buffer_size=buf_size)
3838 pickler = self.pickler_class(f, protocol=proto)
3839 pickler.dump(data)
3840 f.seek(0)
3841 unpickler = self.unpickler_class(f)
3842 self.assertEqual(unpickler.load(), data)
3843
3844
3845 # Tests for dispatch_table attribute
3846
3847 REDUCE_A = 'reduce_A'
3848
3849 class AAA(object):
3850 def __reduce__(self):
3851 return str, (REDUCE_A,)
3852
3853 class BBB(object):
3854 def __init__(self):
3855 # Add an instance attribute to enable state-saving routines at pickling
3856 # time.
3857 self.a = "some attribute"
3858
3859 def __setstate__(self, state):
3860 self.a = "BBB.__setstate__"
3861
3862
3863 def setstate_bbb(obj, state):
3864 """Custom state setter for BBB objects
3865
3866 Such callable may be created by other persons than the ones who created the
3867 BBB class. If passed as the state_setter item of a custom reducer, this
3868 allows for custom state setting behavior of BBB objects. One can think of
3869 it as the analogous of list_setitems or dict_setitems but for foreign
3870 classes/functions.
3871 """
3872 obj.a = "custom state_setter"
3873
3874
3875
3876 class AbstractCustomPicklerClass:
3877 """Pickler implementing a reducing hook using reducer_override."""
3878 def reducer_override(self, obj):
3879 obj_name = getattr(obj, "__name__", None)
3880
3881 if obj_name == 'f':
3882 # asking the pickler to save f as 5
3883 return int, (5, )
3884
3885 if obj_name == 'MyClass':
3886 return str, ('some str',)
3887
3888 elif obj_name == 'g':
3889 # in this case, the callback returns an invalid result (not a 2-5
3890 # tuple or a string), the pickler should raise a proper error.
3891 return False
3892
3893 elif obj_name == 'h':
3894 # Simulate a case when the reducer fails. The error should
3895 # be propagated to the original ``dump`` call.
3896 raise ValueError('The reducer just failed')
3897
3898 return NotImplemented
3899
3900 class AbstractHookTests:
3901 def test_pickler_hook(self):
3902 # test the ability of a custom, user-defined CPickler subclass to
3903 # override the default reducing routines of any type using the method
3904 # reducer_override
3905
3906 def f():
3907 pass
3908
3909 def g():
3910 pass
3911
3912 def h():
3913 pass
3914
3915 class MyClass:
3916 pass
3917
3918 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
3919 with self.subTest(proto=proto):
3920 bio = io.BytesIO()
3921 p = self.pickler_class(bio, proto)
3922
3923 p.dump([f, MyClass, math.log])
3924 new_f, some_str, math_log = pickle.loads(bio.getvalue())
3925
3926 self.assertEqual(new_f, 5)
3927 self.assertEqual(some_str, 'some str')
3928 # math.log does not have its usual reducer overridden, so the
3929 # custom reduction callback should silently direct the pickler
3930 # to the default pickling by attribute, by returning
3931 # NotImplemented
3932 self.assertIs(math_log, math.log)
3933
3934 with self.assertRaises(pickle.PicklingError):
3935 p.dump(g)
3936
3937 with self.assertRaisesRegex(
3938 ValueError, 'The reducer just failed'):
3939 p.dump(h)
3940
3941 @support.cpython_only
3942 def test_reducer_override_no_reference_cycle(self):
3943 # bpo-39492: reducer_override used to induce a spurious reference cycle
3944 # inside the Pickler object, that could prevent all serialized objects
3945 # from being garbage-collected without explicitly invoking gc.collect.
3946
3947 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
3948 with self.subTest(proto=proto):
3949 def f():
3950 pass
3951
3952 wr = weakref.ref(f)
3953
3954 bio = io.BytesIO()
3955 p = self.pickler_class(bio, proto)
3956 p.dump(f)
3957 new_f = pickle.loads(bio.getvalue())
3958 assert new_f == 5
3959
3960 del p
3961 del f
3962
3963 self.assertIsNone(wr())
3964
3965
3966 class AbstractDispatchTableTests:
3967
3968 def test_default_dispatch_table(self):
3969 # No dispatch_table attribute by default
3970 f = io.BytesIO()
3971 p = self.pickler_class(f, 0)
3972 with self.assertRaises(AttributeError):
3973 p.dispatch_table
3974 self.assertFalse(hasattr(p, 'dispatch_table'))
3975
3976 def test_class_dispatch_table(self):
3977 # A dispatch_table attribute can be specified class-wide
3978 dt = self.get_dispatch_table()
3979
3980 class MyPickler(self.pickler_class):
3981 dispatch_table = dt
3982
3983 def dumps(obj, protocol=None):
3984 f = io.BytesIO()
3985 p = MyPickler(f, protocol)
3986 self.assertEqual(p.dispatch_table, dt)
3987 p.dump(obj)
3988 return f.getvalue()
3989
3990 self._test_dispatch_table(dumps, dt)
3991
3992 def test_instance_dispatch_table(self):
3993 # A dispatch_table attribute can also be specified instance-wide
3994 dt = self.get_dispatch_table()
3995
3996 def dumps(obj, protocol=None):
3997 f = io.BytesIO()
3998 p = self.pickler_class(f, protocol)
3999 p.dispatch_table = dt
4000 self.assertEqual(p.dispatch_table, dt)
4001 p.dump(obj)
4002 return f.getvalue()
4003
4004 self._test_dispatch_table(dumps, dt)
4005
4006 def _test_dispatch_table(self, dumps, dispatch_table):
4007 def custom_load_dump(obj):
4008 return pickle.loads(dumps(obj, 4))
4009
4010 def default_load_dump(obj):
4011 return pickle.loads(pickle.dumps(obj, 4))
4012
4013 # pickling complex numbers using protocol 0 relies on copyreg
4014 # so check pickling a complex number still works
4015 z = 1 + 2j
4016 self.assertEqual(custom_load_dump(z), z)
4017 self.assertEqual(default_load_dump(z), z)
4018
4019 # modify pickling of complex
4020 REDUCE_1 = 'reduce_1'
4021 def reduce_1(obj):
4022 return str, (REDUCE_1,)
4023 dispatch_table[complex] = reduce_1
4024 self.assertEqual(custom_load_dump(z), REDUCE_1)
4025 self.assertEqual(default_load_dump(z), z)
4026
4027 # check picklability of AAA and BBB
4028 a = AAA()
4029 b = BBB()
4030 self.assertEqual(custom_load_dump(a), REDUCE_A)
4031 self.assertIsInstance(custom_load_dump(b), BBB)
4032 self.assertEqual(default_load_dump(a), REDUCE_A)
4033 self.assertIsInstance(default_load_dump(b), BBB)
4034
4035 # modify pickling of BBB
4036 dispatch_table[BBB] = reduce_1
4037 self.assertEqual(custom_load_dump(a), REDUCE_A)
4038 self.assertEqual(custom_load_dump(b), REDUCE_1)
4039 self.assertEqual(default_load_dump(a), REDUCE_A)
4040 self.assertIsInstance(default_load_dump(b), BBB)
4041
4042 # revert pickling of BBB and modify pickling of AAA
4043 REDUCE_2 = 'reduce_2'
4044 def reduce_2(obj):
4045 return str, (REDUCE_2,)
4046 dispatch_table[AAA] = reduce_2
4047 del dispatch_table[BBB]
4048 self.assertEqual(custom_load_dump(a), REDUCE_2)
4049 self.assertIsInstance(custom_load_dump(b), BBB)
4050 self.assertEqual(default_load_dump(a), REDUCE_A)
4051 self.assertIsInstance(default_load_dump(b), BBB)
4052
4053 # End-to-end testing of save_reduce with the state_setter keyword
4054 # argument. This is a dispatch_table test as the primary goal of
4055 # state_setter is to tweak objects reduction behavior.
4056 # In particular, state_setter is useful when the default __setstate__
4057 # behavior is not flexible enough.
4058
4059 # No custom reducer for b has been registered for now, so
4060 # BBB.__setstate__ should be used at unpickling time
4061 self.assertEqual(default_load_dump(b).a, "BBB.__setstate__")
4062
4063 def reduce_bbb(obj):
4064 return BBB, (), obj.__dict__, None, None, setstate_bbb
4065
4066 dispatch_table[BBB] = reduce_bbb
4067
4068 # The custom reducer reduce_bbb includes a state setter, that should
4069 # have priority over BBB.__setstate__
4070 self.assertEqual(custom_load_dump(b).a, "custom state_setter")
4071
4072
4073 if __name__ == "__main__":
4074 # Print some stuff that can be used to rewrite DATA{0,1,2}
4075 from pickletools import dis
4076 x = create_data()
4077 for i in range(pickle.HIGHEST_PROTOCOL+1):
4078 p = pickle.dumps(x, i)
4079 print("DATA{0} = (".format(i))
4080 for j in range(0, len(p), 20):
4081 b = bytes(p[j:j+20])
4082 print(" {0!r}".format(b))
4083 print(")")
4084 print()
4085 print("# Disassembly of DATA{0}".format(i))
4086 print("DATA{0}_DIS = \"\"\"\\".format(i))
4087 dis(p)
4088 print("\"\"\"")
4089 print()