Debian Codegraph @

Lib/test/test_ctypes/test_libc.py

raw
1 import math
2 import unittest
3 from ctypes import (CDLL, CFUNCTYPE, POINTER, create_string_buffer, sizeof,
4 c_void_p, c_char, c_int, c_double, c_size_t)
5 from test.support import import_helper
6 _ctypes_test = import_helper.import_module("_ctypes_test")
7
8
9 lib = CDLL(_ctypes_test.__file__)
10
11
12 def three_way_cmp(x, y):
13 """Return -1 if x < y, 0 if x == y and 1 if x > y"""
14 return (x > y) - (x < y)
15
16
17 class LibTest(unittest.TestCase):
18 def test_sqrt(self):
19 lib.my_sqrt.argtypes = c_double,
20 lib.my_sqrt.restype = c_double
21 self.assertEqual(lib.my_sqrt(4.0), 2.0)
22 self.assertEqual(lib.my_sqrt(2.0), math.sqrt(2.0))
23
24 def test_qsort(self):
25 comparefunc = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_char))
26 lib.my_qsort.argtypes = c_void_p, c_size_t, c_size_t, comparefunc
27 lib.my_qsort.restype = None
28
29 def sort(a, b):
30 return three_way_cmp(a[0], b[0])
31
32 chars = create_string_buffer(b"spam, spam, and spam")
33 lib.my_qsort(chars, len(chars)-1, sizeof(c_char), comparefunc(sort))
34 self.assertEqual(chars.raw, b" ,,aaaadmmmnpppsss\x00")
35
36
37 if __name__ == "__main__":
38 unittest.main()