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