| 1 |
import ctypes |
| 2 |
import math |
| 3 |
import unittest |
| 4 |
from ctypes import (CDLL, CFUNCTYPE, POINTER, create_string_buffer, sizeof, |
| 5 |
c_void_p, c_char, c_int, c_double, c_size_t) |
| 6 |
from test.support import import_helper |
| 7 |
_ctypes_test = import_helper.import_module("_ctypes_test") |
| 8 |
|
| 9 |
|
| 10 |
lib = CDLL(_ctypes_test.__file__) |
| 11 |
|
| 12 |
|
| 13 |
def three_way_cmp(x, y): |
| 14 |
"""Return -1 if x < y, 0 if x == y and 1 if x > y""" |
| 15 |
return (x > y) - (x < y) |
| 16 |
|
| 17 |
|
| 18 |
class LibTest(unittest.TestCase): |
| 19 |
def test_sqrt(self): |
| 20 |
lib.my_sqrt.argtypes = c_double, |
| 21 |
lib.my_sqrt.restype = c_double |
| 22 |
self.assertEqual(lib.my_sqrt(4.0), 2.0) |
| 23 |
self.assertEqual(lib.my_sqrt(2.0), math.sqrt(2.0)) |
| 24 |
|
| 25 |
@unittest.skipUnless(hasattr(ctypes, "c_double_complex"), |
| 26 |
"requires C11 complex type and libffi >= 3.3.0") |
| 27 |
def test_csqrt(self): |
| 28 |
lib.my_csqrt.argtypes = ctypes.c_double_complex, |
| 29 |
lib.my_csqrt.restype = ctypes.c_double_complex |
| 30 |
self.assertEqual(lib.my_csqrt(4), 2+0j) |
| 31 |
self.assertAlmostEqual(lib.my_csqrt(-1+0.01j), |
| 32 |
0.004999937502734214+1.0000124996093955j) |
| 33 |
self.assertAlmostEqual(lib.my_csqrt(-1-0.01j), |
| 34 |
0.004999937502734214-1.0000124996093955j) |
| 35 |
|
| 36 |
lib.my_csqrtf.argtypes = ctypes.c_float_complex, |
| 37 |
lib.my_csqrtf.restype = ctypes.c_float_complex |
| 38 |
self.assertAlmostEqual(lib.my_csqrtf(-1+0.01j), |
| 39 |
0.004999937502734214+1.0000124996093955j) |
| 40 |
self.assertAlmostEqual(lib.my_csqrtf(-1-0.01j), |
| 41 |
0.004999937502734214-1.0000124996093955j) |
| 42 |
|
| 43 |
lib.my_csqrtl.argtypes = ctypes.c_longdouble_complex, |
| 44 |
lib.my_csqrtl.restype = ctypes.c_longdouble_complex |
| 45 |
self.assertAlmostEqual(lib.my_csqrtl(-1+0.01j), |
| 46 |
0.004999937502734214+1.0000124996093955j) |
| 47 |
self.assertAlmostEqual(lib.my_csqrtl(-1-0.01j), |
| 48 |
0.004999937502734214-1.0000124996093955j) |
| 49 |
|
| 50 |
def test_qsort(self): |
| 51 |
comparefunc = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_char)) |
| 52 |
lib.my_qsort.argtypes = c_void_p, c_size_t, c_size_t, comparefunc |
| 53 |
lib.my_qsort.restype = None |
| 54 |
|
| 55 |
def sort(a, b): |
| 56 |
return three_way_cmp(a[0], b[0]) |
| 57 |
|
| 58 |
chars = create_string_buffer(b"spam, spam, and spam") |
| 59 |
lib.my_qsort(chars, len(chars)-1, sizeof(c_char), comparefunc(sort)) |
| 60 |
self.assertEqual(chars.raw, b" ,,aaaadmmmnpppsss\x00") |
| 61 |
|
| 62 |
|
| 63 |
if __name__ == "__main__": |
| 64 |
unittest.main() |