• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1from ctypes import *
2import unittest
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
13
14class PythonAPITestCase(unittest.TestCase):
15
16    def test_PyBytes_FromStringAndSize(self):
17        PyBytes_FromStringAndSize = pythonapi.PyBytes_FromStringAndSize
18
19        PyBytes_FromStringAndSize.restype = py_object
20        PyBytes_FromStringAndSize.argtypes = c_char_p, c_size_t
21
22        self.assertEqual(PyBytes_FromStringAndSize(b"abcdefghi", 3), b"abc")
23
24    @support.refcount_test
25    def test_PyString_FromString(self):
26        pythonapi.PyBytes_FromString.restype = py_object
27        pythonapi.PyBytes_FromString.argtypes = (c_char_p,)
28
29        s = b"abc"
30        refcnt = grc(s)
31        pyob = pythonapi.PyBytes_FromString(s)
32        self.assertEqual(grc(s), refcnt)
33        self.assertEqual(s, pyob)
34        del pyob
35        self.assertEqual(grc(s), refcnt)
36
37    @support.refcount_test
38    def test_PyLong_Long(self):
39        ref42 = grc(42)
40        pythonapi.PyLong_FromLong.restype = py_object
41        self.assertEqual(pythonapi.PyLong_FromLong(42), 42)
42
43        self.assertEqual(grc(42), ref42)
44
45        pythonapi.PyLong_AsLong.argtypes = (py_object,)
46        pythonapi.PyLong_AsLong.restype = c_long
47
48        res = pythonapi.PyLong_AsLong(42)
49        self.assertEqual(grc(res), ref42 + 1)
50        del res
51        self.assertEqual(grc(42), ref42)
52
53    @support.refcount_test
54    def test_PyObj_FromPtr(self):
55        s = "abc def ghi jkl"
56        ref = grc(s)
57        # id(python-object) is the address
58        pyobj = PyObj_FromPtr(id(s))
59        self.assertIs(s, pyobj)
60
61        self.assertEqual(grc(s), ref + 1)
62        del pyobj
63        self.assertEqual(grc(s), ref)
64
65    def test_PyOS_snprintf(self):
66        PyOS_snprintf = pythonapi.PyOS_snprintf
67        PyOS_snprintf.argtypes = POINTER(c_char), c_size_t, c_char_p
68
69        buf = c_buffer(256)
70        PyOS_snprintf(buf, sizeof(buf), b"Hello from %s", b"ctypes")
71        self.assertEqual(buf.value, b"Hello from ctypes")
72
73        PyOS_snprintf(buf, sizeof(buf), b"Hello from %s (%d, %d, %d)", b"ctypes", 1, 2, 3)
74        self.assertEqual(buf.value, b"Hello from ctypes (1, 2, 3)")
75
76        # not enough arguments
77        self.assertRaises(TypeError, PyOS_snprintf, buf)
78
79    def test_pyobject_repr(self):
80        self.assertEqual(repr(py_object()), "py_object(<NULL>)")
81        self.assertEqual(repr(py_object(42)), "py_object(42)")
82        self.assertEqual(repr(py_object(object)), "py_object(%r)" % object)
83
84if __name__ == "__main__":
85    unittest.main()
86