1from ctypes import * 2import unittest, sys 3from test import support 4 5################################################################ 6# This section should be moved into ctypes\__init__.py, when it's ready. 7 8from _ctypes import PyObj_FromPtr 9 10################################################################ 11 12from sys import getrefcount as grc 13if sys.version_info > (2, 4): 14 c_py_ssize_t = c_size_t 15else: 16 c_py_ssize_t = c_int 17 18class PythonAPITestCase(unittest.TestCase): 19 20 def test_PyBytes_FromStringAndSize(self): 21 PyBytes_FromStringAndSize = pythonapi.PyBytes_FromStringAndSize 22 23 PyBytes_FromStringAndSize.restype = py_object 24 PyBytes_FromStringAndSize.argtypes = c_char_p, c_py_ssize_t 25 26 self.assertEqual(PyBytes_FromStringAndSize(b"abcdefghi", 3), b"abc") 27 28 @support.refcount_test 29 def test_PyString_FromString(self): 30 pythonapi.PyBytes_FromString.restype = py_object 31 pythonapi.PyBytes_FromString.argtypes = (c_char_p,) 32 33 s = b"abc" 34 refcnt = grc(s) 35 pyob = pythonapi.PyBytes_FromString(s) 36 self.assertEqual(grc(s), refcnt) 37 self.assertEqual(s, pyob) 38 del pyob 39 self.assertEqual(grc(s), refcnt) 40 41 @support.refcount_test 42 def test_PyLong_Long(self): 43 ref42 = grc(42) 44 pythonapi.PyLong_FromLong.restype = py_object 45 self.assertEqual(pythonapi.PyLong_FromLong(42), 42) 46 47 self.assertEqual(grc(42), ref42) 48 49 pythonapi.PyLong_AsLong.argtypes = (py_object,) 50 pythonapi.PyLong_AsLong.restype = c_long 51 52 res = pythonapi.PyLong_AsLong(42) 53 self.assertEqual(grc(res), ref42 + 1) 54 del res 55 self.assertEqual(grc(42), ref42) 56 57 @support.refcount_test 58 def test_PyObj_FromPtr(self): 59 s = "abc def ghi jkl" 60 ref = grc(s) 61 # id(python-object) is the address 62 pyobj = PyObj_FromPtr(id(s)) 63 self.assertIs(s, pyobj) 64 65 self.assertEqual(grc(s), ref + 1) 66 del pyobj 67 self.assertEqual(grc(s), ref) 68 69 def test_PyOS_snprintf(self): 70 PyOS_snprintf = pythonapi.PyOS_snprintf 71 PyOS_snprintf.argtypes = POINTER(c_char), c_size_t, c_char_p 72 73 buf = c_buffer(256) 74 PyOS_snprintf(buf, sizeof(buf), b"Hello from %s", b"ctypes") 75 self.assertEqual(buf.value, b"Hello from ctypes") 76 77 PyOS_snprintf(buf, sizeof(buf), b"Hello from %s (%d, %d, %d)", b"ctypes", 1, 2, 3) 78 self.assertEqual(buf.value, b"Hello from ctypes (1, 2, 3)") 79 80 # not enough arguments 81 self.assertRaises(TypeError, PyOS_snprintf, buf) 82 83 def test_pyobject_repr(self): 84 self.assertEqual(repr(py_object()), "py_object(<NULL>)") 85 self.assertEqual(repr(py_object(42)), "py_object(42)") 86 self.assertEqual(repr(py_object(object)), "py_object(%r)" % object) 87 88if __name__ == "__main__": 89 unittest.main() 90