Debian Codegraph @

lib-python/3/ctypes/test/test_pickling.py

raw symbols SCIP
1 import unittest
2 import pickle
3 from ctypes import *
4 from ctypes.test import xfail
5 import _ctypes_test
6 dll = CDLL(_ctypes_test.__file__)
7
8 class X(Structure):
9 _fields_ = [("a", c_int), ("b", c_double)]
10 init_called = 0
11 def __init__(self, *args, **kw):
12 X.init_called += 1
13 self.x = 42
14
15 class Y(X):
16 _fields_ = [("str", c_char_p)]
17
18 class PickleTest:
19 def dumps(self, item):
20 return pickle.dumps(item, self.proto)
21
22 def loads(self, item):
23 return pickle.loads(item)
24
25 def test_simple(self):
26 for src in [
27 c_int(42),
28 c_double(3.14),
29 ]:
30 dst = self.loads(self.dumps(src))
31 # PyPy modification: the dict contains the _buffer, which isn't equal
32 #self.assertEqual(src.__dict__, dst.__dict__)
33 self.assertEqual(memoryview(src).tobytes(),
34 memoryview(dst).tobytes())
35
36 def test_struct(self):
37 X.init_called = 0
38
39 x = X()
40 x.a = 42
41 self.assertEqual(X.init_called, 1)
42
43 y = self.loads(self.dumps(x))
44
45 # loads must NOT call __init__
46 self.assertEqual(X.init_called, 1)
47
48 # ctypes instances are identical when the instance __dict__
49 # and the memory buffer are identical
50 # PyPy modification: the __dict__ contains the _buffer
51 self.assertEqual(y.__dict__.keys(), x.__dict__.keys())
52 self.assertEqual(y.a, x.a)
53 self.assertEqual(memoryview(y).tobytes(),
54 memoryview(x).tobytes())
55
56 def test_unpickable(self):
57 # ctypes objects that are pointers or contain pointers are
58 # unpickable.
59 self.assertRaises(ValueError, lambda: self.dumps(Y()))
60
61 prototype = CFUNCTYPE(c_int)
62
63 for item in [
64 c_char_p(),
65 c_wchar_p(),
66 c_void_p(),
67 pointer(c_int(42)),
68 dll._testfunc_p_p,
69 prototype(lambda: 42),
70 ]:
71 self.assertRaises(ValueError, lambda: self.dumps(item))
72
73 def test_wchar(self):
74 self.dumps(c_char(b"x"))
75 # Issue 5049
76 self.dumps(c_wchar("x"))
77
78 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
79 name = 'PickleTest_%s' % proto
80 globals()[name] = type(name,
81 (PickleTest, unittest.TestCase),
82 {'proto': proto})
83
84 if __name__ == "__main__":
85 unittest.main()