Debian Codegraph @

Lib/test/test_capi/test_object.py

raw
1 import enum
2 import sys
3 import textwrap
4 import unittest
5 from test import support
6 from test.support import import_helper
7 from test.support import os_helper
8 from test.support import threading_helper
9 from test.support.script_helper import assert_python_failure
10
11
12 _testlimitedcapi = import_helper.import_module('_testlimitedcapi')
13 _testcapi = import_helper.import_module('_testcapi')
14 _testinternalcapi = import_helper.import_module('_testinternalcapi')
15
16
17 class Constant(enum.IntEnum):
18 Py_CONSTANT_NONE = 0
19 Py_CONSTANT_FALSE = 1
20 Py_CONSTANT_TRUE = 2
21 Py_CONSTANT_ELLIPSIS = 3
22 Py_CONSTANT_NOT_IMPLEMENTED = 4
23 Py_CONSTANT_ZERO = 5
24 Py_CONSTANT_ONE = 6
25 Py_CONSTANT_EMPTY_STR = 7
26 Py_CONSTANT_EMPTY_BYTES = 8
27 Py_CONSTANT_EMPTY_TUPLE = 9
28
29 INVALID_CONSTANT = Py_CONSTANT_EMPTY_TUPLE + 1
30
31
32 class GetConstantTest(unittest.TestCase):
33 def check_get_constant(self, get_constant):
34 self.assertIs(get_constant(Constant.Py_CONSTANT_NONE), None)
35 self.assertIs(get_constant(Constant.Py_CONSTANT_FALSE), False)
36 self.assertIs(get_constant(Constant.Py_CONSTANT_TRUE), True)
37 self.assertIs(get_constant(Constant.Py_CONSTANT_ELLIPSIS), Ellipsis)
38 self.assertIs(get_constant(Constant.Py_CONSTANT_NOT_IMPLEMENTED), NotImplemented)
39
40 for constant_id, constant_type, value in (
41 (Constant.Py_CONSTANT_ZERO, int, 0),
42 (Constant.Py_CONSTANT_ONE, int, 1),
43 (Constant.Py_CONSTANT_EMPTY_STR, str, ""),
44 (Constant.Py_CONSTANT_EMPTY_BYTES, bytes, b""),
45 (Constant.Py_CONSTANT_EMPTY_TUPLE, tuple, ()),
46 ):
47 with self.subTest(constant_id=constant_id):
48 obj = get_constant(constant_id)
49 self.assertEqual(type(obj), constant_type, obj)
50 self.assertEqual(obj, value)
51
52 with self.assertRaises(SystemError):
53 get_constant(Constant.INVALID_CONSTANT)
54
55 def test_get_constant(self):
56 self.check_get_constant(_testlimitedcapi.get_constant)
57
58 def test_get_constant_borrowed(self):
59 self.check_get_constant(_testlimitedcapi.get_constant_borrowed)
60
61
62 class PrintTest(unittest.TestCase):
63 def testPyObjectPrintObject(self):
64
65 class PrintableObject:
66
67 def __repr__(self):
68 return "spam spam spam"
69
70 def __str__(self):
71 return "egg egg egg"
72
73 obj = PrintableObject()
74 output_filename = os_helper.TESTFN
75 self.addCleanup(os_helper.unlink, output_filename)
76
77 # Test repr printing
78 _testcapi.call_pyobject_print(obj, output_filename, False)
79 with open(output_filename, 'r') as output_file:
80 self.assertEqual(output_file.read(), repr(obj))
81
82 # Test str printing
83 _testcapi.call_pyobject_print(obj, output_filename, True)
84 with open(output_filename, 'r') as output_file:
85 self.assertEqual(output_file.read(), str(obj))
86
87 def testPyObjectPrintNULL(self):
88 output_filename = os_helper.TESTFN
89 self.addCleanup(os_helper.unlink, output_filename)
90
91 # Test repr printing
92 _testcapi.pyobject_print_null(output_filename)
93 with open(output_filename, 'r') as output_file:
94 self.assertEqual(output_file.read(), '<nil>')
95
96 def testPyObjectPrintNoRefObject(self):
97 output_filename = os_helper.TESTFN
98 self.addCleanup(os_helper.unlink, output_filename)
99
100 # Test repr printing
101 correct_output = _testcapi.pyobject_print_noref_object(output_filename)
102 with open(output_filename, 'r') as output_file:
103 self.assertEqual(output_file.read(), correct_output)
104
105 def testPyObjectPrintOSError(self):
106 output_filename = os_helper.TESTFN
107 self.addCleanup(os_helper.unlink, output_filename)
108
109 open(output_filename, "w+").close()
110 with self.assertRaises(OSError):
111 _testcapi.pyobject_print_os_error(output_filename)
112
113
114 class ClearWeakRefsNoCallbacksTest(unittest.TestCase):
115 """Test PyUnstable_Object_ClearWeakRefsNoCallbacks"""
116 def test_ClearWeakRefsNoCallbacks(self):
117 """Ensure PyUnstable_Object_ClearWeakRefsNoCallbacks works"""
118 import weakref
119 import gc
120 class C:
121 pass
122 obj = C()
123 messages = []
124 ref = weakref.ref(obj, lambda: messages.append("don't add this"))
125 self.assertIs(ref(), obj)
126 self.assertFalse(messages)
127 _testcapi.pyobject_clear_weakrefs_no_callbacks(obj)
128 self.assertIsNone(ref())
129 gc.collect()
130 self.assertFalse(messages)
131
132 def test_ClearWeakRefsNoCallbacks_no_weakref_support(self):
133 """Don't fail on objects that don't support weakrefs"""
134 import weakref
135 obj = object()
136 with self.assertRaises(TypeError):
137 ref = weakref.ref(obj)
138 _testcapi.pyobject_clear_weakrefs_no_callbacks(obj)
139
140
141 @threading_helper.requires_working_threading()
142 class EnableDeferredRefcountingTest(unittest.TestCase):
143 """Test PyUnstable_Object_EnableDeferredRefcount"""
144 @support.requires_resource("cpu")
145 def test_enable_deferred_refcount(self):
146 from threading import Thread
147
148 self.assertEqual(_testcapi.pyobject_enable_deferred_refcount("not tracked"), 0)
149 foo = []
150 self.assertEqual(_testcapi.pyobject_enable_deferred_refcount(foo), int(support.Py_GIL_DISABLED))
151
152 # Make sure reference counting works on foo now
153 self.assertEqual(foo, [])
154 if support.Py_GIL_DISABLED:
155 self.assertTrue(_testinternalcapi.has_deferred_refcount(foo))
156
157 # Make sure that PyUnstable_Object_EnableDeferredRefcount is thread safe
158 def silly_func(obj):
159 self.assertIn(
160 _testcapi.pyobject_enable_deferred_refcount(obj),
161 (0, 1)
162 )
163
164 silly_list = [1, 2, 3]
165 threads = [
166 Thread(target=silly_func, args=(silly_list,)) for _ in range(4)
167 ]
168
169 with threading_helper.start_threads(threads):
170 for i in range(10):
171 silly_list.append(i)
172
173 if support.Py_GIL_DISABLED:
174 self.assertTrue(_testinternalcapi.has_deferred_refcount(silly_list))
175
176
177 class IsUniquelyReferencedTest(unittest.TestCase):
178 """Test PyUnstable_Object_IsUniquelyReferenced"""
179 def test_is_uniquely_referenced(self):
180 self.assertTrue(_testcapi.is_uniquely_referenced(object()))
181 self.assertTrue(_testcapi.is_uniquely_referenced([]))
182 # Immortals
183 self.assertFalse(_testcapi.is_uniquely_referenced("spanish inquisition"))
184 self.assertFalse(_testcapi.is_uniquely_referenced(42))
185 # CRASHES is_uniquely_referenced(NULL)
186
187 class CAPITest(unittest.TestCase):
188 def check_negative_refcount(self, code):
189 # bpo-35059: Check that Py_DECREF() reports the correct filename
190 # when calling _Py_NegativeRefcount() to abort Python.
191 code = textwrap.dedent(code)
192 rc, out, err = assert_python_failure('-c', code)
193 self.assertRegex(err,
194 br'object\.c:[0-9]+: '
195 br'_Py_NegativeRefcount: Assertion failed: '
196 br'object has negative ref count')
197
198 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
199 'need _testcapi.negative_refcount()')
200 def test_negative_refcount(self):
201 code = """
202 import _testcapi
203 from test import support
204
205 with support.SuppressCrashReport():
206 _testcapi.negative_refcount()
207 """
208 self.check_negative_refcount(code)
209
210 @unittest.skipUnless(hasattr(_testcapi, 'decref_freed_object'),
211 'need _testcapi.decref_freed_object()')
212 @support.skip_if_sanitizer("use after free on purpose",
213 address=True, memory=True, ub=True)
214 def test_decref_freed_object(self):
215 code = """
216 import _testcapi
217 from test import support
218
219 with support.SuppressCrashReport():
220 _testcapi.decref_freed_object()
221 """
222 self.check_negative_refcount(code)
223
224 @support.requires_resource('cpu')
225 def test_decref_delayed(self):
226 # gh-130519: Test that _PyObject_XDecRefDelayed() and QSBR code path
227 # handles destructors that are possibly re-entrant or trigger a GC.
228 import gc
229
230 class MyObj:
231 def __del__(self):
232 gc.collect()
233
234 for _ in range(1000):
235 obj = MyObj()
236 _testinternalcapi.incref_decref_delayed(obj)
237
238 def test_is_unique_temporary(self):
239 self.assertTrue(_testcapi.pyobject_is_unique_temporary(object()))
240 obj = object()
241 self.assertFalse(_testcapi.pyobject_is_unique_temporary(obj))
242
243 def func(x):
244 # This relies on the LOAD_FAST_BORROW optimization (gh-130704)
245 self.assertEqual(sys.getrefcount(x), 1)
246 self.assertFalse(_testcapi.pyobject_is_unique_temporary(x))
247
248 func(object())
249
250 # Test that a newly created object in C is not considered
251 # a uniquely referenced temporary, because it's not on the stack.
252 # gh-142586: do the test in a loop over a list to test for handling
253 # tagged ints on the stack.
254 for i in [0, 1, 2]:
255 self.assertFalse(_testcapi.pyobject_is_unique_temporary_new_object())
256
257 if __name__ == "__main__":
258 unittest.main()