blob: fb0483016afc0c3e0fae7b6902b3d86439968589 [file] [log] [blame]
Collin Winter771d8342009-04-16 03:18:06 +00001import io
Jeremy Hylton66426532001-10-15 21:38:56 +00002import unittest
Tim Peters4190fb82003-02-02 16:09:05 +00003import pickle
Tim Peters31f119e2003-02-03 16:20:13 +00004import pickletools
Antoine Pitrou82be19f2011-08-29 23:09:33 +02005import sys
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00006import copyreg
Antoine Pitrou16c4ce12011-03-11 21:30:43 +01007import weakref
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00008from http.cookies import SimpleCookie
Tim Peters4190fb82003-02-02 16:09:05 +00009
Antoine Pitrou82be19f2011-08-29 23:09:33 +020010from test.support import (
Antoine Pitrouee763e22011-08-29 23:14:53 +020011 TestFailed, TESTFN, run_with_locale, no_tracing,
Antoine Pitrou94190bb2011-10-04 10:22:36 +020012 _2G, _4G, bigmemtest,
Antoine Pitrou82be19f2011-08-29 23:09:33 +020013 )
Tim Peterse089c682001-04-10 03:41:41 +000014
Guido van Rossum98297ee2007-11-06 21:34:58 +000015from pickle import bytes_types
16
Tim Petersee1a53c2003-02-02 02:57:53 +000017# Tests that try a number of pickle protocols should have a
18# for proto in protocols:
Tim Peters8587b3c2003-02-13 15:44:41 +000019# kind of outer loop.
Tim Peters8587b3c2003-02-13 15:44:41 +000020protocols = range(pickle.HIGHEST_PROTOCOL + 1)
Tim Petersee1a53c2003-02-02 02:57:53 +000021
Antoine Pitroub7591d42011-10-04 16:18:15 +020022ascii_char_size = 1
Antoine Pitrou82be19f2011-08-29 23:09:33 +020023
Tim Peters22e71712003-02-03 22:27:38 +000024
25# Return True if opcode code appears in the pickle, else False.
26def opcode_in_pickle(code, pickle):
27 for op, dummy, dummy in pickletools.genops(pickle):
Guido van Rossumcfe5f202007-05-08 21:26:54 +000028 if op.code == code.decode("latin-1"):
Tim Peters22e71712003-02-03 22:27:38 +000029 return True
30 return False
31
Tim Peters8d2613a2003-02-11 16:40:16 +000032# Return the number of times opcode code appears in pickle.
33def count_opcode(code, pickle):
34 n = 0
35 for op, dummy, dummy in pickletools.genops(pickle):
Guido van Rossumcfe5f202007-05-08 21:26:54 +000036 if op.code == code.decode("latin-1"):
Tim Peters8d2613a2003-02-11 16:40:16 +000037 n += 1
38 return n
39
Antoine Pitrou04248a82010-10-12 20:51:21 +000040
41class UnseekableIO(io.BytesIO):
42 def peek(self, *args):
43 raise NotImplementedError
44
45 def seekable(self):
46 return False
47
48 def seek(self, *args):
49 raise io.UnsupportedOperation
50
51 def tell(self):
52 raise io.UnsupportedOperation
53
54
Tim Peters3e667d52003-02-04 21:47:44 +000055# We can't very well test the extension registry without putting known stuff
56# in it, but we have to be careful to restore its original state. Code
57# should do this:
58#
59# e = ExtensionSaver(extension_code)
60# try:
61# fiddle w/ the extension registry's stuff for extension_code
62# finally:
63# e.restore()
64
65class ExtensionSaver:
66 # Remember current registration for code (if any), and remove it (if
67 # there is one).
68 def __init__(self, code):
69 self.code = code
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +000070 if code in copyreg._inverted_registry:
71 self.pair = copyreg._inverted_registry[code]
72 copyreg.remove_extension(self.pair[0], self.pair[1], code)
Tim Peters3e667d52003-02-04 21:47:44 +000073 else:
74 self.pair = None
75
76 # Restore previous registration for code.
77 def restore(self):
78 code = self.code
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +000079 curpair = copyreg._inverted_registry.get(code)
Tim Peters3e667d52003-02-04 21:47:44 +000080 if curpair is not None:
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +000081 copyreg.remove_extension(curpair[0], curpair[1], code)
Tim Peters3e667d52003-02-04 21:47:44 +000082 pair = self.pair
83 if pair is not None:
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +000084 copyreg.add_extension(pair[0], pair[1], code)
Tim Peters3e667d52003-02-04 21:47:44 +000085
Jeremy Hylton66426532001-10-15 21:38:56 +000086class C:
Guido van Rossum47b9ff62006-08-24 00:41:19 +000087 def __eq__(self, other):
88 return self.__dict__ == other.__dict__
Jeremy Hylton66426532001-10-15 21:38:56 +000089
Alexander Belopolskyd92f0402010-07-17 22:50:45 +000090class D(C):
91 def __init__(self, arg):
92 pass
93
94class E(C):
95 def __getinitargs__(self):
96 return ()
97
Jeremy Hylton66426532001-10-15 21:38:56 +000098import __main__
99__main__.C = C
100C.__module__ = "__main__"
Alexander Belopolskyd92f0402010-07-17 22:50:45 +0000101__main__.D = D
102D.__module__ = "__main__"
103__main__.E = E
104E.__module__ = "__main__"
Jeremy Hylton66426532001-10-15 21:38:56 +0000105
106class myint(int):
107 def __init__(self, x):
108 self.str = str(x)
109
110class initarg(C):
Guido van Rossum1444f672001-12-19 16:38:29 +0000111
Jeremy Hylton66426532001-10-15 21:38:56 +0000112 def __init__(self, a, b):
113 self.a = a
114 self.b = b
115
116 def __getinitargs__(self):
117 return self.a, self.b
118
Guido van Rossum04a86612001-12-19 16:58:54 +0000119class metaclass(type):
120 pass
121
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000122class use_metaclass(object, metaclass=metaclass):
123 pass
Guido van Rossum04a86612001-12-19 16:58:54 +0000124
Antoine Pitrouffd41d92011-10-04 09:23:04 +0200125class pickling_metaclass(type):
126 def __eq__(self, other):
127 return (type(self) == type(other) and
128 self.reduce_args == other.reduce_args)
129
130 def __reduce__(self):
131 return (create_dynamic_class, self.reduce_args)
132
133def create_dynamic_class(name, bases):
134 result = pickling_metaclass(name, bases, dict())
135 result.reduce_args = (name, bases)
136 return result
137
Tim Peters70b02d72003-02-02 17:26:40 +0000138# DATA0 .. DATA2 are the pickles we expect under the various protocols, for
139# the object returned by create_data().
Tim Petersee1a53c2003-02-02 02:57:53 +0000140
Guido van Rossum98297ee2007-11-06 21:34:58 +0000141DATA0 = (
Mark Dickinson8dd05142009-01-20 20:43:58 +0000142 b'(lp0\nL0L\naL1L\naF2.0\nac'
Georg Brandl1a3284e2007-12-02 09:40:06 +0000143 b'builtins\ncomplex\n'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000144 b'p1\n(F3.0\nF0.0\ntp2\nRp'
Mark Dickinson8dd05142009-01-20 20:43:58 +0000145 b'3\naL1L\naL-1L\naL255L\naL-'
146 b'255L\naL-256L\naL65535L\na'
147 b'L-65535L\naL-65536L\naL2'
148 b'147483647L\naL-2147483'
149 b'647L\naL-2147483648L\na('
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000150 b'Vabc\np4\ng4\nccopyreg'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000151 b'\n_reconstructor\np5\n('
Georg Brandl1a3284e2007-12-02 09:40:06 +0000152 b'c__main__\nC\np6\ncbu'
153 b'iltins\nobject\np7\nNt'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000154 b'p8\nRp9\n(dp10\nVfoo\np1'
Mark Dickinson8dd05142009-01-20 20:43:58 +0000155 b'1\nL1L\nsVbar\np12\nL2L\nsb'
156 b'g9\ntp13\nag13\naL5L\na.'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000157)
Tim Peterse9358162001-01-22 22:05:20 +0000158
Guido van Rossum98297ee2007-11-06 21:34:58 +0000159# Disassembly of DATA0
Tim Peters70b02d72003-02-02 17:26:40 +0000160DATA0_DIS = """\
161 0: ( MARK
162 1: l LIST (MARK at 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000163 2: p PUT 0
164 5: L LONG 0
Mark Dickinson8dd05142009-01-20 20:43:58 +0000165 9: a APPEND
166 10: L LONG 1
167 14: a APPEND
168 15: F FLOAT 2.0
169 20: a APPEND
170 21: c GLOBAL 'builtins complex'
171 39: p PUT 1
172 42: ( MARK
173 43: F FLOAT 3.0
174 48: F FLOAT 0.0
175 53: t TUPLE (MARK at 42)
176 54: p PUT 2
177 57: R REDUCE
178 58: p PUT 3
179 61: a APPEND
180 62: L LONG 1
181 66: a APPEND
182 67: L LONG -1
183 72: a APPEND
184 73: L LONG 255
185 79: a APPEND
186 80: L LONG -255
187 87: a APPEND
188 88: L LONG -256
189 95: a APPEND
190 96: L LONG 65535
191 104: a APPEND
192 105: L LONG -65535
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000193 114: a APPEND
Mark Dickinson8dd05142009-01-20 20:43:58 +0000194 115: L LONG -65536
195 124: a APPEND
196 125: L LONG 2147483647
197 138: a APPEND
198 139: L LONG -2147483647
199 153: a APPEND
200 154: L LONG -2147483648
201 168: a APPEND
202 169: ( MARK
203 170: V UNICODE 'abc'
204 175: p PUT 4
205 178: g GET 4
206 181: c GLOBAL 'copyreg _reconstructor'
207 205: p PUT 5
208 208: ( MARK
209 209: c GLOBAL '__main__ C'
210 221: p PUT 6
211 224: c GLOBAL 'builtins object'
212 241: p PUT 7
213 244: N NONE
214 245: t TUPLE (MARK at 208)
215 246: p PUT 8
216 249: R REDUCE
217 250: p PUT 9
218 253: ( MARK
219 254: d DICT (MARK at 253)
220 255: p PUT 10
221 259: V UNICODE 'foo'
222 264: p PUT 11
223 268: L LONG 1
224 272: s SETITEM
225 273: V UNICODE 'bar'
226 278: p PUT 12
227 282: L LONG 2
228 286: s SETITEM
229 287: b BUILD
230 288: g GET 9
231 291: t TUPLE (MARK at 169)
232 292: p PUT 13
233 296: a APPEND
234 297: g GET 13
235 301: a APPEND
236 302: L LONG 5
237 306: a APPEND
238 307: . STOP
Tim Peters70b02d72003-02-02 17:26:40 +0000239highest protocol among opcodes = 0
240"""
241
Guido van Rossum98297ee2007-11-06 21:34:58 +0000242DATA1 = (
Georg Brandl1a3284e2007-12-02 09:40:06 +0000243 b']q\x00(K\x00K\x01G@\x00\x00\x00\x00\x00\x00\x00c'
244 b'builtins\ncomplex\nq\x01'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000245 b'(G@\x08\x00\x00\x00\x00\x00\x00G\x00\x00\x00\x00\x00\x00\x00\x00t'
246 b'q\x02Rq\x03K\x01J\xff\xff\xff\xffK\xffJ\x01\xff\xff\xffJ'
247 b'\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff\xff'
248 b'\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00\x80(X\x03\x00\x00\x00ab'
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000249 b'cq\x04h\x04ccopyreg\n_reco'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000250 b'nstructor\nq\x05(c__main'
Georg Brandl1a3284e2007-12-02 09:40:06 +0000251 b'__\nC\nq\x06cbuiltins\n'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000252 b'object\nq\x07Ntq\x08Rq\t}q\n('
253 b'X\x03\x00\x00\x00fooq\x0bK\x01X\x03\x00\x00\x00bar'
254 b'q\x0cK\x02ubh\ttq\rh\rK\x05e.'
255)
Tim Peters70b02d72003-02-02 17:26:40 +0000256
Guido van Rossum98297ee2007-11-06 21:34:58 +0000257# Disassembly of DATA1
Tim Peters70b02d72003-02-02 17:26:40 +0000258DATA1_DIS = """\
259 0: ] EMPTY_LIST
Guido van Rossum98297ee2007-11-06 21:34:58 +0000260 1: q BINPUT 0
Tim Peters70b02d72003-02-02 17:26:40 +0000261 3: ( MARK
262 4: K BININT1 0
Guido van Rossum98297ee2007-11-06 21:34:58 +0000263 6: K BININT1 1
264 8: G BINFLOAT 2.0
Georg Brandl1a3284e2007-12-02 09:40:06 +0000265 17: c GLOBAL 'builtins complex'
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000266 35: q BINPUT 1
267 37: ( MARK
268 38: G BINFLOAT 3.0
269 47: G BINFLOAT 0.0
270 56: t TUPLE (MARK at 37)
271 57: q BINPUT 2
272 59: R REDUCE
273 60: q BINPUT 3
274 62: K BININT1 1
275 64: J BININT -1
276 69: K BININT1 255
277 71: J BININT -255
278 76: J BININT -256
279 81: M BININT2 65535
280 84: J BININT -65535
281 89: J BININT -65536
282 94: J BININT 2147483647
283 99: J BININT -2147483647
284 104: J BININT -2147483648
285 109: ( MARK
286 110: X BINUNICODE 'abc'
287 118: q BINPUT 4
288 120: h BINGET 4
289 122: c GLOBAL 'copyreg _reconstructor'
290 146: q BINPUT 5
291 148: ( MARK
292 149: c GLOBAL '__main__ C'
293 161: q BINPUT 6
294 163: c GLOBAL 'builtins object'
295 180: q BINPUT 7
296 182: N NONE
297 183: t TUPLE (MARK at 148)
298 184: q BINPUT 8
299 186: R REDUCE
300 187: q BINPUT 9
301 189: } EMPTY_DICT
302 190: q BINPUT 10
303 192: ( MARK
304 193: X BINUNICODE 'foo'
305 201: q BINPUT 11
306 203: K BININT1 1
307 205: X BINUNICODE 'bar'
308 213: q BINPUT 12
309 215: K BININT1 2
310 217: u SETITEMS (MARK at 192)
311 218: b BUILD
312 219: h BINGET 9
313 221: t TUPLE (MARK at 109)
314 222: q BINPUT 13
315 224: h BINGET 13
316 226: K BININT1 5
317 228: e APPENDS (MARK at 3)
318 229: . STOP
Tim Peters70b02d72003-02-02 17:26:40 +0000319highest protocol among opcodes = 1
320"""
Tim Peterse0c446b2001-10-18 21:57:37 +0000321
Guido van Rossum98297ee2007-11-06 21:34:58 +0000322DATA2 = (
323 b'\x80\x02]q\x00(K\x00K\x01G@\x00\x00\x00\x00\x00\x00\x00c'
Georg Brandl1a3284e2007-12-02 09:40:06 +0000324 b'builtins\ncomplex\n'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000325 b'q\x01G@\x08\x00\x00\x00\x00\x00\x00G\x00\x00\x00\x00\x00\x00\x00\x00'
326 b'\x86q\x02Rq\x03K\x01J\xff\xff\xff\xffK\xffJ\x01\xff\xff\xff'
327 b'J\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff'
328 b'\xff\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00\x80(X\x03\x00\x00\x00a'
329 b'bcq\x04h\x04c__main__\nC\nq\x05'
330 b')\x81q\x06}q\x07(X\x03\x00\x00\x00fooq\x08K\x01'
331 b'X\x03\x00\x00\x00barq\tK\x02ubh\x06tq\nh'
332 b'\nK\x05e.'
333)
Tim Petersfc273752003-03-02 04:54:24 +0000334
Guido van Rossum98297ee2007-11-06 21:34:58 +0000335# Disassembly of DATA2
Tim Petersfc273752003-03-02 04:54:24 +0000336DATA2_DIS = """\
337 0: \x80 PROTO 2
338 2: ] EMPTY_LIST
Guido van Rossum98297ee2007-11-06 21:34:58 +0000339 3: q BINPUT 0
Tim Petersfc273752003-03-02 04:54:24 +0000340 5: ( MARK
341 6: K BININT1 0
Guido van Rossum98297ee2007-11-06 21:34:58 +0000342 8: K BININT1 1
343 10: G BINFLOAT 2.0
Georg Brandl1a3284e2007-12-02 09:40:06 +0000344 19: c GLOBAL 'builtins complex'
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000345 37: q BINPUT 1
346 39: G BINFLOAT 3.0
347 48: G BINFLOAT 0.0
348 57: \x86 TUPLE2
349 58: q BINPUT 2
350 60: R REDUCE
351 61: q BINPUT 3
352 63: K BININT1 1
353 65: J BININT -1
354 70: K BININT1 255
355 72: J BININT -255
356 77: J BININT -256
357 82: M BININT2 65535
358 85: J BININT -65535
359 90: J BININT -65536
360 95: J BININT 2147483647
361 100: J BININT -2147483647
362 105: J BININT -2147483648
363 110: ( MARK
364 111: X BINUNICODE 'abc'
365 119: q BINPUT 4
366 121: h BINGET 4
367 123: c GLOBAL '__main__ C'
368 135: q BINPUT 5
369 137: ) EMPTY_TUPLE
370 138: \x81 NEWOBJ
371 139: q BINPUT 6
372 141: } EMPTY_DICT
373 142: q BINPUT 7
374 144: ( MARK
375 145: X BINUNICODE 'foo'
376 153: q BINPUT 8
377 155: K BININT1 1
378 157: X BINUNICODE 'bar'
379 165: q BINPUT 9
380 167: K BININT1 2
381 169: u SETITEMS (MARK at 144)
382 170: b BUILD
383 171: h BINGET 6
384 173: t TUPLE (MARK at 110)
385 174: q BINPUT 10
386 176: h BINGET 10
387 178: K BININT1 5
388 180: e APPENDS (MARK at 5)
389 181: . STOP
Tim Petersfc273752003-03-02 04:54:24 +0000390highest protocol among opcodes = 2
391"""
392
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000393# set([1,2]) pickled from 2.x with protocol 2
394DATA3 = b'\x80\x02c__builtin__\nset\nq\x00]q\x01(K\x01K\x02e\x85q\x02Rq\x03.'
395
396# xrange(5) pickled from 2.x with protocol 2
397DATA4 = b'\x80\x02c__builtin__\nxrange\nq\x00K\x00K\x05K\x01\x87q\x01Rq\x02.'
398
399# a SimpleCookie() object pickled from 2.x with protocol 2
400DATA5 = (b'\x80\x02cCookie\nSimpleCookie\nq\x00)\x81q\x01U\x03key'
401 b'q\x02cCookie\nMorsel\nq\x03)\x81q\x04(U\x07commentq\x05U'
402 b'\x00q\x06U\x06domainq\x07h\x06U\x06secureq\x08h\x06U\x07'
403 b'expiresq\th\x06U\x07max-ageq\nh\x06U\x07versionq\x0bh\x06U'
404 b'\x04pathq\x0ch\x06U\x08httponlyq\rh\x06u}q\x0e(U\x0b'
405 b'coded_valueq\x0fU\x05valueq\x10h\x10h\x10h\x02h\x02ubs}q\x11b.')
406
407# set([3]) pickled from 2.x with protocol 2
408DATA6 = b'\x80\x02c__builtin__\nset\nq\x00]q\x01K\x03a\x85q\x02Rq\x03.'
409
410
Jeremy Hylton66426532001-10-15 21:38:56 +0000411def create_data():
Tim Peterse9358162001-01-22 22:05:20 +0000412 c = C()
413 c.foo = 1
414 c.bar = 2
Guido van Rossume2a383d2007-01-15 16:59:06 +0000415 x = [0, 1, 2.0, 3.0+0j]
Tim Peters461922a2001-04-09 20:07:05 +0000416 # Append some integer test cases at cPickle.c's internal size
417 # cutoffs.
418 uint1max = 0xff
419 uint2max = 0xffff
420 int4max = 0x7fffffff
421 x.extend([1, -1,
422 uint1max, -uint1max, -uint1max-1,
423 uint2max, -uint2max, -uint2max-1,
424 int4max, -int4max, -int4max-1])
Tim Peterse9358162001-01-22 22:05:20 +0000425 y = ('abc', 'abc', c, c)
426 x.append(y)
427 x.append(y)
428 x.append(5)
Jeremy Hylton66426532001-10-15 21:38:56 +0000429 return x
Tim Petersc58440f2001-04-09 17:16:31 +0000430
Jeremy Hylton66426532001-10-15 21:38:56 +0000431class AbstractPickleTests(unittest.TestCase):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000432 # Subclass must define self.dumps, self.loads.
Tim Petersc58440f2001-04-09 17:16:31 +0000433
Jeremy Hylton66426532001-10-15 21:38:56 +0000434 _testdata = create_data()
Tim Petersc58440f2001-04-09 17:16:31 +0000435
Jeremy Hylton66426532001-10-15 21:38:56 +0000436 def setUp(self):
Tim Peterse9358162001-01-22 22:05:20 +0000437 pass
Tim Petersc58440f2001-04-09 17:16:31 +0000438
Jeremy Hylton66426532001-10-15 21:38:56 +0000439 def test_misc(self):
440 # test various datatypes not tested by testdata
Tim Peters70b02d72003-02-02 17:26:40 +0000441 for proto in protocols:
442 x = myint(4)
443 s = self.dumps(x, proto)
444 y = self.loads(s)
445 self.assertEqual(x, y)
Tim Peterse9358162001-01-22 22:05:20 +0000446
Tim Peters70b02d72003-02-02 17:26:40 +0000447 x = (1, ())
448 s = self.dumps(x, proto)
449 y = self.loads(s)
450 self.assertEqual(x, y)
Tim Peterse9358162001-01-22 22:05:20 +0000451
Tim Peters70b02d72003-02-02 17:26:40 +0000452 x = initarg(1, x)
453 s = self.dumps(x, proto)
454 y = self.loads(s)
455 self.assertEqual(x, y)
Tim Peterse9358162001-01-22 22:05:20 +0000456
Jeremy Hylton66426532001-10-15 21:38:56 +0000457 # XXX test __reduce__ protocol?
458
Tim Peters70b02d72003-02-02 17:26:40 +0000459 def test_roundtrip_equality(self):
460 expected = self._testdata
461 for proto in protocols:
462 s = self.dumps(expected, proto)
463 got = self.loads(s)
464 self.assertEqual(expected, got)
Jeremy Hylton66426532001-10-15 21:38:56 +0000465
Guido van Rossum98297ee2007-11-06 21:34:58 +0000466 def test_load_from_data0(self):
467 self.assertEqual(self._testdata, self.loads(DATA0))
468
469 def test_load_from_data1(self):
470 self.assertEqual(self._testdata, self.loads(DATA1))
471
472 def test_load_from_data2(self):
473 self.assertEqual(self._testdata, self.loads(DATA2))
Jeremy Hylton66426532001-10-15 21:38:56 +0000474
Alexander Belopolskyd92f0402010-07-17 22:50:45 +0000475 def test_load_classic_instance(self):
476 # See issue5180. Test loading 2.x pickles that
477 # contain an instance of old style class.
478 for X, args in [(C, ()), (D, ('x',)), (E, ())]:
479 xname = X.__name__.encode('ascii')
480 # Protocol 0 (text mode pickle):
481 """
482 0: ( MARK
483 1: i INST '__main__ X' (MARK at 0)
484 15: p PUT 0
485 18: ( MARK
486 19: d DICT (MARK at 18)
487 20: p PUT 1
488 23: b BUILD
489 24: . STOP
490 """
491 pickle0 = (b"(i__main__\n"
492 b"X\n"
493 b"p0\n"
494 b"(dp1\nb.").replace(b'X', xname)
495 self.assertEqual(X(*args), self.loads(pickle0))
496
497 # Protocol 1 (binary mode pickle)
498 """
499 0: ( MARK
500 1: c GLOBAL '__main__ X'
501 15: q BINPUT 0
502 17: o OBJ (MARK at 0)
503 18: q BINPUT 1
504 20: } EMPTY_DICT
505 21: q BINPUT 2
506 23: b BUILD
507 24: . STOP
508 """
509 pickle1 = (b'(c__main__\n'
510 b'X\n'
511 b'q\x00oq\x01}q\x02b.').replace(b'X', xname)
512 self.assertEqual(X(*args), self.loads(pickle1))
513
514 # Protocol 2 (pickle2 = b'\x80\x02' + pickle1)
515 """
516 0: \x80 PROTO 2
517 2: ( MARK
518 3: c GLOBAL '__main__ X'
519 17: q BINPUT 0
520 19: o OBJ (MARK at 2)
521 20: q BINPUT 1
522 22: } EMPTY_DICT
523 23: q BINPUT 2
524 25: b BUILD
525 26: . STOP
526 """
527 pickle2 = (b'\x80\x02(c__main__\n'
528 b'X\n'
529 b'q\x00oq\x01}q\x02b.').replace(b'X', xname)
530 self.assertEqual(X(*args), self.loads(pickle2))
531
Tim Peters70b02d72003-02-02 17:26:40 +0000532 # There are gratuitous differences between pickles produced by
533 # pickle and cPickle, largely because cPickle starts PUT indices at
534 # 1 and pickle starts them at 0. See XXX comment in cPickle's put2() --
535 # there's a comment with an exclamation point there whose meaning
536 # is a mystery. cPickle also suppresses PUT for objects with a refcount
537 # of 1.
538 def dont_test_disassembly(self):
Guido van Rossum34d19282007-08-09 01:03:29 +0000539 from io import StringIO
Tim Peters70b02d72003-02-02 17:26:40 +0000540 from pickletools import dis
541
542 for proto, expected in (0, DATA0_DIS), (1, DATA1_DIS):
543 s = self.dumps(self._testdata, proto)
544 filelike = StringIO()
545 dis(s, out=filelike)
546 got = filelike.getvalue()
547 self.assertEqual(expected, got)
Jeremy Hylton66426532001-10-15 21:38:56 +0000548
549 def test_recursive_list(self):
550 l = []
551 l.append(l)
Tim Peters70b02d72003-02-02 17:26:40 +0000552 for proto in protocols:
553 s = self.dumps(l, proto)
554 x = self.loads(s)
Armin Rigo2b3eb402003-10-28 12:05:48 +0000555 self.assertEqual(len(x), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000556 self.assertTrue(x is x[0])
Jeremy Hylton66426532001-10-15 21:38:56 +0000557
Collin Winter8ca69de2009-05-26 16:53:41 +0000558 def test_recursive_tuple(self):
559 t = ([],)
560 t[0].append(t)
561 for proto in protocols:
562 s = self.dumps(t, proto)
563 x = self.loads(s)
564 self.assertEqual(len(x), 1)
565 self.assertEqual(len(x[0]), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000566 self.assertTrue(x is x[0][0])
Collin Winter8ca69de2009-05-26 16:53:41 +0000567
Jeremy Hylton66426532001-10-15 21:38:56 +0000568 def test_recursive_dict(self):
569 d = {}
570 d[1] = d
Tim Peters70b02d72003-02-02 17:26:40 +0000571 for proto in protocols:
572 s = self.dumps(d, proto)
573 x = self.loads(s)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000574 self.assertEqual(list(x.keys()), [1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000575 self.assertTrue(x[1] is x)
Jeremy Hylton66426532001-10-15 21:38:56 +0000576
577 def test_recursive_inst(self):
578 i = C()
579 i.attr = i
Tim Peters70b02d72003-02-02 17:26:40 +0000580 for proto in protocols:
581 s = self.dumps(i, 2)
582 x = self.loads(s)
Armin Rigo2b3eb402003-10-28 12:05:48 +0000583 self.assertEqual(dir(x), dir(i))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000584 self.assertTrue(x.attr is x)
Jeremy Hylton66426532001-10-15 21:38:56 +0000585
586 def test_recursive_multi(self):
587 l = []
588 d = {1:l}
589 i = C()
590 i.attr = d
591 l.append(i)
Tim Peters70b02d72003-02-02 17:26:40 +0000592 for proto in protocols:
593 s = self.dumps(l, proto)
594 x = self.loads(s)
Armin Rigo2b3eb402003-10-28 12:05:48 +0000595 self.assertEqual(len(x), 1)
596 self.assertEqual(dir(x[0]), dir(i))
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000597 self.assertEqual(list(x[0].attr.keys()), [1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000598 self.assertTrue(x[0].attr[1] is x)
Jeremy Hylton66426532001-10-15 21:38:56 +0000599
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000600 def test_get(self):
601 self.assertRaises(KeyError, self.loads, b'g0\np0')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000602 self.assertEqual(self.loads(b'((Kdtp0\nh\x00l.))'), [(100,), (100,)])
Jeremy Hylton66426532001-10-15 21:38:56 +0000603
604 def test_insecure_strings(self):
Guido van Rossum39478e82007-08-27 17:23:59 +0000605 # XXX Some of these tests are temporarily disabled
606 insecure = [b"abc", b"2 + 2", # not quoted
607 ## b"'abc' + 'def'", # not a single quoted string
608 b"'abc", # quote is not closed
609 b"'abc\"", # open quote and close quote don't match
610 b"'abc' ?", # junk after close quote
611 b"'\\'", # trailing backslash
Jeremy Hylton66426532001-10-15 21:38:56 +0000612 # some tests of the quoting rules
Guido van Rossum39478e82007-08-27 17:23:59 +0000613 ## b"'abc\"\''",
614 ## b"'\\\\a\'\'\'\\\'\\\\\''",
Jeremy Hylton66426532001-10-15 21:38:56 +0000615 ]
Guido van Rossum39478e82007-08-27 17:23:59 +0000616 for b in insecure:
617 buf = b"S" + b + b"\012p0\012."
Jeremy Hylton66426532001-10-15 21:38:56 +0000618 self.assertRaises(ValueError, self.loads, buf)
619
Walter Dörwald9b775532007-06-08 14:30:53 +0000620 def test_unicode(self):
Benjamin Petersond1486302008-12-27 16:58:50 +0000621 endcases = ['', '<\\u>', '<\\\u1234>', '<\n>',
Victor Stinner485fb562010-04-13 11:07:24 +0000622 '<\\>', '<\\\U00012345>',
623 # surrogates
624 '<\udc80>']
Walter Dörwald9b775532007-06-08 14:30:53 +0000625 for proto in protocols:
626 for u in endcases:
627 p = self.dumps(u, proto)
628 u2 = self.loads(p)
629 self.assertEqual(u2, u)
Tim Peterse089c682001-04-10 03:41:41 +0000630
Alexandre Vassalotti554d8782008-12-27 07:32:41 +0000631 def test_unicode_high_plane(self):
632 t = '\U00012345'
633 for proto in protocols:
634 p = self.dumps(t, proto)
635 t2 = self.loads(p)
636 self.assertEqual(t2, t)
637
Guido van Rossumf4169812008-03-17 22:56:06 +0000638 def test_bytes(self):
639 for proto in protocols:
Alexandre Vassalotti3bfc65a2011-12-13 13:08:09 -0500640 for s in b'', b'xyz', b'xyz'*100:
641 p = self.dumps(s)
642 self.assertEqual(self.loads(p), s)
643 for s in [bytes([i]) for i in range(256)]:
644 p = self.dumps(s)
645 self.assertEqual(self.loads(p), s)
646 for s in [bytes([i, i]) for i in range(256)]:
647 p = self.dumps(s)
648 self.assertEqual(self.loads(p), s)
Guido van Rossumf4169812008-03-17 22:56:06 +0000649
Jeremy Hylton66426532001-10-15 21:38:56 +0000650 def test_ints(self):
651 import sys
Tim Petersee1a53c2003-02-02 02:57:53 +0000652 for proto in protocols:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000653 n = sys.maxsize
Tim Petersee1a53c2003-02-02 02:57:53 +0000654 while n:
655 for expected in (-n, n):
656 s = self.dumps(expected, proto)
657 n2 = self.loads(s)
658 self.assertEqual(expected, n2)
659 n = n >> 1
Tim Peters19ef62d2001-08-28 22:21:18 +0000660
Jeremy Hylton66426532001-10-15 21:38:56 +0000661 def test_maxint64(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000662 maxint64 = (1 << 63) - 1
Guido van Rossum39478e82007-08-27 17:23:59 +0000663 data = b'I' + str(maxint64).encode("ascii") + b'\n.'
Jeremy Hylton66426532001-10-15 21:38:56 +0000664 got = self.loads(data)
665 self.assertEqual(got, maxint64)
666
667 # Try too with a bogus literal.
Guido van Rossum39478e82007-08-27 17:23:59 +0000668 data = b'I' + str(maxint64).encode("ascii") + b'JUNK\n.'
Jeremy Hylton66426532001-10-15 21:38:56 +0000669 self.assertRaises(ValueError, self.loads, data)
670
Tim Petersee1a53c2003-02-02 02:57:53 +0000671 def test_long(self):
672 for proto in protocols:
Tim Petersbf2674b2003-02-02 07:51:32 +0000673 # 256 bytes is where LONG4 begins.
Tim Petersee1a53c2003-02-02 02:57:53 +0000674 for nbits in 1, 8, 8*254, 8*255, 8*256, 8*257:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000675 nbase = 1 << nbits
Tim Petersee1a53c2003-02-02 02:57:53 +0000676 for npos in nbase-1, nbase, nbase+1:
677 for n in npos, -npos:
678 pickle = self.dumps(n, proto)
679 got = self.loads(pickle)
680 self.assertEqual(n, got)
681 # Try a monster. This is quadratic-time in protos 0 & 1, so don't
682 # bother with those.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000683 nbase = int("deadbeeffeedface", 16)
Tim Petersee1a53c2003-02-02 02:57:53 +0000684 nbase += nbase << 1000000
685 for n in nbase, -nbase:
Tim Petersee1a53c2003-02-02 02:57:53 +0000686 p = self.dumps(n, 2)
Tim Petersee1a53c2003-02-02 02:57:53 +0000687 got = self.loads(p)
Tim Petersee1a53c2003-02-02 02:57:53 +0000688 self.assertEqual(n, got)
689
Mark Dickinsoncddcf442009-01-24 21:46:33 +0000690 def test_float(self):
691 test_values = [0.0, 4.94e-324, 1e-310, 7e-308, 6.626e-34, 0.1, 0.5,
692 3.14, 263.44582062374053, 6.022e23, 1e30]
693 test_values = test_values + [-x for x in test_values]
694 for proto in protocols:
695 for value in test_values:
696 pickle = self.dumps(value, proto)
697 got = self.loads(pickle)
698 self.assertEqual(value, got)
699
Thomas Wouters477c8d52006-05-27 19:21:47 +0000700 @run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
701 def test_float_format(self):
Guido van Rossumf4169812008-03-17 22:56:06 +0000702 # make sure that floats are formatted locale independent with proto 0
703 self.assertEqual(self.dumps(1.2, 0)[0:3], b'F1.')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000704
Jeremy Hylton66426532001-10-15 21:38:56 +0000705 def test_reduce(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000706 pass
Jeremy Hylton66426532001-10-15 21:38:56 +0000707
708 def test_getinitargs(self):
709 pass
710
Antoine Pitrou79035bd2012-06-26 23:04:48 +0200711 def test_pop_empty_stack(self):
712 # Test issue7455
713 s = b'0'
714 self.assertRaises((pickle.UnpicklingError, IndexError), self.loads, s)
715
Guido van Rossum04a86612001-12-19 16:58:54 +0000716 def test_metaclass(self):
717 a = use_metaclass()
Tim Peters70b02d72003-02-02 17:26:40 +0000718 for proto in protocols:
719 s = self.dumps(a, proto)
720 b = self.loads(s)
721 self.assertEqual(a.__class__, b.__class__)
Guido van Rossum04a86612001-12-19 16:58:54 +0000722
Antoine Pitrouffd41d92011-10-04 09:23:04 +0200723 def test_dynamic_class(self):
724 a = create_dynamic_class("my_dynamic_class", (object,))
725 copyreg.pickle(pickling_metaclass, pickling_metaclass.__reduce__)
726 for proto in protocols:
727 s = self.dumps(a, proto)
728 b = self.loads(s)
729 self.assertEqual(a, b)
730
Michael W. Hudson7bb466a2002-03-05 13:27:58 +0000731 def test_structseq(self):
732 import time
Michael W. Hudson0e025302002-03-06 17:11:18 +0000733 import os
Tim Peters70b02d72003-02-02 17:26:40 +0000734
735 t = time.localtime()
736 for proto in protocols:
737 s = self.dumps(t, proto)
Michael W. Hudson0e025302002-03-06 17:11:18 +0000738 u = self.loads(s)
739 self.assertEqual(t, u)
Tim Peters70b02d72003-02-02 17:26:40 +0000740 if hasattr(os, "stat"):
741 t = os.stat(os.curdir)
742 s = self.dumps(t, proto)
743 u = self.loads(s)
744 self.assertEqual(t, u)
745 if hasattr(os, "statvfs"):
746 t = os.statvfs(os.curdir)
747 s = self.dumps(t, proto)
748 u = self.loads(s)
749 self.assertEqual(t, u)
Michael W. Hudson7bb466a2002-03-05 13:27:58 +0000750
Łukasz Langaf3078fb2012-03-12 19:46:12 +0100751 def test_ellipsis(self):
752 for proto in protocols:
753 s = self.dumps(..., proto)
754 u = self.loads(s)
755 self.assertEqual(..., u)
756
757 def test_notimplemented(self):
758 for proto in protocols:
759 s = self.dumps(NotImplemented, proto)
760 u = self.loads(s)
761 self.assertEqual(NotImplemented, u)
762
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000763 # Tests for protocol 2
764
Tim Peters4190fb82003-02-02 16:09:05 +0000765 def test_proto(self):
766 build_none = pickle.NONE + pickle.STOP
767 for proto in protocols:
768 expected = build_none
769 if proto >= 2:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000770 expected = pickle.PROTO + bytes([proto]) + expected
Tim Peters4190fb82003-02-02 16:09:05 +0000771 p = self.dumps(None, proto)
772 self.assertEqual(p, expected)
773
774 oob = protocols[-1] + 1 # a future protocol
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000775 badpickle = pickle.PROTO + bytes([oob]) + build_none
Tim Peters4190fb82003-02-02 16:09:05 +0000776 try:
777 self.loads(badpickle)
Guido van Rossumb940e112007-01-10 16:19:56 +0000778 except ValueError as detail:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000779 self.assertTrue(str(detail).startswith(
Tim Peters4190fb82003-02-02 16:09:05 +0000780 "unsupported pickle protocol"))
781 else:
782 self.fail("expected bad protocol number to raise ValueError")
783
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000784 def test_long1(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000785 x = 12345678910111213141516178920
Tim Peters61bf2572003-02-03 21:31:22 +0000786 for proto in protocols:
787 s = self.dumps(x, proto)
788 y = self.loads(s)
789 self.assertEqual(x, y)
Tim Peters22e71712003-02-03 22:27:38 +0000790 self.assertEqual(opcode_in_pickle(pickle.LONG1, s), proto >= 2)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000791
792 def test_long4(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000793 x = 12345678910111213141516178920 << (256*8)
Tim Peters61bf2572003-02-03 21:31:22 +0000794 for proto in protocols:
795 s = self.dumps(x, proto)
796 y = self.loads(s)
797 self.assertEqual(x, y)
Tim Peters22e71712003-02-03 22:27:38 +0000798 self.assertEqual(opcode_in_pickle(pickle.LONG4, s), proto >= 2)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000799
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000800 def test_short_tuples(self):
Tim Peters1d63c9f2003-02-02 20:29:39 +0000801 # Map (proto, len(tuple)) to expected opcode.
802 expected_opcode = {(0, 0): pickle.TUPLE,
803 (0, 1): pickle.TUPLE,
804 (0, 2): pickle.TUPLE,
805 (0, 3): pickle.TUPLE,
806 (0, 4): pickle.TUPLE,
807
808 (1, 0): pickle.EMPTY_TUPLE,
809 (1, 1): pickle.TUPLE,
810 (1, 2): pickle.TUPLE,
811 (1, 3): pickle.TUPLE,
812 (1, 4): pickle.TUPLE,
813
814 (2, 0): pickle.EMPTY_TUPLE,
815 (2, 1): pickle.TUPLE1,
816 (2, 2): pickle.TUPLE2,
817 (2, 3): pickle.TUPLE3,
818 (2, 4): pickle.TUPLE,
Guido van Rossumf4169812008-03-17 22:56:06 +0000819
820 (3, 0): pickle.EMPTY_TUPLE,
821 (3, 1): pickle.TUPLE1,
822 (3, 2): pickle.TUPLE2,
823 (3, 3): pickle.TUPLE3,
824 (3, 4): pickle.TUPLE,
Tim Peters1d63c9f2003-02-02 20:29:39 +0000825 }
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000826 a = ()
Guido van Rossum025bc2f2003-01-28 04:20:02 +0000827 b = (1,)
828 c = (1, 2)
829 d = (1, 2, 3)
830 e = (1, 2, 3, 4)
Tim Peters4190fb82003-02-02 16:09:05 +0000831 for proto in protocols:
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000832 for x in a, b, c, d, e:
833 s = self.dumps(x, proto)
834 y = self.loads(s)
835 self.assertEqual(x, y, (proto, x, s, y))
Tim Peters1d63c9f2003-02-02 20:29:39 +0000836 expected = expected_opcode[proto, len(x)]
Tim Peters22e71712003-02-03 22:27:38 +0000837 self.assertEqual(opcode_in_pickle(expected, s), True)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000838
Guido van Rossum7d97d312003-01-28 04:25:27 +0000839 def test_singletons(self):
Tim Peters61bf2572003-02-03 21:31:22 +0000840 # Map (proto, singleton) to expected opcode.
841 expected_opcode = {(0, None): pickle.NONE,
842 (1, None): pickle.NONE,
843 (2, None): pickle.NONE,
Guido van Rossumf4169812008-03-17 22:56:06 +0000844 (3, None): pickle.NONE,
Tim Peters61bf2572003-02-03 21:31:22 +0000845
846 (0, True): pickle.INT,
847 (1, True): pickle.INT,
848 (2, True): pickle.NEWTRUE,
Guido van Rossumf4169812008-03-17 22:56:06 +0000849 (3, True): pickle.NEWTRUE,
Tim Peters61bf2572003-02-03 21:31:22 +0000850
851 (0, False): pickle.INT,
852 (1, False): pickle.INT,
853 (2, False): pickle.NEWFALSE,
Guido van Rossumf4169812008-03-17 22:56:06 +0000854 (3, False): pickle.NEWFALSE,
Tim Peters61bf2572003-02-03 21:31:22 +0000855 }
Tim Peters4190fb82003-02-02 16:09:05 +0000856 for proto in protocols:
Guido van Rossum7d97d312003-01-28 04:25:27 +0000857 for x in None, False, True:
858 s = self.dumps(x, proto)
859 y = self.loads(s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000860 self.assertTrue(x is y, (proto, x, s, y))
Tim Peters61bf2572003-02-03 21:31:22 +0000861 expected = expected_opcode[proto, x]
Tim Peters22e71712003-02-03 22:27:38 +0000862 self.assertEqual(opcode_in_pickle(expected, s), True)
Tim Peters3c67d792003-02-02 17:59:11 +0000863
Guido van Rossum533dbcf2003-01-28 17:55:05 +0000864 def test_newobj_tuple(self):
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000865 x = MyTuple([1, 2, 3])
866 x.foo = 42
867 x.bar = "hello"
Tim Peters894453a2003-02-03 22:32:18 +0000868 for proto in protocols:
869 s = self.dumps(x, proto)
870 y = self.loads(s)
871 self.assertEqual(tuple(x), tuple(y))
872 self.assertEqual(x.__dict__, y.__dict__)
Guido van Rossum533dbcf2003-01-28 17:55:05 +0000873
874 def test_newobj_list(self):
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000875 x = MyList([1, 2, 3])
876 x.foo = 42
877 x.bar = "hello"
Tim Peters894453a2003-02-03 22:32:18 +0000878 for proto in protocols:
879 s = self.dumps(x, proto)
880 y = self.loads(s)
881 self.assertEqual(list(x), list(y))
882 self.assertEqual(x.__dict__, y.__dict__)
Guido van Rossum533dbcf2003-01-28 17:55:05 +0000883
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000884 def test_newobj_generic(self):
Tim Peters5013bd92003-02-03 22:28:41 +0000885 for proto in protocols:
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000886 for C in myclasses:
887 B = C.__base__
888 x = C(C.sample)
889 x.foo = 42
890 s = self.dumps(x, proto)
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000891 y = self.loads(s)
892 detail = (proto, C, B, x, y, type(y))
893 self.assertEqual(B(x), B(y), detail)
894 self.assertEqual(x.__dict__, y.__dict__, detail)
895
Antoine Pitrou16c4ce12011-03-11 21:30:43 +0100896 def test_newobj_proxies(self):
897 # NEWOBJ should use the __class__ rather than the raw type
898 classes = myclasses[:]
899 # Cannot create weakproxies to these classes
900 for c in (MyInt, MyTuple):
901 classes.remove(c)
902 for proto in protocols:
903 for C in classes:
904 B = C.__base__
905 x = C(C.sample)
906 x.foo = 42
907 p = weakref.proxy(x)
908 s = self.dumps(p, proto)
909 y = self.loads(s)
910 self.assertEqual(type(y), type(x)) # rather than type(p)
911 detail = (proto, C, B, x, y, type(y))
912 self.assertEqual(B(x), B(y), detail)
913 self.assertEqual(x.__dict__, y.__dict__, detail)
914
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000915 # Register a type with copyreg, with extension code extcode. Pickle
Tim Peters22e71712003-02-03 22:27:38 +0000916 # an object of that type. Check that the resulting pickle uses opcode
917 # (EXT[124]) under proto 2, and not in proto 1.
Tim Peters3e667d52003-02-04 21:47:44 +0000918
Tim Peters22e71712003-02-03 22:27:38 +0000919 def produce_global_ext(self, extcode, opcode):
Tim Peters3e667d52003-02-04 21:47:44 +0000920 e = ExtensionSaver(extcode)
Guido van Rossum0322d0f2003-01-29 06:12:46 +0000921 try:
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000922 copyreg.add_extension(__name__, "MyList", extcode)
Guido van Rossum0322d0f2003-01-29 06:12:46 +0000923 x = MyList([1, 2, 3])
924 x.foo = 42
925 x.bar = "hello"
926
Tim Peters22e71712003-02-03 22:27:38 +0000927 # Dump using protocol 1 for comparison.
Guido van Rossum0322d0f2003-01-29 06:12:46 +0000928 s1 = self.dumps(x, 1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000929 self.assertIn(__name__.encode("utf-8"), s1)
930 self.assertIn(b"MyList", s1)
Tim Peters3e667d52003-02-04 21:47:44 +0000931 self.assertEqual(opcode_in_pickle(opcode, s1), False)
932
Guido van Rossum0322d0f2003-01-29 06:12:46 +0000933 y = self.loads(s1)
934 self.assertEqual(list(x), list(y))
935 self.assertEqual(x.__dict__, y.__dict__)
Guido van Rossum0322d0f2003-01-29 06:12:46 +0000936
Tim Peters22e71712003-02-03 22:27:38 +0000937 # Dump using protocol 2 for test.
Guido van Rossum0322d0f2003-01-29 06:12:46 +0000938 s2 = self.dumps(x, 2)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000939 self.assertNotIn(__name__.encode("utf-8"), s2)
940 self.assertNotIn(b"MyList", s2)
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000941 self.assertEqual(opcode_in_pickle(opcode, s2), True, repr(s2))
Tim Peters3e667d52003-02-04 21:47:44 +0000942
Guido van Rossum0322d0f2003-01-29 06:12:46 +0000943 y = self.loads(s2)
944 self.assertEqual(list(x), list(y))
945 self.assertEqual(x.__dict__, y.__dict__)
Guido van Rossum0322d0f2003-01-29 06:12:46 +0000946
947 finally:
Tim Peters3e667d52003-02-04 21:47:44 +0000948 e.restore()
Tim Peters22e71712003-02-03 22:27:38 +0000949
950 def test_global_ext1(self):
Tim Peters3e667d52003-02-04 21:47:44 +0000951 self.produce_global_ext(0x00000001, pickle.EXT1) # smallest EXT1 code
952 self.produce_global_ext(0x000000ff, pickle.EXT1) # largest EXT1 code
Guido van Rossum0322d0f2003-01-29 06:12:46 +0000953
954 def test_global_ext2(self):
Tim Peters3e667d52003-02-04 21:47:44 +0000955 self.produce_global_ext(0x00000100, pickle.EXT2) # smallest EXT2 code
956 self.produce_global_ext(0x0000ffff, pickle.EXT2) # largest EXT2 code
957 self.produce_global_ext(0x0000abcd, pickle.EXT2) # check endianness
Guido van Rossum0322d0f2003-01-29 06:12:46 +0000958
959 def test_global_ext4(self):
Tim Peters3e667d52003-02-04 21:47:44 +0000960 self.produce_global_ext(0x00010000, pickle.EXT4) # smallest EXT4 code
961 self.produce_global_ext(0x7fffffff, pickle.EXT4) # largest EXT4 code
962 self.produce_global_ext(0x12abcdef, pickle.EXT4) # check endianness
963
Tim Peters8d2613a2003-02-11 16:40:16 +0000964 def test_list_chunking(self):
965 n = 10 # too small to chunk
Guido van Rossum805365e2007-05-07 22:24:25 +0000966 x = list(range(n))
Tim Peters8d2613a2003-02-11 16:40:16 +0000967 for proto in protocols:
968 s = self.dumps(x, proto)
969 y = self.loads(s)
970 self.assertEqual(x, y)
971 num_appends = count_opcode(pickle.APPENDS, s)
972 self.assertEqual(num_appends, proto > 0)
973
974 n = 2500 # expect at least two chunks when proto > 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000975 x = list(range(n))
Tim Peters8d2613a2003-02-11 16:40:16 +0000976 for proto in protocols:
977 s = self.dumps(x, proto)
978 y = self.loads(s)
979 self.assertEqual(x, y)
980 num_appends = count_opcode(pickle.APPENDS, s)
981 if proto == 0:
982 self.assertEqual(num_appends, 0)
983 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000984 self.assertTrue(num_appends >= 2)
Tim Peters8d2613a2003-02-11 16:40:16 +0000985
986 def test_dict_chunking(self):
987 n = 10 # too small to chunk
988 x = dict.fromkeys(range(n))
989 for proto in protocols:
990 s = self.dumps(x, proto)
Ezio Melottie9615932010-01-24 19:26:24 +0000991 self.assertIsInstance(s, bytes_types)
Tim Peters8d2613a2003-02-11 16:40:16 +0000992 y = self.loads(s)
993 self.assertEqual(x, y)
994 num_setitems = count_opcode(pickle.SETITEMS, s)
995 self.assertEqual(num_setitems, proto > 0)
996
997 n = 2500 # expect at least two chunks when proto > 0
998 x = dict.fromkeys(range(n))
999 for proto in protocols:
1000 s = self.dumps(x, proto)
1001 y = self.loads(s)
1002 self.assertEqual(x, y)
1003 num_setitems = count_opcode(pickle.SETITEMS, s)
1004 if proto == 0:
1005 self.assertEqual(num_setitems, 0)
1006 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001007 self.assertTrue(num_setitems >= 2)
Guido van Rossum0322d0f2003-01-29 06:12:46 +00001008
Tim Peterse9ef2032003-02-13 18:42:00 +00001009 def test_simple_newobj(self):
1010 x = object.__new__(SimpleNewObj) # avoid __init__
1011 x.abc = 666
1012 for proto in protocols:
1013 s = self.dumps(x, proto)
1014 self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), proto >= 2)
1015 y = self.loads(s) # will raise TypeError if __init__ called
1016 self.assertEqual(y.abc, 666)
1017 self.assertEqual(x.__dict__, y.__dict__)
1018
Tim Peters42f08ac2003-02-11 22:43:24 +00001019 def test_newobj_list_slots(self):
1020 x = SlotList([1, 2, 3])
1021 x.foo = 42
1022 x.bar = "hello"
1023 s = self.dumps(x, 2)
1024 y = self.loads(s)
1025 self.assertEqual(list(x), list(y))
1026 self.assertEqual(x.__dict__, y.__dict__)
1027 self.assertEqual(x.foo, y.foo)
1028 self.assertEqual(x.bar, y.bar)
1029
Guido van Rossum2a30b212003-02-18 22:41:24 +00001030 def test_reduce_overrides_default_reduce_ex(self):
Collin Winter771d8342009-04-16 03:18:06 +00001031 for proto in protocols:
Guido van Rossum2a30b212003-02-18 22:41:24 +00001032 x = REX_one()
1033 self.assertEqual(x._reduce_called, 0)
1034 s = self.dumps(x, proto)
1035 self.assertEqual(x._reduce_called, 1)
1036 y = self.loads(s)
1037 self.assertEqual(y._reduce_called, 0)
1038
1039 def test_reduce_ex_called(self):
Collin Winter771d8342009-04-16 03:18:06 +00001040 for proto in protocols:
Guido van Rossum2a30b212003-02-18 22:41:24 +00001041 x = REX_two()
1042 self.assertEqual(x._proto, None)
1043 s = self.dumps(x, proto)
1044 self.assertEqual(x._proto, proto)
1045 y = self.loads(s)
1046 self.assertEqual(y._proto, None)
1047
1048 def test_reduce_ex_overrides_reduce(self):
Collin Winter771d8342009-04-16 03:18:06 +00001049 for proto in protocols:
Guido van Rossum2a30b212003-02-18 22:41:24 +00001050 x = REX_three()
1051 self.assertEqual(x._proto, None)
1052 s = self.dumps(x, proto)
1053 self.assertEqual(x._proto, proto)
1054 y = self.loads(s)
1055 self.assertEqual(y._proto, None)
1056
Guido van Rossumd8faa362007-04-27 19:54:29 +00001057 def test_reduce_ex_calls_base(self):
Collin Winter771d8342009-04-16 03:18:06 +00001058 for proto in protocols:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001059 x = REX_four()
1060 self.assertEqual(x._proto, None)
1061 s = self.dumps(x, proto)
1062 self.assertEqual(x._proto, proto)
1063 y = self.loads(s)
1064 self.assertEqual(y._proto, proto)
1065
1066 def test_reduce_calls_base(self):
Collin Winter771d8342009-04-16 03:18:06 +00001067 for proto in protocols:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001068 x = REX_five()
1069 self.assertEqual(x._reduce_called, 0)
1070 s = self.dumps(x, proto)
1071 self.assertEqual(x._reduce_called, 1)
1072 y = self.loads(s)
1073 self.assertEqual(y._reduce_called, 1)
1074
Brett Cannon31f59292011-02-21 19:29:56 +00001075 @no_tracing
Alexandre Vassalotti1f9d9072008-08-15 03:07:47 +00001076 def test_bad_getattr(self):
1077 x = BadGetattr()
1078 for proto in 0, 1:
1079 self.assertRaises(RuntimeError, self.dumps, x, proto)
1080 # protocol 2 don't raise a RuntimeError.
1081 d = self.dumps(x, 2)
Alexandre Vassalotti1f9d9072008-08-15 03:07:47 +00001082
Amaury Forgeot d'Arc424b4812008-10-30 22:25:31 +00001083 def test_reduce_bad_iterator(self):
1084 # Issue4176: crash when 4th and 5th items of __reduce__()
1085 # are not iterators
1086 class C(object):
1087 def __reduce__(self):
1088 # 4th item is not an iterator
1089 return list, (), None, [], None
1090 class D(object):
1091 def __reduce__(self):
1092 # 5th item is not an iterator
1093 return dict, (), None, None, []
1094
Amaury Forgeot d'Arc6285ffd2008-10-31 17:52:47 +00001095 # Protocol 0 is less strict and also accept iterables.
Amaury Forgeot d'Arc424b4812008-10-30 22:25:31 +00001096 for proto in protocols:
Amaury Forgeot d'Arc6285ffd2008-10-31 17:52:47 +00001097 try:
1098 self.dumps(C(), proto)
1099 except (pickle.PickleError):
1100 pass
1101 try:
1102 self.dumps(D(), proto)
1103 except (pickle.PickleError):
1104 pass
Amaury Forgeot d'Arc424b4812008-10-30 22:25:31 +00001105
Collin Winter771d8342009-04-16 03:18:06 +00001106 def test_many_puts_and_gets(self):
1107 # Test that internal data structures correctly deal with lots of
1108 # puts/gets.
1109 keys = ("aaa" + str(i) for i in range(100))
1110 large_dict = dict((k, [4, 5, 6]) for k in keys)
1111 obj = [dict(large_dict), dict(large_dict), dict(large_dict)]
1112
1113 for proto in protocols:
1114 dumped = self.dumps(obj, proto)
1115 loaded = self.loads(dumped)
1116 self.assertEqual(loaded, obj,
1117 "Failed protocol %d: %r != %r"
1118 % (proto, obj, loaded))
1119
Antoine Pitroua9f48a02009-05-02 21:41:14 +00001120 def test_attribute_name_interning(self):
1121 # Test that attribute names of pickled objects are interned when
1122 # unpickling.
1123 for proto in protocols:
1124 x = C()
1125 x.foo = 42
1126 x.bar = "hello"
1127 s = self.dumps(x, proto)
1128 y = self.loads(s)
1129 x_keys = sorted(x.__dict__)
1130 y_keys = sorted(y.__dict__)
1131 for x_key, y_key in zip(x_keys, y_keys):
1132 self.assertIs(x_key, y_key)
1133
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001134 def test_unpickle_from_2x(self):
1135 # Unpickle non-trivial data from Python 2.x.
1136 loaded = self.loads(DATA3)
1137 self.assertEqual(loaded, set([1, 2]))
1138 loaded = self.loads(DATA4)
1139 self.assertEqual(type(loaded), type(range(0)))
1140 self.assertEqual(list(loaded), list(range(5)))
1141 loaded = self.loads(DATA5)
1142 self.assertEqual(type(loaded), SimpleCookie)
1143 self.assertEqual(list(loaded.keys()), ["key"])
1144 self.assertEqual(loaded["key"].value, "Set-Cookie: key=value")
1145
1146 def test_pickle_to_2x(self):
1147 # Pickle non-trivial data with protocol 2, expecting that it yields
1148 # the same result as Python 2.x did.
1149 # NOTE: this test is a bit too strong since we can produce different
1150 # bytecode that 2.x will still understand.
1151 dumped = self.dumps(range(5), 2)
1152 self.assertEqual(dumped, DATA4)
1153 dumped = self.dumps(set([3]), 2)
1154 self.assertEqual(dumped, DATA6)
1155
Antoine Pitrouea99c5c2010-09-09 18:33:21 +00001156 def test_large_pickles(self):
1157 # Test the correctness of internal buffering routines when handling
1158 # large data.
1159 for proto in protocols:
Antoine Pitrou04248a82010-10-12 20:51:21 +00001160 data = (1, min, b'xy' * (30 * 1024), len)
Antoine Pitrouea99c5c2010-09-09 18:33:21 +00001161 dumped = self.dumps(data, proto)
1162 loaded = self.loads(dumped)
Antoine Pitrou04248a82010-10-12 20:51:21 +00001163 self.assertEqual(len(loaded), len(data))
Antoine Pitrouea99c5c2010-09-09 18:33:21 +00001164 self.assertEqual(loaded, data)
1165
Alexander Belopolsky1ce92dc2011-02-24 19:40:09 +00001166 def test_empty_bytestring(self):
1167 # issue 11286
1168 empty = self.loads(b'\x80\x03U\x00q\x00.', encoding='koi8-r')
1169 self.assertEqual(empty, '')
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001170
Antoine Pitrou3c7e9282011-08-13 20:15:19 +02001171 def test_int_pickling_efficiency(self):
1172 # Test compacity of int representation (see issue #12744)
1173 for proto in protocols:
1174 sizes = [len(self.dumps(2**n, proto)) for n in range(70)]
Antoine Pitrou85674932011-08-14 01:51:52 +02001175 # the size function is monotonic
Antoine Pitrou3c7e9282011-08-13 20:15:19 +02001176 self.assertEqual(sorted(sizes), sizes)
1177 if proto >= 2:
1178 self.assertLessEqual(sizes[-1], 14)
1179
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001180 def check_negative_32b_binXXX(self, dumped):
1181 if sys.maxsize > 2**32:
1182 self.skipTest("test is only meaningful on 32-bit builds")
1183 # XXX Pure Python pickle reads lengths as signed and passes
1184 # them directly to read() (hence the EOFError)
1185 with self.assertRaises((pickle.UnpicklingError, EOFError,
1186 ValueError, OverflowError)):
1187 self.loads(dumped)
1188
1189 def test_negative_32b_binbytes(self):
1190 # On 32-bit builds, a BINBYTES of 2**31 or more is refused
1191 self.check_negative_32b_binXXX(b'\x80\x03B\xff\xff\xff\xffxyzq\x00.')
1192
1193 def test_negative_32b_binunicode(self):
1194 # On 32-bit builds, a BINUNICODE of 2**31 or more is refused
1195 self.check_negative_32b_binXXX(b'\x80\x03X\xff\xff\xff\xffxyzq\x00.')
1196
Antoine Pitrou55549ec2011-08-30 00:27:10 +02001197 def test_negative_put(self):
1198 # Issue #12847
1199 dumped = b'Va\np-1\n.'
1200 self.assertRaises(ValueError, self.loads, dumped)
1201
1202 def test_negative_32b_binput(self):
1203 # Issue #12847
1204 if sys.maxsize > 2**32:
1205 self.skipTest("test is only meaningful on 32-bit builds")
1206 dumped = b'\x80\x03X\x01\x00\x00\x00ar\xff\xff\xff\xff.'
1207 self.assertRaises(ValueError, self.loads, dumped)
1208
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001209
1210class BigmemPickleTests(unittest.TestCase):
1211
1212 # Binary protocols can serialize longs of up to 2GB-1
1213
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001214 @bigmemtest(size=_2G, memuse=1 + 1, dry_run=False)
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001215 def test_huge_long_32b(self, size):
1216 data = 1 << (8 * size)
1217 try:
1218 for proto in protocols:
1219 if proto < 2:
1220 continue
1221 with self.assertRaises((ValueError, OverflowError)):
1222 self.dumps(data, protocol=proto)
1223 finally:
1224 data = None
1225
1226 # Protocol 3 can serialize up to 4GB-1 as a bytes object
1227 # (older protocols don't have a dedicated opcode for bytes and are
1228 # too inefficient)
1229
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001230 @bigmemtest(size=_2G, memuse=1 + 1, dry_run=False)
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001231 def test_huge_bytes_32b(self, size):
1232 data = b"abcd" * (size // 4)
1233 try:
1234 for proto in protocols:
1235 if proto < 3:
1236 continue
1237 try:
1238 pickled = self.dumps(data, protocol=proto)
1239 self.assertTrue(b"abcd" in pickled[:15])
1240 self.assertTrue(b"abcd" in pickled[-15:])
1241 finally:
1242 pickled = None
1243 finally:
1244 data = None
1245
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001246 @bigmemtest(size=_4G, memuse=1 + 1, dry_run=False)
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001247 def test_huge_bytes_64b(self, size):
1248 data = b"a" * size
1249 try:
1250 for proto in protocols:
1251 if proto < 3:
1252 continue
1253 with self.assertRaises((ValueError, OverflowError)):
1254 self.dumps(data, protocol=proto)
1255 finally:
1256 data = None
1257
1258 # All protocols use 1-byte per printable ASCII character; we add another
1259 # byte because the encoded form has to be copied into the internal buffer.
1260
Antoine Pitroub7591d42011-10-04 16:18:15 +02001261 @bigmemtest(size=_2G, memuse=2 + ascii_char_size, dry_run=False)
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001262 def test_huge_str_32b(self, size):
1263 data = "abcd" * (size // 4)
1264 try:
1265 for proto in protocols:
1266 try:
1267 pickled = self.dumps(data, protocol=proto)
1268 self.assertTrue(b"abcd" in pickled[:15])
1269 self.assertTrue(b"abcd" in pickled[-15:])
1270 finally:
1271 pickled = None
1272 finally:
1273 data = None
1274
Antoine Pitroue897e952011-08-30 23:39:34 +02001275 # BINUNICODE (protocols 1, 2 and 3) cannot carry more than
1276 # 2**32 - 1 bytes of utf-8 encoded unicode.
1277
Antoine Pitroub7591d42011-10-04 16:18:15 +02001278 @bigmemtest(size=_4G, memuse=1 + ascii_char_size, dry_run=False)
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001279 def test_huge_str_64b(self, size):
1280 data = "a" * size
1281 try:
1282 for proto in protocols:
Antoine Pitroue897e952011-08-30 23:39:34 +02001283 if proto == 0:
1284 continue
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001285 with self.assertRaises((ValueError, OverflowError)):
1286 self.dumps(data, protocol=proto)
1287 finally:
1288 data = None
1289
Antoine Pitrou3c7e9282011-08-13 20:15:19 +02001290
Guido van Rossum2a30b212003-02-18 22:41:24 +00001291# Test classes for reduce_ex
1292
1293class REX_one(object):
1294 _reduce_called = 0
1295 def __reduce__(self):
1296 self._reduce_called = 1
1297 return REX_one, ()
1298 # No __reduce_ex__ here, but inheriting it from object
1299
1300class REX_two(object):
1301 _proto = None
1302 def __reduce_ex__(self, proto):
1303 self._proto = proto
1304 return REX_two, ()
1305 # No __reduce__ here, but inheriting it from object
1306
1307class REX_three(object):
1308 _proto = None
1309 def __reduce_ex__(self, proto):
1310 self._proto = proto
1311 return REX_two, ()
1312 def __reduce__(self):
Collin Winter3add4d72007-08-29 23:37:32 +00001313 raise TestFailed("This __reduce__ shouldn't be called")
Guido van Rossum2a30b212003-02-18 22:41:24 +00001314
Guido van Rossumd8faa362007-04-27 19:54:29 +00001315class REX_four(object):
1316 _proto = None
1317 def __reduce_ex__(self, proto):
1318 self._proto = proto
1319 return object.__reduce_ex__(self, proto)
1320 # Calling base class method should succeed
1321
1322class REX_five(object):
1323 _reduce_called = 0
1324 def __reduce__(self):
1325 self._reduce_called = 1
1326 return object.__reduce__(self)
1327 # This one used to fail with infinite recursion
1328
Guido van Rossum2a30b212003-02-18 22:41:24 +00001329# Test classes for newobj
Tim Peters080c88b2003-02-15 03:01:11 +00001330
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001331class MyInt(int):
1332 sample = 1
1333
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001334class MyFloat(float):
1335 sample = 1.0
1336
1337class MyComplex(complex):
1338 sample = 1.0 + 0.0j
1339
1340class MyStr(str):
1341 sample = "hello"
1342
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001343class MyUnicode(str):
1344 sample = "hello \u1234"
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001345
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001346class MyTuple(tuple):
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001347 sample = (1, 2, 3)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001348
1349class MyList(list):
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001350 sample = [1, 2, 3]
1351
1352class MyDict(dict):
1353 sample = {"a": 1, "b": 2}
1354
Mark Dickinson5c2db372009-12-05 20:28:34 +00001355myclasses = [MyInt, MyFloat,
Guido van Rossum206b9a72003-03-02 13:53:18 +00001356 MyComplex,
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001357 MyStr, MyUnicode,
1358 MyTuple, MyList, MyDict]
1359
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001360
Guido van Rossumc8d6ef52003-01-28 22:02:31 +00001361class SlotList(MyList):
1362 __slots__ = ["foo"]
1363
Tim Peterse9ef2032003-02-13 18:42:00 +00001364class SimpleNewObj(object):
1365 def __init__(self, a, b, c):
1366 # raise an error, to make sure this isn't called
1367 raise TypeError("SimpleNewObj.__init__() didn't expect to get called")
1368
Alexandre Vassalotti1f9d9072008-08-15 03:07:47 +00001369class BadGetattr:
1370 def __getattr__(self, key):
1371 self.foo
1372
Collin Winter771d8342009-04-16 03:18:06 +00001373
Jeremy Hylton66426532001-10-15 21:38:56 +00001374class AbstractPickleModuleTests(unittest.TestCase):
1375
1376 def test_dump_closed_file(self):
Guido van Rossum3b0a3292002-08-09 16:38:32 +00001377 import os
Walter Dörwald11b41f62007-06-20 12:46:31 +00001378 f = open(TESTFN, "wb")
Guido van Rossum3b0a3292002-08-09 16:38:32 +00001379 try:
1380 f.close()
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001381 self.assertRaises(ValueError, pickle.dump, 123, f)
Guido van Rossum3b0a3292002-08-09 16:38:32 +00001382 finally:
1383 os.remove(TESTFN)
Jeremy Hylton66426532001-10-15 21:38:56 +00001384
1385 def test_load_closed_file(self):
Guido van Rossum3b0a3292002-08-09 16:38:32 +00001386 import os
Walter Dörwald11b41f62007-06-20 12:46:31 +00001387 f = open(TESTFN, "wb")
Guido van Rossum3b0a3292002-08-09 16:38:32 +00001388 try:
1389 f.close()
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001390 self.assertRaises(ValueError, pickle.dump, 123, f)
Guido van Rossum3b0a3292002-08-09 16:38:32 +00001391 finally:
1392 os.remove(TESTFN)
Jeremy Hylton4c8be852002-11-13 22:10:47 +00001393
Collin Winter771d8342009-04-16 03:18:06 +00001394 def test_load_from_and_dump_to_file(self):
1395 stream = io.BytesIO()
1396 data = [123, {}, 124]
1397 pickle.dump(data, stream)
1398 stream.seek(0)
1399 unpickled = pickle.load(stream)
1400 self.assertEqual(unpickled, data)
1401
Tim Petersc0c93702003-02-13 19:30:57 +00001402 def test_highest_protocol(self):
1403 # Of course this needs to be changed when HIGHEST_PROTOCOL changes.
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001404 self.assertEqual(pickle.HIGHEST_PROTOCOL, 3)
Tim Petersc0c93702003-02-13 19:30:57 +00001405
Martin v. Löwis544f1192004-07-27 05:22:33 +00001406 def test_callapi(self):
Collin Winter771d8342009-04-16 03:18:06 +00001407 f = io.BytesIO()
Martin v. Löwis544f1192004-07-27 05:22:33 +00001408 # With and without keyword arguments
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001409 pickle.dump(123, f, -1)
1410 pickle.dump(123, file=f, protocol=-1)
1411 pickle.dumps(123, -1)
1412 pickle.dumps(123, protocol=-1)
1413 pickle.Pickler(f, -1)
1414 pickle.Pickler(f, protocol=-1)
Tim Petersc0c93702003-02-13 19:30:57 +00001415
Amaury Forgeot d'Arc87eee632008-10-17 20:15:53 +00001416 def test_bad_init(self):
1417 # Test issue3664 (pickle can segfault from a badly initialized Pickler).
Amaury Forgeot d'Arc87eee632008-10-17 20:15:53 +00001418 # Override initialization without calling __init__() of the superclass.
1419 class BadPickler(pickle.Pickler):
1420 def __init__(self): pass
1421
1422 class BadUnpickler(pickle.Unpickler):
1423 def __init__(self): pass
1424
1425 self.assertRaises(pickle.PicklingError, BadPickler().dump, 0)
1426 self.assertRaises(pickle.UnpicklingError, BadUnpickler().load)
1427
Amaury Forgeot d'Arc3e4e72f2008-11-11 20:05:06 +00001428 def test_bad_input(self):
1429 # Test issue4298
1430 s = bytes([0x58, 0, 0, 0, 0x54])
1431 self.assertRaises(EOFError, pickle.loads, s)
1432
Amaury Forgeot d'Arc87eee632008-10-17 20:15:53 +00001433
Jeremy Hylton4c8be852002-11-13 22:10:47 +00001434class AbstractPersistentPicklerTests(unittest.TestCase):
1435
1436 # This class defines persistent_id() and persistent_load()
1437 # functions that should be used by the pickler. All even integers
1438 # are pickled using persistent ids.
1439
1440 def persistent_id(self, object):
1441 if isinstance(object, int) and object % 2 == 0:
1442 self.id_count += 1
1443 return str(object)
1444 else:
1445 return None
1446
1447 def persistent_load(self, oid):
1448 self.load_count += 1
1449 object = int(oid)
1450 assert object % 2 == 0
1451 return object
1452
1453 def test_persistence(self):
1454 self.id_count = 0
1455 self.load_count = 0
Guido van Rossum805365e2007-05-07 22:24:25 +00001456 L = list(range(10))
Jeremy Hylton4c8be852002-11-13 22:10:47 +00001457 self.assertEqual(self.loads(self.dumps(L)), L)
1458 self.assertEqual(self.id_count, 5)
1459 self.assertEqual(self.load_count, 5)
1460
1461 def test_bin_persistence(self):
1462 self.id_count = 0
1463 self.load_count = 0
Guido van Rossum805365e2007-05-07 22:24:25 +00001464 L = list(range(10))
Jeremy Hylton4c8be852002-11-13 22:10:47 +00001465 self.assertEqual(self.loads(self.dumps(L, 1)), L)
1466 self.assertEqual(self.id_count, 5)
1467 self.assertEqual(self.load_count, 5)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001468
Collin Winter771d8342009-04-16 03:18:06 +00001469
1470class AbstractPicklerUnpicklerObjectTests(unittest.TestCase):
1471
1472 pickler_class = None
1473 unpickler_class = None
1474
1475 def setUp(self):
1476 assert self.pickler_class
1477 assert self.unpickler_class
1478
1479 def test_clear_pickler_memo(self):
1480 # To test whether clear_memo() has any effect, we pickle an object,
1481 # then pickle it again without clearing the memo; the two serialized
1482 # forms should be different. If we clear_memo() and then pickle the
1483 # object again, the third serialized form should be identical to the
1484 # first one we obtained.
1485 data = ["abcdefg", "abcdefg", 44]
1486 f = io.BytesIO()
1487 pickler = self.pickler_class(f)
1488
1489 pickler.dump(data)
1490 first_pickled = f.getvalue()
1491
1492 # Reset StringIO object.
1493 f.seek(0)
1494 f.truncate()
1495
1496 pickler.dump(data)
1497 second_pickled = f.getvalue()
1498
1499 # Reset the Pickler and StringIO objects.
1500 pickler.clear_memo()
1501 f.seek(0)
1502 f.truncate()
1503
1504 pickler.dump(data)
1505 third_pickled = f.getvalue()
1506
1507 self.assertNotEqual(first_pickled, second_pickled)
1508 self.assertEqual(first_pickled, third_pickled)
1509
1510 def test_priming_pickler_memo(self):
1511 # Verify that we can set the Pickler's memo attribute.
1512 data = ["abcdefg", "abcdefg", 44]
1513 f = io.BytesIO()
1514 pickler = self.pickler_class(f)
1515
1516 pickler.dump(data)
1517 first_pickled = f.getvalue()
1518
1519 f = io.BytesIO()
1520 primed = self.pickler_class(f)
1521 primed.memo = pickler.memo
1522
1523 primed.dump(data)
1524 primed_pickled = f.getvalue()
1525
1526 self.assertNotEqual(first_pickled, primed_pickled)
1527
1528 def test_priming_unpickler_memo(self):
1529 # Verify that we can set the Unpickler's memo attribute.
1530 data = ["abcdefg", "abcdefg", 44]
1531 f = io.BytesIO()
1532 pickler = self.pickler_class(f)
1533
1534 pickler.dump(data)
1535 first_pickled = f.getvalue()
1536
1537 f = io.BytesIO()
1538 primed = self.pickler_class(f)
1539 primed.memo = pickler.memo
1540
1541 primed.dump(data)
1542 primed_pickled = f.getvalue()
1543
1544 unpickler = self.unpickler_class(io.BytesIO(first_pickled))
1545 unpickled_data1 = unpickler.load()
1546
1547 self.assertEqual(unpickled_data1, data)
1548
1549 primed = self.unpickler_class(io.BytesIO(primed_pickled))
1550 primed.memo = unpickler.memo
1551 unpickled_data2 = primed.load()
1552
1553 primed.memo.clear()
1554
1555 self.assertEqual(unpickled_data2, data)
1556 self.assertTrue(unpickled_data2 is unpickled_data1)
1557
1558 def test_reusing_unpickler_objects(self):
1559 data1 = ["abcdefg", "abcdefg", 44]
1560 f = io.BytesIO()
1561 pickler = self.pickler_class(f)
1562 pickler.dump(data1)
1563 pickled1 = f.getvalue()
1564
1565 data2 = ["abcdefg", 44, 44]
1566 f = io.BytesIO()
1567 pickler = self.pickler_class(f)
1568 pickler.dump(data2)
1569 pickled2 = f.getvalue()
1570
1571 f = io.BytesIO()
1572 f.write(pickled1)
1573 f.seek(0)
1574 unpickler = self.unpickler_class(f)
1575 self.assertEqual(unpickler.load(), data1)
1576
1577 f.seek(0)
1578 f.truncate()
1579 f.write(pickled2)
1580 f.seek(0)
1581 self.assertEqual(unpickler.load(), data2)
1582
Antoine Pitrou04248a82010-10-12 20:51:21 +00001583 def _check_multiple_unpicklings(self, ioclass):
1584 for proto in protocols:
1585 data1 = [(x, str(x)) for x in range(2000)] + [b"abcde", len]
1586 f = ioclass()
1587 pickler = self.pickler_class(f, protocol=proto)
1588 pickler.dump(data1)
1589 pickled = f.getvalue()
1590
1591 N = 5
1592 f = ioclass(pickled * N)
1593 unpickler = self.unpickler_class(f)
1594 for i in range(N):
1595 if f.seekable():
1596 pos = f.tell()
1597 self.assertEqual(unpickler.load(), data1)
1598 if f.seekable():
1599 self.assertEqual(f.tell(), pos + len(pickled))
1600 self.assertRaises(EOFError, unpickler.load)
1601
1602 def test_multiple_unpicklings_seekable(self):
1603 self._check_multiple_unpicklings(io.BytesIO)
1604
1605 def test_multiple_unpicklings_unseekable(self):
1606 self._check_multiple_unpicklings(UnseekableIO)
1607
Antoine Pitrouf6c7a852011-08-11 21:04:02 +02001608 def test_unpickling_buffering_readline(self):
1609 # Issue #12687: the unpickler's buffering logic could fail with
1610 # text mode opcodes.
1611 data = list(range(10))
1612 for proto in protocols:
1613 for buf_size in range(1, 11):
1614 f = io.BufferedRandom(io.BytesIO(), buffer_size=buf_size)
1615 pickler = self.pickler_class(f, protocol=proto)
1616 pickler.dump(data)
1617 f.seek(0)
1618 unpickler = self.unpickler_class(f)
1619 self.assertEqual(unpickler.load(), data)
1620
Collin Winter771d8342009-04-16 03:18:06 +00001621
Antoine Pitrou8d3c2902012-03-04 18:31:48 +01001622# Tests for dispatch_table attribute
1623
1624REDUCE_A = 'reduce_A'
1625
1626class AAA(object):
1627 def __reduce__(self):
1628 return str, (REDUCE_A,)
1629
1630class BBB(object):
1631 pass
1632
1633class AbstractDispatchTableTests(unittest.TestCase):
1634
1635 def test_default_dispatch_table(self):
1636 # No dispatch_table attribute by default
1637 f = io.BytesIO()
1638 p = self.pickler_class(f, 0)
1639 with self.assertRaises(AttributeError):
1640 p.dispatch_table
1641 self.assertFalse(hasattr(p, 'dispatch_table'))
1642
1643 def test_class_dispatch_table(self):
1644 # A dispatch_table attribute can be specified class-wide
1645 dt = self.get_dispatch_table()
1646
1647 class MyPickler(self.pickler_class):
1648 dispatch_table = dt
1649
1650 def dumps(obj, protocol=None):
1651 f = io.BytesIO()
1652 p = MyPickler(f, protocol)
1653 self.assertEqual(p.dispatch_table, dt)
1654 p.dump(obj)
1655 return f.getvalue()
1656
1657 self._test_dispatch_table(dumps, dt)
1658
1659 def test_instance_dispatch_table(self):
1660 # A dispatch_table attribute can also be specified instance-wide
1661 dt = self.get_dispatch_table()
1662
1663 def dumps(obj, protocol=None):
1664 f = io.BytesIO()
1665 p = self.pickler_class(f, protocol)
1666 p.dispatch_table = dt
1667 self.assertEqual(p.dispatch_table, dt)
1668 p.dump(obj)
1669 return f.getvalue()
1670
1671 self._test_dispatch_table(dumps, dt)
1672
1673 def _test_dispatch_table(self, dumps, dispatch_table):
1674 def custom_load_dump(obj):
1675 return pickle.loads(dumps(obj, 0))
1676
1677 def default_load_dump(obj):
1678 return pickle.loads(pickle.dumps(obj, 0))
1679
1680 # pickling complex numbers using protocol 0 relies on copyreg
1681 # so check pickling a complex number still works
1682 z = 1 + 2j
1683 self.assertEqual(custom_load_dump(z), z)
1684 self.assertEqual(default_load_dump(z), z)
1685
1686 # modify pickling of complex
1687 REDUCE_1 = 'reduce_1'
1688 def reduce_1(obj):
1689 return str, (REDUCE_1,)
1690 dispatch_table[complex] = reduce_1
1691 self.assertEqual(custom_load_dump(z), REDUCE_1)
1692 self.assertEqual(default_load_dump(z), z)
1693
1694 # check picklability of AAA and BBB
1695 a = AAA()
1696 b = BBB()
1697 self.assertEqual(custom_load_dump(a), REDUCE_A)
1698 self.assertIsInstance(custom_load_dump(b), BBB)
1699 self.assertEqual(default_load_dump(a), REDUCE_A)
1700 self.assertIsInstance(default_load_dump(b), BBB)
1701
1702 # modify pickling of BBB
1703 dispatch_table[BBB] = reduce_1
1704 self.assertEqual(custom_load_dump(a), REDUCE_A)
1705 self.assertEqual(custom_load_dump(b), REDUCE_1)
1706 self.assertEqual(default_load_dump(a), REDUCE_A)
1707 self.assertIsInstance(default_load_dump(b), BBB)
1708
1709 # revert pickling of BBB and modify pickling of AAA
1710 REDUCE_2 = 'reduce_2'
1711 def reduce_2(obj):
1712 return str, (REDUCE_2,)
1713 dispatch_table[AAA] = reduce_2
1714 del dispatch_table[BBB]
1715 self.assertEqual(custom_load_dump(a), REDUCE_2)
1716 self.assertIsInstance(custom_load_dump(b), BBB)
1717 self.assertEqual(default_load_dump(a), REDUCE_A)
1718 self.assertIsInstance(default_load_dump(b), BBB)
1719
1720
Guido van Rossum98297ee2007-11-06 21:34:58 +00001721if __name__ == "__main__":
1722 # Print some stuff that can be used to rewrite DATA{0,1,2}
1723 from pickletools import dis
1724 x = create_data()
1725 for i in range(3):
1726 p = pickle.dumps(x, i)
1727 print("DATA{0} = (".format(i))
1728 for j in range(0, len(p), 20):
1729 b = bytes(p[j:j+20])
1730 print(" {0!r}".format(b))
1731 print(")")
1732 print()
1733 print("# Disassembly of DATA{0}".format(i))
1734 print("DATA{0}_DIS = \"\"\"\\".format(i))
1735 dis(p)
1736 print("\"\"\"")
1737 print()