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

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

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