Debian Codegraph @

pypy/interpreter/test/test_zzpickle_and_slow.py

raw symbols SCIP
1 import py
2 from pypy import conftest
3 from pypy.interpreter import gateway
4 from rpython.rlib.jit import non_virtual_ref, vref_None
5
6 class AppTestSlow:
7 def setup_class(cls):
8 if py.test.config.option.runappdirect:
9 filename = __file__
10 else:
11 filename = gateway.__file__
12
13 if filename[-3:] != '.py':
14 filename = filename[:-1]
15
16 cls.w_file = cls.space.wrap(filename)
17
18 def test_inspect(self):
19 if not hasattr(len, 'func_code'):
20 skip("Cannot run this test if builtins have no func_code")
21 import inspect
22 args, varargs, varkw = inspect.getargs(len.__code__)
23 assert args == ['obj']
24 assert varargs is None
25 assert varkw is None
26
27 def _attach_helpers(space):
28 from pypy.interpreter import pytraceback
29 def hide_top_frame(space, w_frame):
30 w_last = None
31 while w_frame.f_backref():
32 w_last = w_frame
33 w_frame = w_frame.f_backref()
34 assert w_last
35 w_saved = w_last.f_backref()
36 w_last.f_backref = vref_None
37 return w_saved
38
39 def restore_top_frame(space, w_frame, w_saved):
40 while w_frame.f_backref():
41 w_frame = w_frame.f_backref()
42 w_frame.f_backref = non_virtual_ref(w_saved)
43
44 def read_exc_type(space, w_frame):
45 if w_frame.last_exception is None:
46 return space.w_None
47 else:
48 return w_frame.last_exception.w_type
49
50 from pypy.interpreter import gateway
51
52 hide_gw = gateway.interp2app(hide_top_frame)
53 space.setitem(space.builtin.w_dict,
54 space.wrap('hide_top_frame'),
55 space.wrap(hide_gw))
56 restore_gw = gateway.interp2app(restore_top_frame)
57 space.setitem(space.builtin.w_dict,
58 space.wrap('restore_top_frame'),
59 space.wrap(restore_gw))
60
61 read_exc_type_gw = gateway.interp2app(read_exc_type)
62 space.setitem(space.builtin.w_dict,
63 space.wrap('read_exc_type'),
64 space.wrap(read_exc_type_gw))
65
66 def _detach_helpers(space):
67 space.delitem(space.builtin.w_dict,
68 space.wrap('hide_top_frame'))
69 space.delitem(space.builtin.w_dict,
70 space.wrap('restore_top_frame'))
71
72
73 class AppTestInterpObjectPickling:
74 spaceconfig = {
75 "usemodules": ["struct", "binascii"]
76 }
77 def setup_class(cls):
78 runappdirect = py.test.config.option.runappdirect
79 cls.w_runappdirect = cls.space.wrap(runappdirect)
80
81 def w_skip_on_cpython(self):
82 import sys
83 if self.runappdirect and '__pypy__' not in sys.modules:
84 skip('Does not work on CPython')
85
86 def test_pickle_basic(self):
87 import _pickle as pickle
88 pckl = pickle.dumps((u'abc', 0))
89 result = pickle.loads(pckl)
90 assert result == (u'abc', 0)
91
92 def test_pickle_code(self):
93 self.skip_on_cpython()
94 def f():
95 return 42
96 import _pickle as pickle
97 code = f.__code__
98 pckl = pickle.dumps(code)
99 result = pickle.loads(pckl)
100 assert code == result
101
102 def test_pickle_global_func(self):
103 import types
104 mod = types.ModuleType('mod')
105 import sys
106 sys.modules['mod'] = mod
107 try:
108 def func():
109 return 42
110 mod.__dict__['func'] = func
111 func.__module__ = 'mod'
112 func.__qualname__ = 'func'
113 import _pickle as pickle
114 pckl = pickle.dumps(func)
115 result = pickle.loads(pckl)
116 assert func is result
117 finally:
118 del sys.modules['mod']
119
120 def test_pickle_not_imported_module(self):
121 self.skip_on_cpython()
122 import types
123 mod = types.ModuleType('mod')
124 mod.__dict__['a'] = 1
125 import _pickle as pickle
126 pckl = pickle.dumps(mod)
127 result = pickle.loads(pckl)
128 assert mod.__name__ == result.__name__
129 assert mod.__dict__ == result.__dict__
130
131 def test_pickle_builtin_func(self):
132 import _pickle as pickle
133 pckl = pickle.dumps(map)
134 result = pickle.loads(pckl)
135 assert map is result
136
137 def test_pickle_non_top_reachable_func(self):
138 self.skip_on_cpython()
139 skip("this behavior was disabled to follow CPython more closely")
140 def func():
141 return 42
142 global a
143 a = 42
144 del globals()['test_pickle_non_top_reachable_func']
145 import _pickle as pickle
146 pckl = pickle.dumps(func)
147 result = pickle.loads(pckl)
148 assert func.__name__ == result.__name__
149 assert func.__closure__ == result.__closure__
150 assert func.__code__ == result.__code__
151 assert func.__defaults__ == result.__defaults__
152 assert func.__dict__ == result.__dict__
153 assert func.__doc__ == result.__doc__
154 assert func.__globals__ == result.__globals__
155
156 def test_pickle_cell(self):
157 self.skip_on_cpython()
158 def g():
159 x = [42]
160 def f():
161 x[0] += 1
162 return x
163 return f.__closure__[0]
164 import _pickle as pickle
165 cell = g()
166 pckl = pickle.dumps(cell)
167 result = pickle.loads(pckl)
168 assert cell == result
169 assert not (cell != result)
170
171 def test_pickle_module(self):
172 self.skip_on_cpython()
173 import _pickle as pickle
174 mod = pickle
175 pckl = pickle.dumps(mod)
176 result = pickle.loads(pckl)
177 assert mod is result
178
179 def test_pickle_moduledict(self):
180 skip("this behavior was disabled to follow CPython more closely")
181 self.skip_on_cpython()
182 import _pickle as pickle
183 moddict = pickle.__dict__
184 pckl = pickle.dumps(moddict)
185 result = pickle.loads(pckl)
186 assert moddict is result
187
188 def test_pickle_bltins_module(self):
189 self.skip_on_cpython()
190 import _pickle as pickle
191 mod = __builtins__
192 pckl = pickle.dumps(mod)
193 result = pickle.loads(pckl)
194 assert mod is result
195
196 def test_pickle_complex(self):
197 import _pickle as pickle
198 a = complex(1.23,4.567)
199 pckl = pickle.dumps(a)
200 result = pickle.loads(pckl)
201 assert a == result
202
203 def test_pickle_method(self):
204 skip("this behavior was disabled to follow CPython more closely")
205 class myclass(object):
206 def f(self):
207 return 42
208 def __reduce__(self):
209 return (myclass, ())
210 import _pickle as pickle, sys, types
211 myclass.__module__ = 'mod'
212 myclass.__qualname__ = 'myclass'
213 myclass_inst = myclass()
214 mod = types.ModuleType('mod')
215 mod.myclass = myclass
216 sys.modules['mod'] = mod
217 try:
218 method = myclass_inst.f
219 pckl = pickle.dumps(method)
220 result = pickle.loads(pckl)
221 # we cannot compare the objects, because the method will be a fresh one
222 assert method() == result()
223 finally:
224 del sys.modules['mod']
225
226 def test_pickle_staticmethod(self):
227 skip("this behavior was disabled to follow CPython more closely")
228 self.skip_on_cpython()
229 class myclass(object):
230 def f():
231 return 42
232 f = staticmethod(f)
233 import _pickle as pickle
234 method = myclass.f
235 pckl = pickle.dumps(method)
236 result = pickle.loads(pckl)
237 assert method() == result()
238
239 def test_pickle_classmethod(self):
240 skip("this behavior was disabled to follow CPython more closely")
241 class myclass(object):
242 def f(cls):
243 return cls
244 f = classmethod(f)
245 import _pickle as pickle, sys, types
246 myclass.__module__ = 'mod'
247 myclass.__qualname__ = 'myclass'
248 mod = types.ModuleType('mod')
249 mod.myclass = myclass
250 sys.modules['mod'] = mod
251 try:
252 method = myclass.f
253 pckl = pickle.dumps(method)
254 result = pickle.loads(pckl)
255 assert method() == result()
256 finally:
257 del sys.modules['mod']
258
259 def test_pickle_sequenceiter(self):
260 '''
261 In PyPy there is no distinction here between listiterator and
262 tupleiterator that is why you will find no test_pickle_listiter nor
263 test_pickle_tupleiter here, just this test.
264 '''
265 import _pickle as pickle
266 liter = iter([3,9,6,12,15,17,19,111])
267 next(liter)
268 pckl = pickle.dumps(liter)
269 result = pickle.loads(pckl)
270 next(liter)
271 next(result)
272 assert type(liter) is type(result)
273 raises(TypeError, len, liter)
274 assert list(liter) == list(result)
275
276 def test_pickle_reversesequenceiter(self):
277 import _pickle as pickle
278 liter = reversed([3,9,6,12,15,17,19,111])
279 next(liter)
280 pckl = pickle.dumps(liter)
281 result = pickle.loads(pckl)
282 next(liter)
283 next(result)
284 assert type(liter) is type(result)
285 raises(TypeError, len, liter)
286 assert list(liter) == list(result)
287
288 def test_pickle_reversesequenceiter_stopped(self):
289 import _pickle as pickle
290 iter = reversed([])
291 raises(StopIteration, next, iter)
292 pckl = pickle.dumps(iter)
293 result = pickle.loads(pckl)
294 raises(StopIteration, next, result)
295
296 def test_pickle_dictiter(self):
297 import _pickle as pickle
298 tdict = {'2':2, '3':3, '5':5}
299 diter = iter(tdict)
300 res1 = next(diter)
301 s = pickle.dumps(diter)
302 res2 = next(diter)
303 res3 = next(diter)
304 assert {res1, res2, res3} == set(tdict)
305
306 diter2 = pickle.loads(s)
307 assert set(diter2) == set(tdict) - {res1}
308
309 def test_pickle_reversed(self):
310 import _pickle as pickle
311 r = reversed(tuple(range(10)))
312 next(r)
313 next(r)
314 pickled = pickle.dumps(r)
315 result = pickle.loads(pickled)
316 next(result)
317 next(r)
318 assert type(r) is type(result)
319 assert list(r) == list(result)
320
321 def test_pickle_reversed_stopped(self):
322 import _pickle as pickle
323 class IE(object):
324 def __len__(self):
325 return 1
326 def __getitem__(self, i):
327 raise IndexError
328 for it in (), IE():
329 iter = reversed(it)
330 raises(StopIteration, next, iter)
331 pckl = pickle.dumps(iter)
332 result = pickle.loads(pckl)
333 raises(StopIteration, next, result)
334
335 def test_pickle_enum(self):
336 import _pickle as pickle
337 e = enumerate(range(100, 106))
338 next(e)
339 next(e)
340 pckl = pickle.dumps(e)
341 result = pickle.loads(pckl)
342 res = next(e)
343 assert res == (2, 102)
344 res = next(result)
345 assert res == (2, 102)
346 assert type(e) is type(result)
347 res = list(e)
348 assert res == [(3, 103), (4, 104), (5, 105)]
349 res = list(result)
350 assert res == [(3, 103), (4, 104), (5, 105)]
351
352 def test_pickle_xrangeiter(self):
353 import _pickle as pickle
354 riter = iter(range(5))
355 next(riter)
356 next(riter)
357 pckl = pickle.dumps(riter)
358 result = pickle.loads(pckl)
359 assert type(riter) is type(result)
360 assert list(result) == [2,3,4]
361
362 def test_pickle_generator(self):
363 skip("not supported any more for now")
364 self.skip_on_cpython()
365 import types
366 mod = types.ModuleType('mod')
367 import sys
368 sys.modules['mod'] = mod
369 try:
370 def giveme(n):
371 x = 0
372 while x < n:
373 yield x
374 x += 1
375 import _pickle as pickle
376 mod.giveme = giveme
377 giveme.__module__ = mod
378 g1 = mod.giveme(10)
379 #next(g1)
380 #next(g1)
381 pckl = pickle.dumps(g1)
382 g2 = pickle.loads(pckl)
383 assert list(g1) == list(g2)
384 finally:
385 del sys.modules['mod']
386
387 def test_pickle_generator_blk(self):
388 skip("not supported any more for now")
389 self.skip_on_cpython()
390 # same as above but with the generator inside a block
391 import types
392 mod = types.ModuleType('mod')
393 import sys
394 sys.modules['mod'] = mod
395 try:
396 def giveme(n):
397 x = 0
398 while x < n:
399 yield x
400 x += 1
401 import _pickle as pickle
402 mod.giveme = giveme
403 giveme.__module__ = mod
404 giveme.__qualname__ = 'giveme'
405 g1 = mod.giveme(10)
406 next(g1)
407 next(g1)
408 pckl = pickle.dumps(g1)
409 g2 = pickle.loads(pckl)
410 assert list(g1) == list(g2)
411 finally:
412 del sys.modules['mod']
413
414 def test_pickle_builtin_method(self):
415 import _pickle as pickle
416
417 a_list = [1]
418 meth1 = a_list.append
419 pckl = pickle.dumps(meth1)
420 meth2 = pickle.loads(pckl)
421 meth1(1)
422 meth2(2)
423 assert a_list == [1, 1]
424 assert meth2.__self__ == [1, 2]
425
426 def test_pickle_submodule(self):
427 self.skip_on_cpython()
428 import _pickle as pickle
429 import sys, types
430
431 mod = types.ModuleType('pack.mod')
432 sys.modules['pack.mod'] = mod
433 pack = types.ModuleType('pack')
434 pack.mod = mod
435 sys.modules['pack'] = pack
436
437 import pack.mod
438 pckl = pickle.dumps(pack.mod)
439 result = pickle.loads(pckl)
440 assert pack.mod is result
441
442 def test_dict_subclass(self):
443 import _pickle as pickle
444 import sys
445 import types
446 sys.modules['mod'] = mod = types.ModuleType('mod')
447 try:
448 class MyDict(dict):
449 pass
450 MyDict.__module__ = 'mod'
451 MyDict.__qualname__ = MyDict.__name__
452 mod.MyDict = MyDict
453 obj = MyDict()
454 pckl = pickle.dumps(obj)
455 result = pickle.loads(pckl)
456 assert obj == result
457 finally:
458 del sys.modules['mod']
459
460
461 def test_pickle_generator_crash(self):
462 skip("not supported any more for now")
463 self.skip_on_cpython()
464 import _pickle as pickle
465
466 def f():
467 yield 0
468
469 x = f()
470 next(x)
471 try:
472 next(x)
473 except StopIteration:
474 y = pickle.loads(pickle.dumps(x))
475 assert 'finished' in y.__name__
476 assert 'finished' in repr(y)
477 assert y.gi_code is None
478
479 def test_pickle_memoryview(self):
480 import _pickle as pickle
481 raises(TypeError, pickle.dumps, memoryview(b"abc"))
482
483 class XAppTestGeneratorCloning:
484
485 def setup_class(cls):
486 try:
487 cls.space.appexec([], """():
488 def f(): yield 42
489 f().__reduce__()
490 """)
491 except TypeError as e:
492 if 'pickle generator' not in str(e):
493 raise
494 py.test.skip("Frames can't be __reduce__()-ed")
495
496 def test_deepcopy_generator(self):
497 import copy
498
499 def f(n):
500 for i in range(n):
501 yield 42 + i
502 g = f(4)
503 g2 = copy.deepcopy(g)
504 res = next(g)
505 assert res == 42
506 res = next(g2)
507 assert res == 42
508 g3 = copy.deepcopy(g)
509 res = next(g)
510 assert res == 43
511 res = next(g2)
512 assert res == 43
513 res = next(g3)
514 assert res == 43
515
516 def test_shallowcopy_generator(self):
517 """Note: shallow copies of generators are often confusing.
518 To start with, 'for' loops have an iterator that will not
519 be copied, and so create tons of confusion.
520 """
521 import copy
522
523 def f(n):
524 while n > 0:
525 yield 42 + n
526 n -= 1
527 g = f(2)
528 g2 = copy.copy(g)
529 res = next(g)
530 assert res == 44
531 res = next(g2)
532 assert res == 44
533 g3 = copy.copy(g)
534 res = next(g)
535 assert res == 43
536 res = next(g2)
537 assert res == 43
538 res = next(g3)
539 assert res == 43
540 g4 = copy.copy(g2)
541 for i in range(2):
542 raises(StopIteration, next, g)
543 raises(StopIteration, next, g2)
544 raises(StopIteration, next, g3)
545 raises(StopIteration, next, g4)
546
547 class XAppTestFramePickling(object):
548 pytestmark = py.test.mark.skipif("config.option.runappdirect")
549 spaceconfig = {
550 "usemodules": ["struct"]
551 }
552
553 def setup_class(cls):
554 _attach_helpers(cls.space)
555
556 def teardown_class(cls):
557 _detach_helpers(cls.space)
558
559 def test_pickle_frame(self):
560 #import sys
561 # avoid creating a closure for now
562 def f():
563 try:
564 raise Exception()
565 except:
566 import sys
567 exc_type, exc, tb = sys.exc_info()
568 return tb.tb_frame
569 import _pickle as pickle
570 f1 = f()
571 saved = hide_top_frame(f1)
572 pckl = pickle.dumps(f1)
573 restore_top_frame(f1, saved)
574 f2 = pickle.loads(pckl)
575
576 assert type(f1) is type(f2)
577 assert dir(f1) == dir(f2)
578 assert f1.__doc__ == f2.__doc__
579 assert f2.f_back is None # because we pruned it
580 assert f1.f_builtins is f2.f_builtins
581 assert f1.f_code == f2.f_code
582 assert f1.f_exc_traceback is f2.f_exc_traceback
583 assert f1.f_exc_type is f2.f_exc_type
584 assert f1.f_exc_value is f2.f_exc_value
585 assert f1.f_lasti == f2.f_lasti
586 assert f1.f_lineno == f2.f_lineno
587 assert f1.f_restricted is f2.f_restricted
588 assert f1.f_trace is f2.f_trace
589
590 def test_pickle_frame_with_exc(self):
591 #import sys
592 # avoid creating a closure for now
593 self = None
594 def f():
595 try:
596 raise ValueError
597 except:
598 import sys, pickle
599 f = sys._getframe()
600 saved = hide_top_frame(f)
601 pckl = pickle.dumps(f)
602 restore_top_frame(f, saved)
603 return pckl
604
605 import _pickle as pickle
606 pckl = f()
607 f2 = pickle.loads(pckl)
608
609 assert read_exc_type(f2) is ValueError
610
611 def test_pickle_frame_with_exc_nested(self):
612 # avoid creating a closure for now
613 self = None
614 def f():
615 try:
616 1/0
617 except:
618 try:
619 raise ValueError
620 except:
621 import sys, pickle
622 f = sys._getframe()
623 saved = hide_top_frame(f)
624 pckl = pickle.dumps(f)
625 restore_top_frame(f, saved)
626 return pckl
627
628 import _pickle as pickle
629 pckl = f()
630 f2 = pickle.loads(pckl)
631
632 assert read_exc_type(f2) is ValueError
633
634 def test_pickle_frame_clos(self):
635 # similar to above, therefore skipping the asserts.
636 # we just want to see that the closure works
637 import sys # this is the difference!
638 def f():
639 try:
640 raise Exception()
641 except:
642 exc_type, exc, tb = sys.exc_info()
643 return tb.tb_frame
644 import _pickle as pickle
645 f1 = f()
646 saved = hide_top_frame(f1)
647 pckl = pickle.dumps(f1)
648 restore_top_frame(f1, saved)
649 f2 = pickle.loads(pckl)
650
651 def test_frame_setstate_crash(self):
652 import sys
653 raises(ValueError, sys._getframe().__setstate__, [])
654
655 def test_pickle_traceback(self):
656 def f():
657 try:
658 raise Exception()
659 except:
660 from sys import exc_info
661 exc_type, exc, tb = exc_info()
662 return tb
663 import _pickle as pickle
664 tb = f()
665 saved = hide_top_frame(tb.tb_frame)
666 pckl = pickle.dumps(tb)
667 result = pickle.loads(pckl)
668
669 assert type(tb) is type(result)
670 assert tb.tb_lasti == result.tb_lasti
671 assert tb.tb_lineno == result.tb_lineno
672 assert tb.tb_next == result.tb_next
673
674 restore_top_frame(tb.tb_frame, saved)