Debian Codegraph @

Lib/test/pickletester.py

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