3
from ctypes.test import is_resource_enabled
5
################################################################
6
# This section should be moved into ctypes\__init__.py, when it's ready.
8
from _ctypes import PyObj_FromPtr
10
################################################################
12
from sys import getrefcount as grc
13
if sys.version_info > (2, 4):
14
c_py_ssize_t = c_size_t
18
class PythonAPITestCase(unittest.TestCase):
20
def test_PyBytes_FromStringAndSize(self):
21
PyBytes_FromStringAndSize = pythonapi.PyBytes_FromStringAndSize
23
PyBytes_FromStringAndSize.restype = py_object
24
PyBytes_FromStringAndSize.argtypes = c_char_p, c_py_ssize_t
26
self.failUnlessEqual(PyBytes_FromStringAndSize(b"abcdefghi", 3), b"abc")
28
def test_PyString_FromString(self):
29
pythonapi.PyBytes_FromString.restype = py_object
30
pythonapi.PyBytes_FromString.argtypes = (c_char_p,)
34
pyob = pythonapi.PyBytes_FromString(s)
35
self.failUnlessEqual(grc(s), refcnt)
36
self.failUnlessEqual(s, pyob)
38
self.failUnlessEqual(grc(s), refcnt)
40
if is_resource_enabled("refcount"):
41
# This test is unreliable, because it is possible that code in
42
# unittest changes the refcount of the '42' integer. So, it
43
# is disabled by default.
44
def test_PyLong_Long(self):
46
pythonapi.PyLong_FromLong.restype = py_object
47
self.failUnlessEqual(pythonapi.PyLong_FromLong(42), 42)
49
self.failUnlessEqual(grc(42), ref42)
51
pythonapi.PyLong_AsLong.argtypes = (py_object,)
52
pythonapi.PyLong_AsLong.restype = c_long
54
res = pythonapi.PyLong_AsLong(42)
55
self.failUnlessEqual(grc(res), ref42 + 1)
57
self.failUnlessEqual(grc(42), ref42)
59
def test_PyObj_FromPtr(self):
62
# id(python-object) is the address
63
pyobj = PyObj_FromPtr(id(s))
64
self.failUnless(s is pyobj)
66
self.failUnlessEqual(grc(s), ref + 1)
68
self.failUnlessEqual(grc(s), ref)
70
def test_PyOS_snprintf(self):
71
PyOS_snprintf = pythonapi.PyOS_snprintf
72
PyOS_snprintf.argtypes = POINTER(c_char), c_size_t, c_char_p
75
PyOS_snprintf(buf, sizeof(buf), "Hello from %s", b"ctypes")
76
self.failUnlessEqual(buf.value, b"Hello from ctypes")
78
PyOS_snprintf(buf, sizeof(buf), "Hello from %s (%d, %d, %d)", b"ctypes", 1, 2, 3)
79
self.failUnlessEqual(buf.value, b"Hello from ctypes (1, 2, 3)")
81
# not enough arguments
82
self.failUnlessRaises(TypeError, PyOS_snprintf, buf)
84
def test_pyobject_repr(self):
85
self.failUnlessEqual(repr(py_object()), "py_object(<NULL>)")
86
self.failUnlessEqual(repr(py_object(42)), "py_object(42)")
87
self.failUnlessEqual(repr(py_object(object)), "py_object(%r)" % object)
89
if __name__ == "__main__":