/Lib/ctypes/test/test_random_things.py

http://unladen-swallow.googlecode.com/ · Python · 75 lines · 49 code · 13 blank · 13 comment · 4 complexity · a474060652a00805e90717efa70a2e72 MD5 · raw file

  1. from ctypes import *
  2. import unittest, sys
  3. def callback_func(arg):
  4. 42 / arg
  5. raise ValueError(arg)
  6. if sys.platform == "win32":
  7. class call_function_TestCase(unittest.TestCase):
  8. # _ctypes.call_function is deprecated and private, but used by
  9. # Gary Bishp's readline module. If we have it, we must test it as well.
  10. def test(self):
  11. from _ctypes import call_function
  12. windll.kernel32.LoadLibraryA.restype = c_void_p
  13. windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p
  14. windll.kernel32.GetProcAddress.restype = c_void_p
  15. hdll = windll.kernel32.LoadLibraryA("kernel32")
  16. funcaddr = windll.kernel32.GetProcAddress(hdll, "GetModuleHandleA")
  17. self.failUnlessEqual(call_function(funcaddr, (None,)),
  18. windll.kernel32.GetModuleHandleA(None))
  19. class CallbackTracbackTestCase(unittest.TestCase):
  20. # When an exception is raised in a ctypes callback function, the C
  21. # code prints a traceback.
  22. #
  23. # This test makes sure the exception types *and* the exception
  24. # value is printed correctly.
  25. #
  26. # Changed in 0.9.3: No longer is '(in callback)' prepended to the
  27. # error message - instead a additional frame for the C code is
  28. # created, then a full traceback printed. When SystemExit is
  29. # raised in a callback function, the interpreter exits.
  30. def capture_stderr(self, func, *args, **kw):
  31. # helper - call function 'func', and return the captured stderr
  32. import StringIO
  33. old_stderr = sys.stderr
  34. logger = sys.stderr = StringIO.StringIO()
  35. try:
  36. func(*args, **kw)
  37. finally:
  38. sys.stderr = old_stderr
  39. return logger.getvalue()
  40. def test_ValueError(self):
  41. cb = CFUNCTYPE(c_int, c_int)(callback_func)
  42. out = self.capture_stderr(cb, 42)
  43. self.failUnlessEqual(out.splitlines()[-1],
  44. "ValueError: 42")
  45. def test_IntegerDivisionError(self):
  46. cb = CFUNCTYPE(c_int, c_int)(callback_func)
  47. out = self.capture_stderr(cb, 0)
  48. self.failUnlessEqual(out.splitlines()[-1][:19],
  49. "ZeroDivisionError: ")
  50. def test_FloatDivisionError(self):
  51. cb = CFUNCTYPE(c_int, c_double)(callback_func)
  52. out = self.capture_stderr(cb, 0.0)
  53. self.failUnlessEqual(out.splitlines()[-1][:19],
  54. "ZeroDivisionError: ")
  55. def test_TypeErrorDivisionError(self):
  56. cb = CFUNCTYPE(c_int, c_char_p)(callback_func)
  57. out = self.capture_stderr(cb, "spam")
  58. self.failUnlessEqual(out.splitlines()[-1],
  59. "TypeError: "
  60. "unsupported operand type(s) for /: 'int' and 'str'")
  61. if __name__ == '__main__':
  62. unittest.main()