Debian Codegraph @

Lib/test/test_ctypes/test_pickling.py

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