Tim Peters | d66595f | 2001-02-04 03:09:53 +0000 | [diff] [blame] | 1 | # Run the _testcapi module tests (tests for the Python/C API): by defn, |
Guido van Rossum | 361c535 | 2001-04-13 17:03:04 +0000 | [diff] [blame] | 2 | # these are all functions _testcapi exports whose name begins with 'test_'. |
Tim Peters | 9ea17ac | 2001-02-02 05:57:15 +0000 | [diff] [blame] | 3 | |
Nick Coghlan | 39f0bb5 | 2017-11-28 08:11:51 +1000 | [diff] [blame] | 4 | from collections import OrderedDict |
Victor Stinner | c9b8e9c | 2021-01-27 17:39:16 +0100 | [diff] [blame] | 5 | import importlib.machinery |
| 6 | import importlib.util |
Antoine Pitrou | 8e60577 | 2011-04-25 21:21:07 +0200 | [diff] [blame] | 7 | import os |
Antoine Pitrou | 2f828f2 | 2012-01-18 00:21:11 +0100 | [diff] [blame] | 8 | import pickle |
Jeffrey Yasskin | 8e0bdfd | 2010-05-13 18:31:05 +0000 | [diff] [blame] | 9 | import random |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 10 | import re |
Jeffrey Yasskin | 8e0bdfd | 2010-05-13 18:31:05 +0000 | [diff] [blame] | 11 | import subprocess |
Martin v. Löwis | 6ce7ed2 | 2005-03-03 12:26:35 +0000 | [diff] [blame] | 12 | import sys |
Victor Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 13 | import textwrap |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 14 | import threading |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 15 | import time |
Benjamin Peterson | 9b6df6a | 2008-10-16 23:56:29 +0000 | [diff] [blame] | 16 | import unittest |
Eddie Elizondo | 3368f3c | 2019-09-19 09:29:05 -0700 | [diff] [blame] | 17 | import weakref |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 18 | from test import support |
Larry Hastings | fcafe43 | 2013-11-23 17:35:48 -0800 | [diff] [blame] | 19 | from test.support import MISSING_C_DOCSTRINGS |
Hai Shi | 883bc63 | 2020-07-06 17:12:49 +0800 | [diff] [blame] | 20 | from test.support import import_helper |
Hai Shi | e80697d | 2020-05-28 06:10:27 +0800 | [diff] [blame] | 21 | from test.support import threading_helper |
Inada Naoki | 902356a | 2020-07-20 12:02:50 +0900 | [diff] [blame] | 22 | from test.support import warnings_helper |
xdegaye | 85f6430 | 2017-07-01 14:14:45 +0200 | [diff] [blame] | 23 | from test.support.script_helper import assert_python_failure, assert_python_ok |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 24 | try: |
Stefan Krah | fd24f9e | 2012-08-20 11:04:24 +0200 | [diff] [blame] | 25 | import _posixsubprocess |
| 26 | except ImportError: |
| 27 | _posixsubprocess = None |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 28 | |
Serhiy Storchaka | 5cfc79d | 2014-02-07 10:06:39 +0200 | [diff] [blame] | 29 | # Skip this test if the _testcapi module isn't available. |
Hai Shi | 883bc63 | 2020-07-06 17:12:49 +0800 | [diff] [blame] | 30 | _testcapi = import_helper.import_module('_testcapi') |
Tim Peters | 9ea17ac | 2001-02-02 05:57:15 +0000 | [diff] [blame] | 31 | |
Victor Stinner | 1ae035b | 2020-04-17 17:47:20 +0200 | [diff] [blame] | 32 | import _testinternalcapi |
| 33 | |
Victor Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 34 | # Were we compiled --with-pydebug or with #define Py_DEBUG? |
| 35 | Py_DEBUG = hasattr(sys, 'gettotalrefcount') |
| 36 | |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 37 | |
Victor Stinner | c9b8e9c | 2021-01-27 17:39:16 +0100 | [diff] [blame] | 38 | def decode_stderr(err): |
| 39 | return err.decode('utf-8', 'replace').replace('\r', '') |
| 40 | |
| 41 | |
Benjamin Peterson | 9b6df6a | 2008-10-16 23:56:29 +0000 | [diff] [blame] | 42 | def testfunction(self): |
| 43 | """some doc""" |
| 44 | return self |
| 45 | |
Jeroen Demeyer | aacc77f | 2019-05-29 20:31:52 +0200 | [diff] [blame] | 46 | |
Benjamin Peterson | 9b6df6a | 2008-10-16 23:56:29 +0000 | [diff] [blame] | 47 | class InstanceMethod: |
| 48 | id = _testcapi.instancemethod(id) |
| 49 | testfunction = _testcapi.instancemethod(testfunction) |
| 50 | |
| 51 | class CAPITest(unittest.TestCase): |
| 52 | |
| 53 | def test_instancemethod(self): |
| 54 | inst = InstanceMethod() |
| 55 | self.assertEqual(id(inst), inst.id()) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 56 | self.assertTrue(inst.testfunction() is inst) |
Benjamin Peterson | 9b6df6a | 2008-10-16 23:56:29 +0000 | [diff] [blame] | 57 | 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 Yasskin | 8e0bdfd | 2010-05-13 18:31:05 +0000 | [diff] [blame] | 64 | def test_no_FatalError_infinite_loop(self): |
Antoine Pitrou | 77e904e | 2013-10-08 23:04:32 +0200 | [diff] [blame] | 65 | with support.SuppressCrashReport(): |
Ezio Melotti | 25a4045 | 2013-03-05 20:26:17 +0200 | [diff] [blame] | 66 | p = subprocess.Popen([sys.executable, "-c", |
Ezio Melotti | e1857d9 | 2013-03-05 20:31:34 +0200 | [diff] [blame] | 67 | 'import _testcapi;' |
| 68 | '_testcapi.crash_no_current_thread()'], |
| 69 | stdout=subprocess.PIPE, |
| 70 | stderr=subprocess.PIPE) |
Jeffrey Yasskin | 8e0bdfd | 2010-05-13 18:31:05 +0000 | [diff] [blame] | 71 | (out, err) = p.communicate() |
| 72 | self.assertEqual(out, b'') |
| 73 | # This used to cause an infinite loop. |
Vinay Sajip | 7395404 | 2012-05-06 11:34:50 +0100 | [diff] [blame] | 74 | self.assertTrue(err.rstrip().startswith( |
Victor Stinner | 9e5d30c | 2020-03-07 00:54:20 +0100 | [diff] [blame] | 75 | b'Fatal Python error: ' |
Victor Stinner | 23ef89d | 2020-03-18 02:26:04 +0100 | [diff] [blame] | 76 | b'PyThreadState_Get: ' |
Victor Stinner | 3026cad | 2020-06-01 16:02:40 +0200 | [diff] [blame] | 77 | 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 Yasskin | 8e0bdfd | 2010-05-13 18:31:05 +0000 | [diff] [blame] | 81 | |
Antoine Pitrou | 915605c | 2011-02-24 20:53:48 +0000 | [diff] [blame] | 82 | def test_memoryview_from_NULL_pointer(self): |
| 83 | self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer) |
Benjamin Peterson | 9b6df6a | 2008-10-16 23:56:29 +0000 | [diff] [blame] | 84 | |
Martin v. Löwis | aa2efcb | 2012-04-19 14:33:43 +0200 | [diff] [blame] | 85 | 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 Krah | fd24f9e | 2012-08-20 11:04:24 +0200 | [diff] [blame] | 108 | @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. Smith | f3751ef | 2019-10-12 13:24:56 -0700 | [diff] [blame] | 115 | 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21) |
Stefan Krah | 7cacd2e | 2012-08-21 08:16:09 +0200 | [diff] [blame] | 116 | # 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. Smith | f3751ef | 2019-10-12 13:24:56 -0700 | [diff] [blame] | 123 | 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21) |
Stefan Krah | fd24f9e | 2012-08-20 11:04:24 +0200 | [diff] [blame] | 124 | |
Stefan Krah | db579d7 | 2012-08-20 14:36:47 +0200 | [diff] [blame] | 125 | @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. Smith | f3751ef | 2019-10-12 13:24:56 -0700 | [diff] [blame] | 133 | Z(),[b'1'],3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21) |
Stefan Krah | db579d7 | 2012-08-20 14:36:47 +0200 | [diff] [blame] | 134 | |
Larry Hastings | fcafe43 | 2013-11-23 17:35:48 -0800 | [diff] [blame] | 135 | @unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 136 | "Signature information for builtins requires docstrings") |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 137 | 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 Ware | 8ef887c | 2015-04-13 18:22:35 -0500 | [diff] [blame] | 142 | self.assertEqual(_testcapi.docstring_empty.__doc__, None) |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 143 | 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 Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 150 | "docstring_with_invalid_signature($module, /, boo)\n" |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 151 | "\n" |
| 152 | "This docstring has an invalid signature." |
| 153 | ) |
| 154 | self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None) |
| 155 | |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 156 | 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 Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 165 | self.assertEqual(_testcapi.docstring_with_signature.__doc__, |
| 166 | "This docstring has a valid signature.") |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 167 | self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)") |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 168 | |
Zachary Ware | 8ef887c | 2015-04-13 18:22:35 -0500 | [diff] [blame] | 169 | 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 Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 173 | self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__, |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 174 | "\nThis docstring has a valid signature and some extra newlines.") |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 175 | self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__, |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 176 | "($module, /, parameter)") |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 177 | |
Benjamin Peterson | d51374e | 2014-04-09 23:55:56 -0400 | [diff] [blame] | 178 | 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 Spytz | c7f803b | 2019-05-31 03:46:36 -0600 | [diff] [blame] | 195 | 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 Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 202 | 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 Stinner | c9b8e9c | 2021-01-27 17:39:16 +0100 | [diff] [blame] | 214 | 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 Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 224 | 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 Stinner | c9b8e9c | 2021-01-27 17:39:16 +0100 | [diff] [blame] | 229 | 'returned NULL without setting an exception') |
Victor Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 230 | |
| 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 Stinner | c9b8e9c | 2021-01-27 17:39:16 +0100 | [diff] [blame] | 242 | 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 Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 258 | 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 Stinner | c9b8e9c | 2021-01-27 17:39:16 +0100 | [diff] [blame] | 263 | '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 Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 294 | |
Serhiy Storchaka | 13e602e | 2016-05-20 22:31:14 +0300 | [diff] [blame] | 295 | def test_buildvalue_N(self): |
| 296 | _testcapi.test_buildvalue_N() |
| 297 | |
xdegaye | 85f6430 | 2017-07-01 14:14:45 +0200 | [diff] [blame] | 298 | 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 Milman | 0ccc0f6 | 2017-10-08 11:17:46 +0300 | [diff] [blame] | 330 | 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 Stinner | 18618e65 | 2018-10-25 17:28:11 +0200 | [diff] [blame] | 374 | @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 Stinner | 3ec9af7 | 2018-10-26 02:12:34 +0200 | [diff] [blame] | 388 | br'_testcapimodule\.c:[0-9]+: ' |
Victor Stinner | f1d002c | 2018-11-21 23:53:44 +0100 | [diff] [blame] | 389 | br'_Py_NegativeRefcount: Assertion failed: ' |
Victor Stinner | 3ec9af7 | 2018-10-26 02:12:34 +0200 | [diff] [blame] | 390 | br'object has negative ref count') |
Victor Stinner | 18618e65 | 2018-10-25 17:28:11 +0200 | [diff] [blame] | 391 | |
Jeroen Demeyer | 351c674 | 2019-05-10 19:21:11 +0200 | [diff] [blame] | 392 | 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 Stinner | 0127bb1 | 2019-11-21 12:54:02 +0100 | [diff] [blame] | 400 | @support.requires_resource('cpu') |
Jeroen Demeyer | 351c674 | 2019-05-10 19:21:11 +0200 | [diff] [blame] | 401 | def test_trashcan_python_class1(self): |
| 402 | self.do_test_trashcan_python_class(list) |
| 403 | |
Victor Stinner | 0127bb1 | 2019-11-21 12:54:02 +0100 | [diff] [blame] | 404 | @support.requires_resource('cpu') |
Jeroen Demeyer | 351c674 | 2019-05-10 19:21:11 +0200 | [diff] [blame] | 405 | 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 Peterson | 3940333 | 2020-09-02 11:29:06 -0500 | [diff] [blame] | 437 | 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 Shi | 88c2cfd | 2020-11-07 00:04:47 +0800 | [diff] [blame] | 441 | def test_null_type_doc(self): |
| 442 | self.assertEqual(_testcapi.NullTpDocType.__doc__, None) |
| 443 | |
Eddie Elizondo | ff023ed | 2019-09-11 05:17:13 -0400 | [diff] [blame] | 444 | 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 Elizondo | 3368f3c | 2019-09-19 09:29:05 -0700 | [diff] [blame] | 496 | 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 | |
scoder | f7c4e23 | 2020-06-06 21:35:10 +0200 | [diff] [blame] | 522 | def test_heaptype_with_buffer(self): |
| 523 | inst = _testcapi.HeapCTypeWithBuffer() |
| 524 | b = bytes(inst) |
| 525 | self.assertEqual(b, b"1234") |
| 526 | |
Eddie Elizondo | ff023ed | 2019-09-11 05:17:13 -0400 | [diff] [blame] | 527 | 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 | |
scoder | 148f329 | 2020-07-03 02:09:28 +0200 | [diff] [blame] | 561 | 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 Storchaka | e5ccc94 | 2020-03-09 20:03:38 +0200 | [diff] [blame] | 569 | 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 Stinner | 66f77ca | 2021-01-19 23:35:27 +0100 | [diff] [blame] | 583 | def check_fatal_error(self, code, expected, not_expected=()): |
Victor Stinner | e232025 | 2021-01-18 18:24:29 +0100 | [diff] [blame] | 584 | with support.SuppressCrashReport(): |
| 585 | rc, out, err = assert_python_failure('-sSI', '-c', code) |
| 586 | |
Victor Stinner | c9b8e9c | 2021-01-27 17:39:16 +0100 | [diff] [blame] | 587 | err = decode_stderr(err) |
Victor Stinner | e232025 | 2021-01-18 18:24:29 +0100 | [diff] [blame] | 588 | self.assertIn('Fatal Python error: test_fatal_error: MESSAGE\n', |
| 589 | err) |
| 590 | |
Victor Stinner | 66f77ca | 2021-01-19 23:35:27 +0100 | [diff] [blame] | 591 | match = re.search(r'^Extension modules:(.*) \(total: ([0-9]+)\)$', |
| 592 | err, re.MULTILINE) |
Victor Stinner | 250035d | 2021-01-18 20:47:13 +0100 | [diff] [blame] | 593 | if not match: |
| 594 | self.fail(f"Cannot find 'Extension modules:' in {err!r}") |
| 595 | modules = set(match.group(1).strip().split(', ')) |
Victor Stinner | 66f77ca | 2021-01-19 23:35:27 +0100 | [diff] [blame] | 596 | total = int(match.group(2)) |
| 597 | |
| 598 | for name in expected: |
Victor Stinner | 250035d | 2021-01-18 20:47:13 +0100 | [diff] [blame] | 599 | self.assertIn(name, modules) |
Victor Stinner | 66f77ca | 2021-01-19 23:35:27 +0100 | [diff] [blame] | 600 | for name in not_expected: |
| 601 | self.assertNotIn(name, modules) |
| 602 | self.assertEqual(len(modules), total) |
| 603 | |
| 604 | def test_fatal_error(self): |
Victor Stinner | db584bd | 2021-01-25 13:24:42 +0100 | [diff] [blame] | 605 | # By default, stdlib extension modules are ignored, |
| 606 | # but not test modules. |
Victor Stinner | 66f77ca | 2021-01-19 23:35:27 +0100 | [diff] [blame] | 607 | expected = ('_testcapi',) |
Victor Stinner | db584bd | 2021-01-25 13:24:42 +0100 | [diff] [blame] | 608 | not_expected = ('sys',) |
| 609 | code = 'import _testcapi, sys; _testcapi.fatal_error(b"MESSAGE")' |
Victor Stinner | 66f77ca | 2021-01-19 23:35:27 +0100 | [diff] [blame] | 610 | self.check_fatal_error(code, expected, not_expected) |
Victor Stinner | 250035d | 2021-01-18 20:47:13 +0100 | [diff] [blame] | 611 | |
Victor Stinner | db584bd | 2021-01-25 13:24:42 +0100 | [diff] [blame] | 612 | # Mark _testcapi as stdlib module, but not sys |
| 613 | expected = ('sys',) |
| 614 | not_expected = ('_testcapi',) |
| 615 | code = textwrap.dedent(''' |
| 616 | import _testcapi, sys |
Victor Stinner | 9852cb3 | 2021-01-25 23:12:50 +0100 | [diff] [blame] | 617 | sys.stdlib_module_names = frozenset({"_testcapi"}) |
Victor Stinner | db584bd | 2021-01-25 13:24:42 +0100 | [diff] [blame] | 618 | _testcapi.fatal_error(b"MESSAGE") |
| 619 | ''') |
| 620 | self.check_fatal_error(code, expected) |
| 621 | |
Miss Islington (bot) | 6ff7fef | 2021-08-23 12:30:21 -0700 | [diff] [blame^] | 622 | def test_pyobject_repr_from_null(self): |
| 623 | s = _testcapi.pyobject_repr_from_null() |
| 624 | self.assertEqual(s, '<NULL>') |
| 625 | |
| 626 | def test_pyobject_str_from_null(self): |
| 627 | s = _testcapi.pyobject_str_from_null() |
| 628 | self.assertEqual(s, '<NULL>') |
| 629 | |
| 630 | def test_pyobject_bytes_from_null(self): |
| 631 | s = _testcapi.pyobject_bytes_from_null() |
| 632 | self.assertEqual(s, b'<NULL>') |
| 633 | |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 634 | |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 635 | class TestPendingCalls(unittest.TestCase): |
| 636 | |
| 637 | def pendingcalls_submit(self, l, n): |
| 638 | def callback(): |
| 639 | #this function can be interrupted by thread switching so let's |
| 640 | #use an atomic operation |
| 641 | l.append(None) |
| 642 | |
| 643 | for i in range(n): |
| 644 | time.sleep(random.random()*0.02) #0.01 secs on average |
| 645 | #try submitting callback until successful. |
| 646 | #rely on regular interrupt to flush queue if we are |
| 647 | #unsuccessful. |
| 648 | while True: |
| 649 | if _testcapi._pending_threadfunc(callback): |
Miss Islington (bot) | 280425d | 2021-06-23 03:02:40 -0700 | [diff] [blame] | 650 | break |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 651 | |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 652 | def pendingcalls_wait(self, l, n, context = None): |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 653 | #now, stick around until l[0] has grown to 10 |
Miss Islington (bot) | 280425d | 2021-06-23 03:02:40 -0700 | [diff] [blame] | 654 | count = 0 |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 655 | while len(l) != n: |
| 656 | #this busy loop is where we expect to be interrupted to |
| 657 | #run our callbacks. Note that callbacks are only run on the |
| 658 | #main thread |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 659 | if False and support.verbose: |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 660 | print("(%i)"%(len(l),),) |
| 661 | for i in range(1000): |
| 662 | a = i*i |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 663 | if context and not context.event.is_set(): |
| 664 | continue |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 665 | count += 1 |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 666 | self.assertTrue(count < 10000, |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 667 | "timeout waiting for %i callbacks, got %i"%(n, len(l))) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 668 | if False and support.verbose: |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 669 | print("(%i)"%(len(l),)) |
| 670 | |
| 671 | def test_pendingcalls_threaded(self): |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 672 | |
| 673 | #do every callback on a separate thread |
Victor Stinner | e225beb | 2019-06-03 18:14:24 +0200 | [diff] [blame] | 674 | n = 32 #total callbacks |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 675 | threads = [] |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 676 | class foo(object):pass |
| 677 | context = foo() |
| 678 | context.l = [] |
| 679 | context.n = 2 #submits per thread |
| 680 | context.nThreads = n // context.n |
| 681 | context.nFinished = 0 |
| 682 | context.lock = threading.Lock() |
| 683 | context.event = threading.Event() |
| 684 | |
Serhiy Storchaka | 263dcd2 | 2015-04-01 13:01:14 +0300 | [diff] [blame] | 685 | threads = [threading.Thread(target=self.pendingcalls_thread, |
| 686 | args=(context,)) |
| 687 | for i in range(context.nThreads)] |
Hai Shi | e80697d | 2020-05-28 06:10:27 +0800 | [diff] [blame] | 688 | with threading_helper.start_threads(threads): |
Serhiy Storchaka | 263dcd2 | 2015-04-01 13:01:14 +0300 | [diff] [blame] | 689 | self.pendingcalls_wait(context.l, n, context) |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 690 | |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 691 | def pendingcalls_thread(self, context): |
| 692 | try: |
| 693 | self.pendingcalls_submit(context.l, context.n) |
| 694 | finally: |
| 695 | with context.lock: |
| 696 | context.nFinished += 1 |
| 697 | nFinished = context.nFinished |
| 698 | if False and support.verbose: |
| 699 | print("finished threads: ", nFinished) |
| 700 | if nFinished == context.nThreads: |
| 701 | context.event.set() |
| 702 | |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 703 | def test_pendingcalls_non_threaded(self): |
Ezio Melotti | 1392500 | 2011-03-16 11:05:33 +0200 | [diff] [blame] | 704 | #again, just using the main thread, likely they will all be dispatched at |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 705 | #once. It is ok to ask for too many, because we loop until we find a slot. |
| 706 | #the loop can be interrupted to dispatch. |
| 707 | #there are only 32 dispatch slots, so we go for twice that! |
| 708 | l = [] |
| 709 | n = 64 |
| 710 | self.pendingcalls_submit(l, n) |
| 711 | self.pendingcalls_wait(l, n) |
| 712 | |
Antoine Pitrou | 7a2572c | 2013-08-01 20:43:26 +0200 | [diff] [blame] | 713 | |
| 714 | class SubinterpreterTest(unittest.TestCase): |
| 715 | |
Antoine Pitrou | 2f828f2 | 2012-01-18 00:21:11 +0100 | [diff] [blame] | 716 | def test_subinterps(self): |
Antoine Pitrou | 2f828f2 | 2012-01-18 00:21:11 +0100 | [diff] [blame] | 717 | import builtins |
| 718 | r, w = os.pipe() |
| 719 | code = """if 1: |
| 720 | import sys, builtins, pickle |
| 721 | with open({:d}, "wb") as f: |
| 722 | pickle.dump(id(sys.modules), f) |
| 723 | pickle.dump(id(builtins), f) |
| 724 | """.format(w) |
| 725 | with open(r, "rb") as f: |
Victor Stinner | ed3b0bc | 2013-11-23 12:27:24 +0100 | [diff] [blame] | 726 | ret = support.run_in_subinterp(code) |
Antoine Pitrou | 2f828f2 | 2012-01-18 00:21:11 +0100 | [diff] [blame] | 727 | self.assertEqual(ret, 0) |
| 728 | self.assertNotEqual(pickle.load(f), id(sys.modules)) |
| 729 | self.assertNotEqual(pickle.load(f), id(builtins)) |
| 730 | |
Guido van Rossum | 9d197c7 | 2020-06-27 17:33:49 -0700 | [diff] [blame] | 731 | def test_subinterps_recent_language_features(self): |
| 732 | r, w = os.pipe() |
| 733 | code = """if 1: |
| 734 | import pickle |
| 735 | with open({:d}, "wb") as f: |
| 736 | |
| 737 | @(lambda x:x) # Py 3.9 |
| 738 | def noop(x): return x |
| 739 | |
| 740 | a = (b := f'1{{2}}3') + noop('x') # Py 3.8 (:=) / 3.6 (f'') |
| 741 | |
| 742 | async def foo(arg): return await arg # Py 3.5 |
| 743 | |
| 744 | pickle.dump(dict(a=a, b=b), f) |
| 745 | """.format(w) |
| 746 | |
| 747 | with open(r, "rb") as f: |
| 748 | ret = support.run_in_subinterp(code) |
| 749 | self.assertEqual(ret, 0) |
| 750 | self.assertEqual(pickle.load(f), {'a': '123x', 'b': '123'}) |
| 751 | |
Marcel Plch | 33e71e0 | 2019-05-22 13:51:26 +0200 | [diff] [blame] | 752 | def test_mutate_exception(self): |
| 753 | """ |
| 754 | Exceptions saved in global module state get shared between |
| 755 | individual module instances. This test checks whether or not |
| 756 | a change in one interpreter's module gets reflected into the |
| 757 | other ones. |
| 758 | """ |
| 759 | import binascii |
| 760 | |
| 761 | support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'") |
| 762 | |
| 763 | self.assertFalse(hasattr(binascii.Error, "foobar")) |
| 764 | |
Antoine Pitrou | 7a2572c | 2013-08-01 20:43:26 +0200 | [diff] [blame] | 765 | |
Ezio Melotti | 29267c8 | 2013-02-23 05:52:46 +0200 | [diff] [blame] | 766 | class TestThreadState(unittest.TestCase): |
| 767 | |
Hai Shi | e80697d | 2020-05-28 06:10:27 +0800 | [diff] [blame] | 768 | @threading_helper.reap_threads |
Ezio Melotti | 29267c8 | 2013-02-23 05:52:46 +0200 | [diff] [blame] | 769 | def test_thread_state(self): |
| 770 | # some extra thread-state tests driven via _testcapi |
| 771 | def target(): |
| 772 | idents = [] |
| 773 | |
| 774 | def callback(): |
Ezio Melotti | 35246bd | 2013-02-23 05:58:38 +0200 | [diff] [blame] | 775 | idents.append(threading.get_ident()) |
Ezio Melotti | 29267c8 | 2013-02-23 05:52:46 +0200 | [diff] [blame] | 776 | |
| 777 | _testcapi._test_thread_state(callback) |
| 778 | a = b = callback |
| 779 | time.sleep(1) |
| 780 | # Check our main thread is in the list exactly 3 times. |
Ezio Melotti | 35246bd | 2013-02-23 05:58:38 +0200 | [diff] [blame] | 781 | self.assertEqual(idents.count(threading.get_ident()), 3, |
Ezio Melotti | 29267c8 | 2013-02-23 05:52:46 +0200 | [diff] [blame] | 782 | "Couldn't find main thread correctly in the list") |
| 783 | |
| 784 | target() |
| 785 | t = threading.Thread(target=target) |
| 786 | t.start() |
| 787 | t.join() |
| 788 | |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 789 | |
Zachary Ware | c12f09e | 2013-11-11 22:47:04 -0600 | [diff] [blame] | 790 | class Test_testcapi(unittest.TestCase): |
Serhiy Storchaka | 8f7bb10 | 2018-08-06 16:50:19 +0300 | [diff] [blame] | 791 | locals().update((name, getattr(_testcapi, name)) |
| 792 | for name in dir(_testcapi) |
| 793 | if name.startswith('test_') and not name.endswith('_code')) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 794 | |
Inada Naoki | 902356a | 2020-07-20 12:02:50 +0900 | [diff] [blame] | 795 | # Suppress warning from PyUnicode_FromUnicode(). |
| 796 | @warnings_helper.ignore_warnings(category=DeprecationWarning) |
| 797 | def test_widechar(self): |
| 798 | _testcapi.test_widechar() |
| 799 | |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 800 | |
Victor Stinner | 1ae035b | 2020-04-17 17:47:20 +0200 | [diff] [blame] | 801 | class Test_testinternalcapi(unittest.TestCase): |
| 802 | locals().update((name, getattr(_testinternalcapi, name)) |
| 803 | for name in dir(_testinternalcapi) |
| 804 | if name.startswith('test_')) |
| 805 | |
| 806 | |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 807 | class PyMemDebugTests(unittest.TestCase): |
| 808 | PYTHONMALLOC = 'debug' |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 809 | # '0x04c06e0' or '04C06E0' |
Victor Stinner | 08572f6 | 2016-03-14 21:55:43 +0100 | [diff] [blame] | 810 | PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 811 | |
| 812 | def check(self, code): |
| 813 | with support.SuppressCrashReport(): |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 814 | out = assert_python_failure('-c', code, |
| 815 | PYTHONMALLOC=self.PYTHONMALLOC) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 816 | stderr = out.err |
| 817 | return stderr.decode('ascii', 'replace') |
| 818 | |
| 819 | def test_buffer_overflow(self): |
| 820 | out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()') |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 821 | regex = (r"Debug memory block at address p={ptr}: API 'm'\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 822 | r" 16 bytes originally requested\n" |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 823 | r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n" |
| 824 | r" The [0-9] pad bytes at tail={ptr} are not all FORBIDDENBYTE \(0x[0-9a-f]{{2}}\):\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 825 | r" at tail\+0: 0x78 \*\*\* OUCH\n" |
Victor Stinner | 4c409be | 2019-04-11 13:01:15 +0200 | [diff] [blame] | 826 | r" at tail\+1: 0xfd\n" |
| 827 | r" at tail\+2: 0xfd\n" |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 828 | r" .*\n" |
Victor Stinner | e8f9acf | 2019-04-12 21:54:06 +0200 | [diff] [blame] | 829 | r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?" |
Victor Stinner | 4c409be | 2019-04-11 13:01:15 +0200 | [diff] [blame] | 830 | r" Data at p: cd cd cd .*\n" |
Victor Stinner | 6453e9e | 2016-03-15 23:36:28 +0100 | [diff] [blame] | 831 | r"\n" |
Victor Stinner | f966e53 | 2018-11-13 15:14:58 +0100 | [diff] [blame] | 832 | r"Enable tracemalloc to get the memory block allocation traceback\n" |
| 833 | r"\n" |
Victor Stinner | 9e5d30c | 2020-03-07 00:54:20 +0100 | [diff] [blame] | 834 | r"Fatal Python error: _PyMem_DebugRawFree: bad trailing pad byte") |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 835 | regex = regex.format(ptr=self.PTR_REGEX) |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 836 | regex = re.compile(regex, flags=re.DOTALL) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 837 | self.assertRegex(out, regex) |
| 838 | |
| 839 | def test_api_misuse(self): |
| 840 | out = self.check('import _testcapi; _testcapi.pymem_api_misuse()') |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 841 | regex = (r"Debug memory block at address p={ptr}: API 'm'\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 842 | r" 16 bytes originally requested\n" |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 843 | r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n" |
| 844 | r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n" |
Victor Stinner | e8f9acf | 2019-04-12 21:54:06 +0200 | [diff] [blame] | 845 | r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?" |
Victor Stinner | 4c409be | 2019-04-11 13:01:15 +0200 | [diff] [blame] | 846 | r" Data at p: cd cd cd .*\n" |
Victor Stinner | 6453e9e | 2016-03-15 23:36:28 +0100 | [diff] [blame] | 847 | r"\n" |
Victor Stinner | f966e53 | 2018-11-13 15:14:58 +0100 | [diff] [blame] | 848 | r"Enable tracemalloc to get the memory block allocation traceback\n" |
| 849 | r"\n" |
Victor Stinner | 9e5d30c | 2020-03-07 00:54:20 +0100 | [diff] [blame] | 850 | r"Fatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API 'm', verified using API 'r'\n") |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 851 | regex = regex.format(ptr=self.PTR_REGEX) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 852 | self.assertRegex(out, regex) |
| 853 | |
Victor Stinner | ad52437 | 2016-03-16 12:12:53 +0100 | [diff] [blame] | 854 | def check_malloc_without_gil(self, code): |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 855 | out = self.check(code) |
Victor Stinner | 9e5d30c | 2020-03-07 00:54:20 +0100 | [diff] [blame] | 856 | expected = ('Fatal Python error: _PyMem_DebugMalloc: ' |
| 857 | 'Python memory allocator called without holding the GIL') |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 858 | self.assertIn(expected, out) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 859 | |
Victor Stinner | ad52437 | 2016-03-16 12:12:53 +0100 | [diff] [blame] | 860 | def test_pymem_malloc_without_gil(self): |
| 861 | # Debug hooks must raise an error if PyMem_Malloc() is called |
| 862 | # without holding the GIL |
| 863 | code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()' |
| 864 | self.check_malloc_without_gil(code) |
| 865 | |
| 866 | def test_pyobject_malloc_without_gil(self): |
| 867 | # Debug hooks must raise an error if PyObject_Malloc() is called |
| 868 | # without holding the GIL |
| 869 | code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()' |
| 870 | self.check_malloc_without_gil(code) |
| 871 | |
Victor Stinner | 3bf0f3a | 2019-06-07 16:22:21 +0200 | [diff] [blame] | 872 | def check_pyobject_is_freed(self, func_name): |
| 873 | code = textwrap.dedent(f''' |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 874 | import gc, os, sys, _testcapi |
| 875 | # Disable the GC to avoid crash on GC collection |
| 876 | gc.disable() |
Victor Stinner | 3bf0f3a | 2019-06-07 16:22:21 +0200 | [diff] [blame] | 877 | try: |
| 878 | _testcapi.{func_name}() |
| 879 | # Exit immediately to avoid a crash while deallocating |
| 880 | # the invalid object |
| 881 | os._exit(0) |
| 882 | except _testcapi.error: |
| 883 | os._exit(1) |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 884 | ''') |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 885 | assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC) |
| 886 | |
Victor Stinner | 6876257 | 2019-10-07 18:42:01 +0200 | [diff] [blame] | 887 | def test_pyobject_null_is_freed(self): |
| 888 | self.check_pyobject_is_freed('check_pyobject_null_is_freed') |
| 889 | |
Victor Stinner | 3bf0f3a | 2019-06-07 16:22:21 +0200 | [diff] [blame] | 890 | def test_pyobject_uninitialized_is_freed(self): |
| 891 | self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed') |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 892 | |
Victor Stinner | 3bf0f3a | 2019-06-07 16:22:21 +0200 | [diff] [blame] | 893 | def test_pyobject_forbidden_bytes_is_freed(self): |
| 894 | self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed') |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 895 | |
Victor Stinner | 3bf0f3a | 2019-06-07 16:22:21 +0200 | [diff] [blame] | 896 | def test_pyobject_freed_is_freed(self): |
| 897 | self.check_pyobject_is_freed('check_pyobject_freed_is_freed') |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 898 | |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 899 | |
| 900 | class PyMemMallocDebugTests(PyMemDebugTests): |
| 901 | PYTHONMALLOC = 'malloc_debug' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 902 | |
| 903 | |
Victor Stinner | 5d39e04 | 2017-11-29 17:20:38 +0100 | [diff] [blame] | 904 | @unittest.skipUnless(support.with_pymalloc(), 'need pymalloc') |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 905 | class PyMemPymallocDebugTests(PyMemDebugTests): |
| 906 | PYTHONMALLOC = 'pymalloc_debug' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 907 | |
| 908 | |
| 909 | @unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG') |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 910 | class PyMemDefaultTests(PyMemDebugTests): |
| 911 | # test default allocator of Python compiled in debug mode |
| 912 | PYTHONMALLOC = '' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 913 | |
| 914 | |
Petr Viktorin | e1becf4 | 2020-05-07 15:39:59 +0200 | [diff] [blame] | 915 | class Test_ModuleStateAccess(unittest.TestCase): |
| 916 | """Test access to module start (PEP 573)""" |
| 917 | |
| 918 | # The C part of the tests lives in _testmultiphase, in a module called |
| 919 | # _testmultiphase_meth_state_access. |
| 920 | # This module has multi-phase initialization, unlike _testcapi. |
| 921 | |
| 922 | def setUp(self): |
| 923 | fullname = '_testmultiphase_meth_state_access' # XXX |
| 924 | origin = importlib.util.find_spec('_testmultiphase').origin |
| 925 | loader = importlib.machinery.ExtensionFileLoader(fullname, origin) |
| 926 | spec = importlib.util.spec_from_loader(fullname, loader) |
| 927 | module = importlib.util.module_from_spec(spec) |
| 928 | loader.exec_module(module) |
| 929 | self.module = module |
| 930 | |
| 931 | def test_subclass_get_module(self): |
| 932 | """PyType_GetModule for defining_class""" |
| 933 | class StateAccessType_Subclass(self.module.StateAccessType): |
| 934 | pass |
| 935 | |
| 936 | instance = StateAccessType_Subclass() |
| 937 | self.assertIs(instance.get_defining_module(), self.module) |
| 938 | |
| 939 | def test_subclass_get_module_with_super(self): |
| 940 | class StateAccessType_Subclass(self.module.StateAccessType): |
| 941 | def get_defining_module(self): |
| 942 | return super().get_defining_module() |
| 943 | |
| 944 | instance = StateAccessType_Subclass() |
| 945 | self.assertIs(instance.get_defining_module(), self.module) |
| 946 | |
| 947 | def test_state_access(self): |
| 948 | """Checks methods defined with and without argument clinic |
| 949 | |
| 950 | This tests a no-arg method (get_count) and a method with |
| 951 | both a positional and keyword argument. |
| 952 | """ |
| 953 | |
| 954 | a = self.module.StateAccessType() |
| 955 | b = self.module.StateAccessType() |
| 956 | |
| 957 | methods = { |
| 958 | 'clinic': a.increment_count_clinic, |
| 959 | 'noclinic': a.increment_count_noclinic, |
| 960 | } |
| 961 | |
| 962 | for name, increment_count in methods.items(): |
| 963 | with self.subTest(name): |
| 964 | self.assertEqual(a.get_count(), b.get_count()) |
| 965 | self.assertEqual(a.get_count(), 0) |
| 966 | |
| 967 | increment_count() |
| 968 | self.assertEqual(a.get_count(), b.get_count()) |
| 969 | self.assertEqual(a.get_count(), 1) |
| 970 | |
| 971 | increment_count(3) |
| 972 | self.assertEqual(a.get_count(), b.get_count()) |
| 973 | self.assertEqual(a.get_count(), 4) |
| 974 | |
| 975 | increment_count(-2, twice=True) |
| 976 | self.assertEqual(a.get_count(), b.get_count()) |
| 977 | self.assertEqual(a.get_count(), 0) |
| 978 | |
| 979 | with self.assertRaises(TypeError): |
| 980 | increment_count(thrice=3) |
| 981 | |
| 982 | with self.assertRaises(TypeError): |
| 983 | increment_count(1, 2, 3) |
| 984 | |
| 985 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 986 | if __name__ == "__main__": |
Zachary Ware | c12f09e | 2013-11-11 22:47:04 -0600 | [diff] [blame] | 987 | unittest.main() |