diff options
author | Thomas Heller <theller@ctypes.org> | 2008-02-13 20:40:44 (GMT) |
---|---|---|
committer | Thomas Heller <theller@ctypes.org> | 2008-02-13 20:40:44 (GMT) |
commit | 13394e907dc452537120b051cb4cdafe4900f334 (patch) | |
tree | e13a8e2f903ce01c206dd9c94243d66758d02e0f /Lib | |
parent | 2bc6b5eb369b70a068f8de8728914467bb35b017 (diff) | |
download | cpython-13394e907dc452537120b051cb4cdafe4900f334.zip cpython-13394e907dc452537120b051cb4cdafe4900f334.tar.gz cpython-13394e907dc452537120b051cb4cdafe4900f334.tar.bz2 |
Merged revisions 60767,60768 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r60767 | thomas.heller | 2008-02-13 21:21:53 +0100 (Mi, 13 Feb 2008) | 1 line
Add pickle support to ctypes types.
........
r60768 | thomas.heller | 2008-02-13 21:36:51 +0100 (Mi, 13 Feb 2008) | 1 line
Make the test somewhat clearer (I hope).
........
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/ctypes/test/test_pickling.py | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/Lib/ctypes/test/test_pickling.py b/Lib/ctypes/test/test_pickling.py new file mode 100644 index 0000000..94a14b9 --- /dev/null +++ b/Lib/ctypes/test/test_pickling.py @@ -0,0 +1,78 @@ +import unittest +import pickle +from ctypes import * +import _ctypes_test +dll = CDLL(_ctypes_test.__file__) + +class X(Structure): + _fields_ = [("a", c_int), ("b", c_double)] + init_called = 0 + def __init__(self, *args, **kw): + X.init_called += 1 + self.x = 42 + +class Y(X): + _fields_ = [("str", c_char_p)] + +class PickleTest(unittest.TestCase): + def dumps(self, item): + return pickle.dumps(item) + + def loads(self, item): + return pickle.loads(item) + + def test_simple(self): + for src in [ + c_int(42), + c_double(3.14), + ]: + dst = self.loads(self.dumps(src)) + self.failUnlessEqual(src.__dict__, dst.__dict__) + self.failUnlessEqual(memoryview(src).tobytes(), + memoryview(dst).tobytes()) + + def test_struct(self): + X.init_called = 0 + + x = X() + x.a = 42 + self.failUnlessEqual(X.init_called, 1) + + y = self.loads(self.dumps(x)) + + # loads must NOT call __init__ + self.failUnlessEqual(X.init_called, 1) + + # ctypes instances are identical when the instance __dict__ + # and the memory buffer are identical + self.failUnlessEqual(y.__dict__, x.__dict__) + self.failUnlessEqual(memoryview(y).tobytes(), + memoryview(x).tobytes()) + + def test_unpickable(self): + # ctypes objects that are pointers or contain pointers are + # unpickable. + self.assertRaises(ValueError, lambda: self.dumps(Y())) + + prototype = CFUNCTYPE(c_int) + + for item in [ + c_char_p(), + c_wchar_p(), + c_void_p(), + pointer(c_int(42)), + dll._testfunc_p_p, + prototype(lambda: 42), + ]: + self.assertRaises(ValueError, lambda: self.dumps(item)) + +class PickleTest_1(PickleTest): + def dumps(self, item): + return pickle.dumps(item, 1) + +class PickleTest_2(PickleTest): + def dumps(self, item): + return pickle.dumps(item, 2) + +if __name__ == "__main__": + unittest.main() |