/Lib/ctypes/test/test_simplesubclasses.py

http://unladen-swallow.googlecode.com/ · Python · 57 lines · 39 code · 16 blank · 2 comment · 2 complexity · 9f6211068f389b8a95345309d7bfd877 MD5 · raw file

  1. import unittest
  2. from ctypes import *
  3. class MyInt(c_int):
  4. def __cmp__(self, other):
  5. if type(other) != MyInt:
  6. return -1
  7. return cmp(self.value, other.value)
  8. def __hash__(self): # Silence Py3k warning
  9. return hash(self.value)
  10. class Test(unittest.TestCase):
  11. def test_compare(self):
  12. self.failUnlessEqual(MyInt(3), MyInt(3))
  13. self.failIfEqual(MyInt(42), MyInt(43))
  14. def test_ignore_retval(self):
  15. # Test if the return value of a callback is ignored
  16. # if restype is None
  17. proto = CFUNCTYPE(None)
  18. def func():
  19. return (1, "abc", None)
  20. cb = proto(func)
  21. self.failUnlessEqual(None, cb())
  22. def test_int_callback(self):
  23. args = []
  24. def func(arg):
  25. args.append(arg)
  26. return arg
  27. cb = CFUNCTYPE(None, MyInt)(func)
  28. self.failUnlessEqual(None, cb(42))
  29. self.failUnlessEqual(type(args[-1]), MyInt)
  30. cb = CFUNCTYPE(c_int, c_int)(func)
  31. self.failUnlessEqual(42, cb(42))
  32. self.failUnlessEqual(type(args[-1]), int)
  33. def test_int_struct(self):
  34. class X(Structure):
  35. _fields_ = [("x", MyInt)]
  36. self.failUnlessEqual(X().x, MyInt())
  37. s = X()
  38. s.x = MyInt(42)
  39. self.failUnlessEqual(s.x, MyInt(42))
  40. if __name__ == "__main__":
  41. unittest.main()