ยปCore Development>Code coverage>Lib/ctypes/test/test_pickling.py

Python code coverage for Lib/ctypes/test/test_pickling.py

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