blob: 1b18bfad553007a48d3c9dbd34b3a7e89903aba8 [file] [log] [blame]
Tim Petersd66595f2001-02-04 03:09:53 +00001# Run the _testcapi module tests (tests for the Python/C API): by defn,
Guido van Rossum361c5352001-04-13 17:03:04 +00002# these are all functions _testcapi exports whose name begins with 'test_'.
Tim Peters9ea17ac2001-02-02 05:57:15 +00003
Nick Coghlan39f0bb52017-11-28 08:11:51 +10004from collections import OrderedDict
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +01005import importlib.machinery
6import importlib.util
Antoine Pitrou8e605772011-04-25 21:21:07 +02007import os
Antoine Pitrou2f828f22012-01-18 00:21:11 +01008import pickle
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00009import random
Victor Stinnerb3adb1a2016-03-14 17:40:09 +010010import re
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000011import subprocess
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +000012import sys
Victor Stinnerefde1462015-03-21 15:04:43 +010013import textwrap
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020014import threading
Benjamin Petersona54c9092009-01-13 02:11:23 +000015import time
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000016import unittest
Eddie Elizondo3368f3c2019-09-19 09:29:05 -070017import weakref
Benjamin Petersonee8712c2008-05-20 21:35:26 +000018from test import support
Larry Hastingsfcafe432013-11-23 17:35:48 -080019from test.support import MISSING_C_DOCSTRINGS
Hai Shi883bc632020-07-06 17:12:49 +080020from test.support import import_helper
Hai Shie80697d2020-05-28 06:10:27 +080021from test.support import threading_helper
Inada Naoki902356a2020-07-20 12:02:50 +090022from test.support import warnings_helper
xdegaye85f64302017-07-01 14:14:45 +020023from test.support.script_helper import assert_python_failure, assert_python_ok
Victor Stinner45df8202010-04-28 22:31:17 +000024try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020025 import _posixsubprocess
26except ImportError:
27 _posixsubprocess = None
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020028
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +020029# Skip this test if the _testcapi module isn't available.
Hai Shi883bc632020-07-06 17:12:49 +080030_testcapi = import_helper.import_module('_testcapi')
Tim Peters9ea17ac2001-02-02 05:57:15 +000031
Victor Stinner1ae035b2020-04-17 17:47:20 +020032import _testinternalcapi
33
Victor Stinnerefde1462015-03-21 15:04:43 +010034# Were we compiled --with-pydebug or with #define Py_DEBUG?
35Py_DEBUG = hasattr(sys, 'gettotalrefcount')
36
Benjamin Petersona54c9092009-01-13 02:11:23 +000037
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +010038def decode_stderr(err):
39 return err.decode('utf-8', 'replace').replace('\r', '')
40
41
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000042def testfunction(self):
43 """some doc"""
44 return self
45
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +020046
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000047class InstanceMethod:
48 id = _testcapi.instancemethod(id)
49 testfunction = _testcapi.instancemethod(testfunction)
50
51class CAPITest(unittest.TestCase):
52
53 def test_instancemethod(self):
54 inst = InstanceMethod()
55 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000056 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000057 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
58 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
59
60 InstanceMethod.testfunction.attribute = "test"
61 self.assertEqual(testfunction.attribute, "test")
62 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
63
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000064 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020065 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020066 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020067 'import _testcapi;'
68 '_testcapi.crash_no_current_thread()'],
69 stdout=subprocess.PIPE,
70 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000071 (out, err) = p.communicate()
72 self.assertEqual(out, b'')
73 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010074 self.assertTrue(err.rstrip().startswith(
Victor Stinner9e5d30c2020-03-07 00:54:20 +010075 b'Fatal Python error: '
Victor Stinner23ef89d2020-03-18 02:26:04 +010076 b'PyThreadState_Get: '
Victor Stinner3026cad2020-06-01 16:02:40 +020077 b'the function must be called with the GIL held, '
78 b'but the GIL is released '
79 b'(the current Python thread state is NULL)'),
80 err)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000081
Antoine Pitrou915605c2011-02-24 20:53:48 +000082 def test_memoryview_from_NULL_pointer(self):
83 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000084
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020085 def test_exc_info(self):
86 raised_exception = ValueError("5")
87 new_exc = TypeError("TEST")
88 try:
89 raise raised_exception
90 except ValueError as e:
91 tb = e.__traceback__
92 orig_sys_exc_info = sys.exc_info()
93 orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
94 new_sys_exc_info = sys.exc_info()
95 new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
96 reset_sys_exc_info = sys.exc_info()
97
98 self.assertEqual(orig_exc_info[1], e)
99
100 self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
101 self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
102 self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
103 self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
104 self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
105 else:
106 self.assertTrue(False)
107
Stefan Krahfd24f9e2012-08-20 11:04:24 +0200108 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
109 def test_seq_bytes_to_charp_array(self):
110 # Issue #15732: crash in _PySequence_BytesToCharpArray()
111 class Z(object):
112 def __len__(self):
113 return 1
114 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700115 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)
Stefan Krah7cacd2e2012-08-21 08:16:09 +0200116 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
117 class Z(object):
118 def __len__(self):
119 return sys.maxsize
120 def __getitem__(self, i):
121 return b'x'
122 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700123 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)
Stefan Krahfd24f9e2012-08-20 11:04:24 +0200124
Stefan Krahdb579d72012-08-20 14:36:47 +0200125 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
126 def test_subprocess_fork_exec(self):
127 class Z(object):
128 def __len__(self):
129 return 1
130
131 # Issue #15738: crash in subprocess_fork_exec()
132 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -0700133 Z(),[b'1'],3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)
Stefan Krahdb579d72012-08-20 14:36:47 +0200134
Larry Hastingsfcafe432013-11-23 17:35:48 -0800135 @unittest.skipIf(MISSING_C_DOCSTRINGS,
136 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800137 def test_docstring_signature_parsing(self):
138
139 self.assertEqual(_testcapi.no_docstring.__doc__, None)
140 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
141
Zachary Ware8ef887c2015-04-13 18:22:35 -0500142 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800143 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
144
145 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
146 "This docstring has no signature.")
147 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
148
149 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800150 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800151 "\n"
152 "This docstring has an invalid signature."
153 )
154 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
155
Larry Hastings2623c8c2014-02-08 22:15:29 -0800156 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
157 "docstring_with_invalid_signature2($module, /, boo)\n"
158 "\n"
159 "--\n"
160 "\n"
161 "This docstring also has an invalid signature."
162 )
163 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
164
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800165 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
166 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800167 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800168
Zachary Ware8ef887c2015-04-13 18:22:35 -0500169 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
170 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
171 "($module, /, sig)")
172
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800173 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800174 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800175 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800176 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800177
Benjamin Petersond51374e2014-04-09 23:55:56 -0400178 def test_c_type_with_matrix_multiplication(self):
179 M = _testcapi.matmulType
180 m1 = M()
181 m2 = M()
182 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
183 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
184 self.assertEqual(42 @ m1, ("matmul", 42, m1))
185 o = m1
186 o @= m2
187 self.assertEqual(o, ("imatmul", m1, m2))
188 o = m1
189 o @= 42
190 self.assertEqual(o, ("imatmul", m1, 42))
191 o = 42
192 o @= m1
193 self.assertEqual(o, ("matmul", 42, m1))
194
Zackery Spytzc7f803b2019-05-31 03:46:36 -0600195 def test_c_type_with_ipow(self):
196 # When the __ipow__ method of a type was implemented in C, using the
197 # modulo param would cause segfaults.
198 o = _testcapi.ipowType()
199 self.assertEqual(o.__ipow__(1), (1, None))
200 self.assertEqual(o.__ipow__(2, 2), (2, 2))
201
Victor Stinnerefde1462015-03-21 15:04:43 +0100202 def test_return_null_without_error(self):
203 # Issue #23571: A function must not return NULL without setting an
204 # error
205 if Py_DEBUG:
206 code = textwrap.dedent("""
207 import _testcapi
208 from test import support
209
210 with support.SuppressCrashReport():
211 _testcapi.return_null_without_error()
212 """)
213 rc, out, err = assert_python_failure('-c', code)
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +0100214 err = decode_stderr(err)
215 self.assertRegex(err,
216 r'Fatal Python error: _Py_CheckFunctionResult: '
217 r'a function returned NULL without setting an exception\n'
218 r'Python runtime state: initialized\n'
219 r'SystemError: <built-in function return_null_without_error> '
220 r'returned NULL without setting an exception\n'
221 r'\n'
222 r'Current thread.*:\n'
223 r' File .*", line 6 in <module>\n')
Victor Stinnerefde1462015-03-21 15:04:43 +0100224 else:
225 with self.assertRaises(SystemError) as cm:
226 _testcapi.return_null_without_error()
227 self.assertRegex(str(cm.exception),
228 'return_null_without_error.* '
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +0100229 'returned NULL without setting an exception')
Victor Stinnerefde1462015-03-21 15:04:43 +0100230
231 def test_return_result_with_error(self):
232 # Issue #23571: A function must not return a result with an error set
233 if Py_DEBUG:
234 code = textwrap.dedent("""
235 import _testcapi
236 from test import support
237
238 with support.SuppressCrashReport():
239 _testcapi.return_result_with_error()
240 """)
241 rc, out, err = assert_python_failure('-c', code)
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +0100242 err = decode_stderr(err)
243 self.assertRegex(err,
244 r'Fatal Python error: _Py_CheckFunctionResult: '
245 r'a function returned a result with an exception set\n'
246 r'Python runtime state: initialized\n'
247 r'ValueError\n'
248 r'\n'
249 r'The above exception was the direct cause '
250 r'of the following exception:\n'
251 r'\n'
252 r'SystemError: <built-in '
253 r'function return_result_with_error> '
254 r'returned a result with an exception set\n'
255 r'\n'
256 r'Current thread.*:\n'
257 r' File .*, line 6 in <module>\n')
Victor Stinnerefde1462015-03-21 15:04:43 +0100258 else:
259 with self.assertRaises(SystemError) as cm:
260 _testcapi.return_result_with_error()
261 self.assertRegex(str(cm.exception),
262 'return_result_with_error.* '
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +0100263 'returned a result with an exception set')
264
265 def test_getitem_with_error(self):
266 # Test _Py_CheckSlotResult(). Raise an exception and then calls
267 # PyObject_GetItem(): check that the assertion catchs the bug.
268 # PyObject_GetItem() must not be called with an exception set.
269 code = textwrap.dedent("""
270 import _testcapi
271 from test import support
272
273 with support.SuppressCrashReport():
274 _testcapi.getitem_with_error({1: 2}, 1)
275 """)
276 rc, out, err = assert_python_failure('-c', code)
277 err = decode_stderr(err)
278 if 'SystemError: ' not in err:
279 self.assertRegex(err,
280 r'Fatal Python error: _Py_CheckSlotResult: '
281 r'Slot __getitem__ of type dict succeeded '
282 r'with an exception set\n'
283 r'Python runtime state: initialized\n'
284 r'ValueError: bug\n'
285 r'\n'
286 r'Current thread .* \(most recent call first\):\n'
287 r' File .*, line 6 in <module>\n'
288 r'\n'
289 r'Extension modules: _testcapi \(total: 1\)\n')
290 else:
291 # Python built with NDEBUG macro defined:
292 # test _Py_CheckFunctionResult() instead.
293 self.assertIn('returned a result with an exception set', err)
Victor Stinnerefde1462015-03-21 15:04:43 +0100294
Serhiy Storchaka13e602e2016-05-20 22:31:14 +0300295 def test_buildvalue_N(self):
296 _testcapi.test_buildvalue_N()
297
xdegaye85f64302017-07-01 14:14:45 +0200298 def test_set_nomemory(self):
299 code = """if 1:
300 import _testcapi
301
302 class C(): pass
303
304 # The first loop tests both functions and that remove_mem_hooks()
305 # can be called twice in a row. The second loop checks a call to
306 # set_nomemory() after a call to remove_mem_hooks(). The third
307 # loop checks the start and stop arguments of set_nomemory().
308 for outer_cnt in range(1, 4):
309 start = 10 * outer_cnt
310 for j in range(100):
311 if j == 0:
312 if outer_cnt != 3:
313 _testcapi.set_nomemory(start)
314 else:
315 _testcapi.set_nomemory(start, start + 1)
316 try:
317 C()
318 except MemoryError as e:
319 if outer_cnt != 3:
320 _testcapi.remove_mem_hooks()
321 print('MemoryError', outer_cnt, j)
322 _testcapi.remove_mem_hooks()
323 break
324 """
325 rc, out, err = assert_python_ok('-c', code)
326 self.assertIn(b'MemoryError 1 10', out)
327 self.assertIn(b'MemoryError 2 20', out)
328 self.assertIn(b'MemoryError 3 30', out)
329
Oren Milman0ccc0f62017-10-08 11:17:46 +0300330 def test_mapping_keys_values_items(self):
331 class Mapping1(dict):
332 def keys(self):
333 return list(super().keys())
334 def values(self):
335 return list(super().values())
336 def items(self):
337 return list(super().items())
338 class Mapping2(dict):
339 def keys(self):
340 return tuple(super().keys())
341 def values(self):
342 return tuple(super().values())
343 def items(self):
344 return tuple(super().items())
345 dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
346
347 for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
348 dict_obj, OrderedDict(dict_obj),
349 Mapping1(dict_obj), Mapping2(dict_obj)]:
350 self.assertListEqual(_testcapi.get_mapping_keys(mapping),
351 list(mapping.keys()))
352 self.assertListEqual(_testcapi.get_mapping_values(mapping),
353 list(mapping.values()))
354 self.assertListEqual(_testcapi.get_mapping_items(mapping),
355 list(mapping.items()))
356
357 def test_mapping_keys_values_items_bad_arg(self):
358 self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
359 self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
360 self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
361
362 class BadMapping:
363 def keys(self):
364 return None
365 def values(self):
366 return None
367 def items(self):
368 return None
369 bad_mapping = BadMapping()
370 self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
371 self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
372 self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
373
Victor Stinner18618e652018-10-25 17:28:11 +0200374 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
375 'need _testcapi.negative_refcount')
376 def test_negative_refcount(self):
377 # bpo-35059: Check that Py_DECREF() reports the correct filename
378 # when calling _Py_NegativeRefcount() to abort Python.
379 code = textwrap.dedent("""
380 import _testcapi
381 from test import support
382
383 with support.SuppressCrashReport():
384 _testcapi.negative_refcount()
385 """)
386 rc, out, err = assert_python_failure('-c', code)
387 self.assertRegex(err,
Victor Stinner3ec9af72018-10-26 02:12:34 +0200388 br'_testcapimodule\.c:[0-9]+: '
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100389 br'_Py_NegativeRefcount: Assertion failed: '
Victor Stinner3ec9af72018-10-26 02:12:34 +0200390 br'object has negative ref count')
Victor Stinner18618e652018-10-25 17:28:11 +0200391
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200392 def test_trashcan_subclass(self):
393 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
394 # activated when its tp_dealloc is being called by a subclass
395 from _testcapi import MyList
396 L = None
397 for i in range(1000):
398 L = MyList((L,))
399
Victor Stinner0127bb12019-11-21 12:54:02 +0100400 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200401 def test_trashcan_python_class1(self):
402 self.do_test_trashcan_python_class(list)
403
Victor Stinner0127bb12019-11-21 12:54:02 +0100404 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200405 def test_trashcan_python_class2(self):
406 from _testcapi import MyList
407 self.do_test_trashcan_python_class(MyList)
408
409 def do_test_trashcan_python_class(self, base):
410 # Check that the trashcan mechanism works properly for a Python
411 # subclass of a class using the trashcan (this specific test assumes
412 # that the base class "base" behaves like list)
413 class PyList(base):
414 # Count the number of PyList instances to verify that there is
415 # no memory leak
416 num = 0
417 def __init__(self, *args):
418 __class__.num += 1
419 super().__init__(*args)
420 def __del__(self):
421 __class__.num -= 1
422
423 for parity in (0, 1):
424 L = None
425 # We need in the order of 2**20 iterations here such that a
426 # typical 8MB stack would overflow without the trashcan.
427 for i in range(2**20):
428 L = PyList((L,))
429 L.attr = i
430 if parity:
431 # Add one additional nesting layer
432 L = (L,)
433 self.assertGreater(PyList.num, 0)
434 del L
435 self.assertEqual(PyList.num, 0)
436
Benjamin Peterson39403332020-09-02 11:29:06 -0500437 def test_heap_ctype_doc_and_text_signature(self):
438 self.assertEqual(_testcapi.HeapDocCType.__doc__, "somedoc")
439 self.assertEqual(_testcapi.HeapDocCType.__text_signature__, "(arg1, arg2)")
440
Hai Shi88c2cfd2020-11-07 00:04:47 +0800441 def test_null_type_doc(self):
442 self.assertEqual(_testcapi.NullTpDocType.__doc__, None)
443
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400444 def test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once(self):
445 class HeapGcCTypeSubclass(_testcapi.HeapGcCType):
446 def __init__(self):
447 self.value2 = 20
448 super().__init__()
449
450 subclass_instance = HeapGcCTypeSubclass()
451 type_refcnt = sys.getrefcount(HeapGcCTypeSubclass)
452
453 # Test that subclass instance was fully created
454 self.assertEqual(subclass_instance.value, 10)
455 self.assertEqual(subclass_instance.value2, 20)
456
457 # Test that the type reference count is only decremented once
458 del subclass_instance
459 self.assertEqual(type_refcnt - 1, sys.getrefcount(HeapGcCTypeSubclass))
460
461 def test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
462 class A(_testcapi.HeapGcCType):
463 def __init__(self):
464 self.value2 = 20
465 super().__init__()
466
467 class B(A):
468 def __init__(self):
469 super().__init__()
470
471 def __del__(self):
472 self.__class__ = A
473 A.refcnt_in_del = sys.getrefcount(A)
474 B.refcnt_in_del = sys.getrefcount(B)
475
476 subclass_instance = B()
477 type_refcnt = sys.getrefcount(B)
478 new_type_refcnt = sys.getrefcount(A)
479
480 # Test that subclass instance was fully created
481 self.assertEqual(subclass_instance.value, 10)
482 self.assertEqual(subclass_instance.value2, 20)
483
484 del subclass_instance
485
486 # Test that setting __class__ modified the reference counts of the types
487 self.assertEqual(type_refcnt - 1, B.refcnt_in_del)
488 self.assertEqual(new_type_refcnt + 1, A.refcnt_in_del)
489
490 # Test that the original type already has decreased its refcnt
491 self.assertEqual(type_refcnt - 1, sys.getrefcount(B))
492
493 # Test that subtype_dealloc decref the newly assigned __class__ only once
494 self.assertEqual(new_type_refcnt, sys.getrefcount(A))
495
Eddie Elizondo3368f3c2019-09-19 09:29:05 -0700496 def test_heaptype_with_dict(self):
497 inst = _testcapi.HeapCTypeWithDict()
498 inst.foo = 42
499 self.assertEqual(inst.foo, 42)
500 self.assertEqual(inst.dictobj, inst.__dict__)
501 self.assertEqual(inst.dictobj, {"foo": 42})
502
503 inst = _testcapi.HeapCTypeWithDict()
504 self.assertEqual({}, inst.__dict__)
505
506 def test_heaptype_with_negative_dict(self):
507 inst = _testcapi.HeapCTypeWithNegativeDict()
508 inst.foo = 42
509 self.assertEqual(inst.foo, 42)
510 self.assertEqual(inst.dictobj, inst.__dict__)
511 self.assertEqual(inst.dictobj, {"foo": 42})
512
513 inst = _testcapi.HeapCTypeWithNegativeDict()
514 self.assertEqual({}, inst.__dict__)
515
516 def test_heaptype_with_weakref(self):
517 inst = _testcapi.HeapCTypeWithWeakref()
518 ref = weakref.ref(inst)
519 self.assertEqual(ref(), inst)
520 self.assertEqual(inst.weakreflist, ref)
521
scoderf7c4e232020-06-06 21:35:10 +0200522 def test_heaptype_with_buffer(self):
523 inst = _testcapi.HeapCTypeWithBuffer()
524 b = bytes(inst)
525 self.assertEqual(b, b"1234")
526
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400527 def test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once(self):
528 subclass_instance = _testcapi.HeapCTypeSubclass()
529 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
530
531 # Test that subclass instance was fully created
532 self.assertEqual(subclass_instance.value, 10)
533 self.assertEqual(subclass_instance.value2, 20)
534
535 # Test that the type reference count is only decremented once
536 del subclass_instance
537 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclass))
538
539 def test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
540 subclass_instance = _testcapi.HeapCTypeSubclassWithFinalizer()
541 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer)
542 new_type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
543
544 # Test that subclass instance was fully created
545 self.assertEqual(subclass_instance.value, 10)
546 self.assertEqual(subclass_instance.value2, 20)
547
548 # The tp_finalize slot will set __class__ to HeapCTypeSubclass
549 del subclass_instance
550
551 # Test that setting __class__ modified the reference counts of the types
552 self.assertEqual(type_refcnt - 1, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
553 self.assertEqual(new_type_refcnt + 1, _testcapi.HeapCTypeSubclass.refcnt_in_del)
554
555 # Test that the original type already has decreased its refcnt
556 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer))
557
558 # Test that subtype_dealloc decref the newly assigned __class__ only once
559 self.assertEqual(new_type_refcnt, sys.getrefcount(_testcapi.HeapCTypeSubclass))
560
scoder148f3292020-07-03 02:09:28 +0200561 def test_heaptype_with_setattro(self):
562 obj = _testcapi.HeapCTypeSetattr()
563 self.assertEqual(obj.pvalue, 10)
564 obj.value = 12
565 self.assertEqual(obj.pvalue, 12)
566 del obj.value
567 self.assertEqual(obj.pvalue, 0)
568
Serhiy Storchakae5ccc942020-03-09 20:03:38 +0200569 def test_pynumber_tobase(self):
570 from _testcapi import pynumber_tobase
571 self.assertEqual(pynumber_tobase(123, 2), '0b1111011')
572 self.assertEqual(pynumber_tobase(123, 8), '0o173')
573 self.assertEqual(pynumber_tobase(123, 10), '123')
574 self.assertEqual(pynumber_tobase(123, 16), '0x7b')
575 self.assertEqual(pynumber_tobase(-123, 2), '-0b1111011')
576 self.assertEqual(pynumber_tobase(-123, 8), '-0o173')
577 self.assertEqual(pynumber_tobase(-123, 10), '-123')
578 self.assertEqual(pynumber_tobase(-123, 16), '-0x7b')
579 self.assertRaises(TypeError, pynumber_tobase, 123.0, 10)
580 self.assertRaises(TypeError, pynumber_tobase, '123', 10)
581 self.assertRaises(SystemError, pynumber_tobase, 123, 0)
582
Victor Stinner66f77ca2021-01-19 23:35:27 +0100583 def check_fatal_error(self, code, expected, not_expected=()):
Victor Stinnere2320252021-01-18 18:24:29 +0100584 with support.SuppressCrashReport():
585 rc, out, err = assert_python_failure('-sSI', '-c', code)
586
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +0100587 err = decode_stderr(err)
Victor Stinnere2320252021-01-18 18:24:29 +0100588 self.assertIn('Fatal Python error: test_fatal_error: MESSAGE\n',
589 err)
590
Victor Stinner66f77ca2021-01-19 23:35:27 +0100591 match = re.search(r'^Extension modules:(.*) \(total: ([0-9]+)\)$',
592 err, re.MULTILINE)
Victor Stinner250035d2021-01-18 20:47:13 +0100593 if not match:
594 self.fail(f"Cannot find 'Extension modules:' in {err!r}")
595 modules = set(match.group(1).strip().split(', '))
Victor Stinner66f77ca2021-01-19 23:35:27 +0100596 total = int(match.group(2))
597
598 for name in expected:
Victor Stinner250035d2021-01-18 20:47:13 +0100599 self.assertIn(name, modules)
Victor Stinner66f77ca2021-01-19 23:35:27 +0100600 for name in not_expected:
601 self.assertNotIn(name, modules)
602 self.assertEqual(len(modules), total)
603
604 def test_fatal_error(self):
Victor Stinnerdb584bd2021-01-25 13:24:42 +0100605 # By default, stdlib extension modules are ignored,
606 # but not test modules.
Victor Stinner66f77ca2021-01-19 23:35:27 +0100607 expected = ('_testcapi',)
Victor Stinnerdb584bd2021-01-25 13:24:42 +0100608 not_expected = ('sys',)
609 code = 'import _testcapi, sys; _testcapi.fatal_error(b"MESSAGE")'
Victor Stinner66f77ca2021-01-19 23:35:27 +0100610 self.check_fatal_error(code, expected, not_expected)
Victor Stinner250035d2021-01-18 20:47:13 +0100611
Victor Stinnerdb584bd2021-01-25 13:24:42 +0100612 # Mark _testcapi as stdlib module, but not sys
613 expected = ('sys',)
614 not_expected = ('_testcapi',)
615 code = textwrap.dedent('''
616 import _testcapi, sys
Victor Stinner9852cb32021-01-25 23:12:50 +0100617 sys.stdlib_module_names = frozenset({"_testcapi"})
Victor Stinnerdb584bd2021-01-25 13:24:42 +0100618 _testcapi.fatal_error(b"MESSAGE")
619 ''')
620 self.check_fatal_error(code, expected)
621
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800622
Benjamin Petersona54c9092009-01-13 02:11:23 +0000623class TestPendingCalls(unittest.TestCase):
624
625 def pendingcalls_submit(self, l, n):
626 def callback():
627 #this function can be interrupted by thread switching so let's
628 #use an atomic operation
629 l.append(None)
630
631 for i in range(n):
632 time.sleep(random.random()*0.02) #0.01 secs on average
633 #try submitting callback until successful.
634 #rely on regular interrupt to flush queue if we are
635 #unsuccessful.
636 while True:
637 if _testcapi._pending_threadfunc(callback):
638 break;
639
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000640 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000641 #now, stick around until l[0] has grown to 10
642 count = 0;
643 while len(l) != n:
644 #this busy loop is where we expect to be interrupted to
645 #run our callbacks. Note that callbacks are only run on the
646 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000647 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000648 print("(%i)"%(len(l),),)
649 for i in range(1000):
650 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000651 if context and not context.event.is_set():
652 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000653 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000654 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000655 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000656 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000657 print("(%i)"%(len(l),))
658
659 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000660
661 #do every callback on a separate thread
Victor Stinnere225beb2019-06-03 18:14:24 +0200662 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000663 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000664 class foo(object):pass
665 context = foo()
666 context.l = []
667 context.n = 2 #submits per thread
668 context.nThreads = n // context.n
669 context.nFinished = 0
670 context.lock = threading.Lock()
671 context.event = threading.Event()
672
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300673 threads = [threading.Thread(target=self.pendingcalls_thread,
674 args=(context,))
675 for i in range(context.nThreads)]
Hai Shie80697d2020-05-28 06:10:27 +0800676 with threading_helper.start_threads(threads):
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300677 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000678
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000679 def pendingcalls_thread(self, context):
680 try:
681 self.pendingcalls_submit(context.l, context.n)
682 finally:
683 with context.lock:
684 context.nFinished += 1
685 nFinished = context.nFinished
686 if False and support.verbose:
687 print("finished threads: ", nFinished)
688 if nFinished == context.nThreads:
689 context.event.set()
690
Benjamin Petersona54c9092009-01-13 02:11:23 +0000691 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200692 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000693 #once. It is ok to ask for too many, because we loop until we find a slot.
694 #the loop can be interrupted to dispatch.
695 #there are only 32 dispatch slots, so we go for twice that!
696 l = []
697 n = 64
698 self.pendingcalls_submit(l, n)
699 self.pendingcalls_wait(l, n)
700
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200701
702class SubinterpreterTest(unittest.TestCase):
703
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100704 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100705 import builtins
706 r, w = os.pipe()
707 code = """if 1:
708 import sys, builtins, pickle
709 with open({:d}, "wb") as f:
710 pickle.dump(id(sys.modules), f)
711 pickle.dump(id(builtins), f)
712 """.format(w)
713 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100714 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100715 self.assertEqual(ret, 0)
716 self.assertNotEqual(pickle.load(f), id(sys.modules))
717 self.assertNotEqual(pickle.load(f), id(builtins))
718
Guido van Rossum9d197c72020-06-27 17:33:49 -0700719 def test_subinterps_recent_language_features(self):
720 r, w = os.pipe()
721 code = """if 1:
722 import pickle
723 with open({:d}, "wb") as f:
724
725 @(lambda x:x) # Py 3.9
726 def noop(x): return x
727
728 a = (b := f'1{{2}}3') + noop('x') # Py 3.8 (:=) / 3.6 (f'')
729
730 async def foo(arg): return await arg # Py 3.5
731
732 pickle.dump(dict(a=a, b=b), f)
733 """.format(w)
734
735 with open(r, "rb") as f:
736 ret = support.run_in_subinterp(code)
737 self.assertEqual(ret, 0)
738 self.assertEqual(pickle.load(f), {'a': '123x', 'b': '123'})
739
Marcel Plch33e71e02019-05-22 13:51:26 +0200740 def test_mutate_exception(self):
741 """
742 Exceptions saved in global module state get shared between
743 individual module instances. This test checks whether or not
744 a change in one interpreter's module gets reflected into the
745 other ones.
746 """
747 import binascii
748
749 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
750
751 self.assertFalse(hasattr(binascii.Error, "foobar"))
752
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200753
Ezio Melotti29267c82013-02-23 05:52:46 +0200754class TestThreadState(unittest.TestCase):
755
Hai Shie80697d2020-05-28 06:10:27 +0800756 @threading_helper.reap_threads
Ezio Melotti29267c82013-02-23 05:52:46 +0200757 def test_thread_state(self):
758 # some extra thread-state tests driven via _testcapi
759 def target():
760 idents = []
761
762 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200763 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200764
765 _testcapi._test_thread_state(callback)
766 a = b = callback
767 time.sleep(1)
768 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200769 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200770 "Couldn't find main thread correctly in the list")
771
772 target()
773 t = threading.Thread(target=target)
774 t.start()
775 t.join()
776
Victor Stinner34be8072016-03-14 12:04:26 +0100777
Zachary Warec12f09e2013-11-11 22:47:04 -0600778class Test_testcapi(unittest.TestCase):
Serhiy Storchaka8f7bb102018-08-06 16:50:19 +0300779 locals().update((name, getattr(_testcapi, name))
780 for name in dir(_testcapi)
781 if name.startswith('test_') and not name.endswith('_code'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000782
Inada Naoki902356a2020-07-20 12:02:50 +0900783 # Suppress warning from PyUnicode_FromUnicode().
784 @warnings_helper.ignore_warnings(category=DeprecationWarning)
785 def test_widechar(self):
786 _testcapi.test_widechar()
787
Victor Stinner34be8072016-03-14 12:04:26 +0100788
Victor Stinner1ae035b2020-04-17 17:47:20 +0200789class Test_testinternalcapi(unittest.TestCase):
790 locals().update((name, getattr(_testinternalcapi, name))
791 for name in dir(_testinternalcapi)
792 if name.startswith('test_'))
793
794
Victor Stinnerc4aec362016-03-14 22:26:53 +0100795class PyMemDebugTests(unittest.TestCase):
796 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100797 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100798 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100799
800 def check(self, code):
801 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100802 out = assert_python_failure('-c', code,
803 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100804 stderr = out.err
805 return stderr.decode('ascii', 'replace')
806
807 def test_buffer_overflow(self):
808 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100809 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100810 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100811 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
812 r" The [0-9] pad bytes at tail={ptr} are not all FORBIDDENBYTE \(0x[0-9a-f]{{2}}\):\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100813 r" at tail\+0: 0x78 \*\*\* OUCH\n"
Victor Stinner4c409be2019-04-11 13:01:15 +0200814 r" at tail\+1: 0xfd\n"
815 r" at tail\+2: 0xfd\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100816 r" .*\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200817 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200818 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100819 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100820 r"Enable tracemalloc to get the memory block allocation traceback\n"
821 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100822 r"Fatal Python error: _PyMem_DebugRawFree: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100823 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100824 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100825 self.assertRegex(out, regex)
826
827 def test_api_misuse(self):
828 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100829 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100830 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100831 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
832 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200833 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200834 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100835 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100836 r"Enable tracemalloc to get the memory block allocation traceback\n"
837 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100838 r"Fatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100839 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100840 self.assertRegex(out, regex)
841
Victor Stinnerad524372016-03-16 12:12:53 +0100842 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100843 out = self.check(code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100844 expected = ('Fatal Python error: _PyMem_DebugMalloc: '
845 'Python memory allocator called without holding the GIL')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100846 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100847
Victor Stinnerad524372016-03-16 12:12:53 +0100848 def test_pymem_malloc_without_gil(self):
849 # Debug hooks must raise an error if PyMem_Malloc() is called
850 # without holding the GIL
851 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
852 self.check_malloc_without_gil(code)
853
854 def test_pyobject_malloc_without_gil(self):
855 # Debug hooks must raise an error if PyObject_Malloc() is called
856 # without holding the GIL
857 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
858 self.check_malloc_without_gil(code)
859
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200860 def check_pyobject_is_freed(self, func_name):
861 code = textwrap.dedent(f'''
Victor Stinner2b00db62019-04-11 11:33:27 +0200862 import gc, os, sys, _testcapi
863 # Disable the GC to avoid crash on GC collection
864 gc.disable()
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200865 try:
866 _testcapi.{func_name}()
867 # Exit immediately to avoid a crash while deallocating
868 # the invalid object
869 os._exit(0)
870 except _testcapi.error:
871 os._exit(1)
Victor Stinner2b00db62019-04-11 11:33:27 +0200872 ''')
Victor Stinner2b00db62019-04-11 11:33:27 +0200873 assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC)
874
Victor Stinner68762572019-10-07 18:42:01 +0200875 def test_pyobject_null_is_freed(self):
876 self.check_pyobject_is_freed('check_pyobject_null_is_freed')
877
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200878 def test_pyobject_uninitialized_is_freed(self):
879 self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200880
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200881 def test_pyobject_forbidden_bytes_is_freed(self):
882 self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200883
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200884 def test_pyobject_freed_is_freed(self):
885 self.check_pyobject_is_freed('check_pyobject_freed_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200886
Victor Stinnerc4aec362016-03-14 22:26:53 +0100887
888class PyMemMallocDebugTests(PyMemDebugTests):
889 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100890
891
Victor Stinner5d39e042017-11-29 17:20:38 +0100892@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100893class PyMemPymallocDebugTests(PyMemDebugTests):
894 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100895
896
897@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100898class PyMemDefaultTests(PyMemDebugTests):
899 # test default allocator of Python compiled in debug mode
900 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100901
902
Petr Viktorine1becf42020-05-07 15:39:59 +0200903class Test_ModuleStateAccess(unittest.TestCase):
904 """Test access to module start (PEP 573)"""
905
906 # The C part of the tests lives in _testmultiphase, in a module called
907 # _testmultiphase_meth_state_access.
908 # This module has multi-phase initialization, unlike _testcapi.
909
910 def setUp(self):
911 fullname = '_testmultiphase_meth_state_access' # XXX
912 origin = importlib.util.find_spec('_testmultiphase').origin
913 loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
914 spec = importlib.util.spec_from_loader(fullname, loader)
915 module = importlib.util.module_from_spec(spec)
916 loader.exec_module(module)
917 self.module = module
918
919 def test_subclass_get_module(self):
920 """PyType_GetModule for defining_class"""
921 class StateAccessType_Subclass(self.module.StateAccessType):
922 pass
923
924 instance = StateAccessType_Subclass()
925 self.assertIs(instance.get_defining_module(), self.module)
926
927 def test_subclass_get_module_with_super(self):
928 class StateAccessType_Subclass(self.module.StateAccessType):
929 def get_defining_module(self):
930 return super().get_defining_module()
931
932 instance = StateAccessType_Subclass()
933 self.assertIs(instance.get_defining_module(), self.module)
934
935 def test_state_access(self):
936 """Checks methods defined with and without argument clinic
937
938 This tests a no-arg method (get_count) and a method with
939 both a positional and keyword argument.
940 """
941
942 a = self.module.StateAccessType()
943 b = self.module.StateAccessType()
944
945 methods = {
946 'clinic': a.increment_count_clinic,
947 'noclinic': a.increment_count_noclinic,
948 }
949
950 for name, increment_count in methods.items():
951 with self.subTest(name):
952 self.assertEqual(a.get_count(), b.get_count())
953 self.assertEqual(a.get_count(), 0)
954
955 increment_count()
956 self.assertEqual(a.get_count(), b.get_count())
957 self.assertEqual(a.get_count(), 1)
958
959 increment_count(3)
960 self.assertEqual(a.get_count(), b.get_count())
961 self.assertEqual(a.get_count(), 4)
962
963 increment_count(-2, twice=True)
964 self.assertEqual(a.get_count(), b.get_count())
965 self.assertEqual(a.get_count(), 0)
966
967 with self.assertRaises(TypeError):
968 increment_count(thrice=3)
969
970 with self.assertRaises(TypeError):
971 increment_count(1, 2, 3)
972
973
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000974if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600975 unittest.main()