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 |
Antoine Pitrou | 8e60577 | 2011-04-25 21:21:07 +0200 | [diff] [blame] | 5 | import os |
Antoine Pitrou | 2f828f2 | 2012-01-18 00:21:11 +0100 | [diff] [blame] | 6 | import pickle |
Jeffrey Yasskin | 8e0bdfd | 2010-05-13 18:31:05 +0000 | [diff] [blame] | 7 | import random |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 8 | import re |
Jeffrey Yasskin | 8e0bdfd | 2010-05-13 18:31:05 +0000 | [diff] [blame] | 9 | import subprocess |
Martin v. Löwis | 6ce7ed2 | 2005-03-03 12:26:35 +0000 | [diff] [blame] | 10 | import sys |
Victor Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 11 | import textwrap |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 12 | import threading |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 13 | import time |
Benjamin Peterson | 9b6df6a | 2008-10-16 23:56:29 +0000 | [diff] [blame] | 14 | import unittest |
Eddie Elizondo | 3368f3c | 2019-09-19 09:29:05 -0700 | [diff] [blame] | 15 | import weakref |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 16 | from test import support |
Larry Hastings | fcafe43 | 2013-11-23 17:35:48 -0800 | [diff] [blame] | 17 | from test.support import MISSING_C_DOCSTRINGS |
xdegaye | 85f6430 | 2017-07-01 14:14:45 +0200 | [diff] [blame] | 18 | from test.support.script_helper import assert_python_failure, assert_python_ok |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 19 | try: |
Stefan Krah | fd24f9e | 2012-08-20 11:04:24 +0200 | [diff] [blame] | 20 | import _posixsubprocess |
| 21 | except ImportError: |
| 22 | _posixsubprocess = None |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 23 | |
Serhiy Storchaka | 5cfc79d | 2014-02-07 10:06:39 +0200 | [diff] [blame] | 24 | # Skip this test if the _testcapi module isn't available. |
| 25 | _testcapi = support.import_module('_testcapi') |
Tim Peters | 9ea17ac | 2001-02-02 05:57:15 +0000 | [diff] [blame] | 26 | |
Victor Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 27 | # Were we compiled --with-pydebug or with #define Py_DEBUG? |
| 28 | Py_DEBUG = hasattr(sys, 'gettotalrefcount') |
| 29 | |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 30 | |
Benjamin Peterson | 9b6df6a | 2008-10-16 23:56:29 +0000 | [diff] [blame] | 31 | def testfunction(self): |
| 32 | """some doc""" |
| 33 | return self |
| 34 | |
Jeroen Demeyer | aacc77f | 2019-05-29 20:31:52 +0200 | [diff] [blame] | 35 | |
Benjamin Peterson | 9b6df6a | 2008-10-16 23:56:29 +0000 | [diff] [blame] | 36 | class InstanceMethod: |
| 37 | id = _testcapi.instancemethod(id) |
| 38 | testfunction = _testcapi.instancemethod(testfunction) |
| 39 | |
| 40 | class CAPITest(unittest.TestCase): |
| 41 | |
| 42 | def test_instancemethod(self): |
| 43 | inst = InstanceMethod() |
| 44 | self.assertEqual(id(inst), inst.id()) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 45 | self.assertTrue(inst.testfunction() is inst) |
Benjamin Peterson | 9b6df6a | 2008-10-16 23:56:29 +0000 | [diff] [blame] | 46 | self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__) |
| 47 | self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__) |
| 48 | |
| 49 | InstanceMethod.testfunction.attribute = "test" |
| 50 | self.assertEqual(testfunction.attribute, "test") |
| 51 | self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test") |
| 52 | |
Jeffrey Yasskin | 8e0bdfd | 2010-05-13 18:31:05 +0000 | [diff] [blame] | 53 | def test_no_FatalError_infinite_loop(self): |
Antoine Pitrou | 77e904e | 2013-10-08 23:04:32 +0200 | [diff] [blame] | 54 | with support.SuppressCrashReport(): |
Ezio Melotti | 25a4045 | 2013-03-05 20:26:17 +0200 | [diff] [blame] | 55 | p = subprocess.Popen([sys.executable, "-c", |
Ezio Melotti | e1857d9 | 2013-03-05 20:31:34 +0200 | [diff] [blame] | 56 | 'import _testcapi;' |
| 57 | '_testcapi.crash_no_current_thread()'], |
| 58 | stdout=subprocess.PIPE, |
| 59 | stderr=subprocess.PIPE) |
Jeffrey Yasskin | 8e0bdfd | 2010-05-13 18:31:05 +0000 | [diff] [blame] | 60 | (out, err) = p.communicate() |
| 61 | self.assertEqual(out, b'') |
| 62 | # This used to cause an infinite loop. |
Vinay Sajip | 7395404 | 2012-05-06 11:34:50 +0100 | [diff] [blame] | 63 | self.assertTrue(err.rstrip().startswith( |
Jeffrey Yasskin | 8e0bdfd | 2010-05-13 18:31:05 +0000 | [diff] [blame] | 64 | b'Fatal Python error:' |
Vinay Sajip | 7395404 | 2012-05-06 11:34:50 +0100 | [diff] [blame] | 65 | b' PyThreadState_Get: no current thread')) |
Jeffrey Yasskin | 8e0bdfd | 2010-05-13 18:31:05 +0000 | [diff] [blame] | 66 | |
Antoine Pitrou | 915605c | 2011-02-24 20:53:48 +0000 | [diff] [blame] | 67 | def test_memoryview_from_NULL_pointer(self): |
| 68 | self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer) |
Benjamin Peterson | 9b6df6a | 2008-10-16 23:56:29 +0000 | [diff] [blame] | 69 | |
Martin v. Löwis | aa2efcb | 2012-04-19 14:33:43 +0200 | [diff] [blame] | 70 | def test_exc_info(self): |
| 71 | raised_exception = ValueError("5") |
| 72 | new_exc = TypeError("TEST") |
| 73 | try: |
| 74 | raise raised_exception |
| 75 | except ValueError as e: |
| 76 | tb = e.__traceback__ |
| 77 | orig_sys_exc_info = sys.exc_info() |
| 78 | orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None) |
| 79 | new_sys_exc_info = sys.exc_info() |
| 80 | new_exc_info = _testcapi.set_exc_info(*orig_exc_info) |
| 81 | reset_sys_exc_info = sys.exc_info() |
| 82 | |
| 83 | self.assertEqual(orig_exc_info[1], e) |
| 84 | |
| 85 | self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb)) |
| 86 | self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info) |
| 87 | self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info) |
| 88 | self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None)) |
| 89 | self.assertSequenceEqual(new_sys_exc_info, new_exc_info) |
| 90 | else: |
| 91 | self.assertTrue(False) |
| 92 | |
Stefan Krah | fd24f9e | 2012-08-20 11:04:24 +0200 | [diff] [blame] | 93 | @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.') |
| 94 | def test_seq_bytes_to_charp_array(self): |
| 95 | # Issue #15732: crash in _PySequence_BytesToCharpArray() |
| 96 | class Z(object): |
| 97 | def __len__(self): |
| 98 | return 1 |
| 99 | self.assertRaises(TypeError, _posixsubprocess.fork_exec, |
Gregory P. Smith | f3751ef | 2019-10-12 13:24:56 -0700 | [diff] [blame] | 100 | 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] | 101 | # Issue #15736: overflow in _PySequence_BytesToCharpArray() |
| 102 | class Z(object): |
| 103 | def __len__(self): |
| 104 | return sys.maxsize |
| 105 | def __getitem__(self, i): |
| 106 | return b'x' |
| 107 | self.assertRaises(MemoryError, _posixsubprocess.fork_exec, |
Gregory P. Smith | f3751ef | 2019-10-12 13:24:56 -0700 | [diff] [blame] | 108 | 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] | 109 | |
Stefan Krah | db579d7 | 2012-08-20 14:36:47 +0200 | [diff] [blame] | 110 | @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.') |
| 111 | def test_subprocess_fork_exec(self): |
| 112 | class Z(object): |
| 113 | def __len__(self): |
| 114 | return 1 |
| 115 | |
| 116 | # Issue #15738: crash in subprocess_fork_exec() |
| 117 | self.assertRaises(TypeError, _posixsubprocess.fork_exec, |
Gregory P. Smith | f3751ef | 2019-10-12 13:24:56 -0700 | [diff] [blame] | 118 | 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] | 119 | |
Larry Hastings | fcafe43 | 2013-11-23 17:35:48 -0800 | [diff] [blame] | 120 | @unittest.skipIf(MISSING_C_DOCSTRINGS, |
| 121 | "Signature information for builtins requires docstrings") |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 122 | def test_docstring_signature_parsing(self): |
| 123 | |
| 124 | self.assertEqual(_testcapi.no_docstring.__doc__, None) |
| 125 | self.assertEqual(_testcapi.no_docstring.__text_signature__, None) |
| 126 | |
Zachary Ware | 8ef887c | 2015-04-13 18:22:35 -0500 | [diff] [blame] | 127 | self.assertEqual(_testcapi.docstring_empty.__doc__, None) |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 128 | self.assertEqual(_testcapi.docstring_empty.__text_signature__, None) |
| 129 | |
| 130 | self.assertEqual(_testcapi.docstring_no_signature.__doc__, |
| 131 | "This docstring has no signature.") |
| 132 | self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None) |
| 133 | |
| 134 | self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__, |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 135 | "docstring_with_invalid_signature($module, /, boo)\n" |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 136 | "\n" |
| 137 | "This docstring has an invalid signature." |
| 138 | ) |
| 139 | self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None) |
| 140 | |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 141 | self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__, |
| 142 | "docstring_with_invalid_signature2($module, /, boo)\n" |
| 143 | "\n" |
| 144 | "--\n" |
| 145 | "\n" |
| 146 | "This docstring also has an invalid signature." |
| 147 | ) |
| 148 | self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None) |
| 149 | |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 150 | self.assertEqual(_testcapi.docstring_with_signature.__doc__, |
| 151 | "This docstring has a valid signature.") |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 152 | self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)") |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 153 | |
Zachary Ware | 8ef887c | 2015-04-13 18:22:35 -0500 | [diff] [blame] | 154 | self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None) |
| 155 | self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__, |
| 156 | "($module, /, sig)") |
| 157 | |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 158 | self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__, |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 159 | "\nThis docstring has a valid signature and some extra newlines.") |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 160 | self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__, |
Larry Hastings | 2623c8c | 2014-02-08 22:15:29 -0800 | [diff] [blame] | 161 | "($module, /, parameter)") |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 162 | |
Benjamin Peterson | d51374e | 2014-04-09 23:55:56 -0400 | [diff] [blame] | 163 | def test_c_type_with_matrix_multiplication(self): |
| 164 | M = _testcapi.matmulType |
| 165 | m1 = M() |
| 166 | m2 = M() |
| 167 | self.assertEqual(m1 @ m2, ("matmul", m1, m2)) |
| 168 | self.assertEqual(m1 @ 42, ("matmul", m1, 42)) |
| 169 | self.assertEqual(42 @ m1, ("matmul", 42, m1)) |
| 170 | o = m1 |
| 171 | o @= m2 |
| 172 | self.assertEqual(o, ("imatmul", m1, m2)) |
| 173 | o = m1 |
| 174 | o @= 42 |
| 175 | self.assertEqual(o, ("imatmul", m1, 42)) |
| 176 | o = 42 |
| 177 | o @= m1 |
| 178 | self.assertEqual(o, ("matmul", 42, m1)) |
| 179 | |
Zackery Spytz | c7f803b | 2019-05-31 03:46:36 -0600 | [diff] [blame] | 180 | def test_c_type_with_ipow(self): |
| 181 | # When the __ipow__ method of a type was implemented in C, using the |
| 182 | # modulo param would cause segfaults. |
| 183 | o = _testcapi.ipowType() |
| 184 | self.assertEqual(o.__ipow__(1), (1, None)) |
| 185 | self.assertEqual(o.__ipow__(2, 2), (2, 2)) |
| 186 | |
Victor Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 187 | def test_return_null_without_error(self): |
| 188 | # Issue #23571: A function must not return NULL without setting an |
| 189 | # error |
| 190 | if Py_DEBUG: |
| 191 | code = textwrap.dedent(""" |
| 192 | import _testcapi |
| 193 | from test import support |
| 194 | |
| 195 | with support.SuppressCrashReport(): |
| 196 | _testcapi.return_null_without_error() |
| 197 | """) |
| 198 | rc, out, err = assert_python_failure('-c', code) |
Victor Stinner | 381a9bc | 2015-03-24 14:01:32 +0100 | [diff] [blame] | 199 | self.assertRegex(err.replace(b'\r', b''), |
Victor Stinner | 944fbcc | 2015-03-24 16:28:52 +0100 | [diff] [blame] | 200 | br'Fatal Python error: a function returned NULL ' |
| 201 | br'without setting an error\n' |
Victor Stinner | 1ce16fb | 2019-09-18 01:35:33 +0200 | [diff] [blame] | 202 | br'Python runtime state: initialized\n' |
Victor Stinner | 381a9bc | 2015-03-24 14:01:32 +0100 | [diff] [blame] | 203 | br'SystemError: <built-in function ' |
| 204 | br'return_null_without_error> returned NULL ' |
| 205 | br'without setting an error\n' |
| 206 | br'\n' |
| 207 | br'Current thread.*:\n' |
| 208 | br' File .*", line 6 in <module>') |
Victor Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 209 | else: |
| 210 | with self.assertRaises(SystemError) as cm: |
| 211 | _testcapi.return_null_without_error() |
| 212 | self.assertRegex(str(cm.exception), |
| 213 | 'return_null_without_error.* ' |
| 214 | 'returned NULL without setting an error') |
| 215 | |
| 216 | def test_return_result_with_error(self): |
| 217 | # Issue #23571: A function must not return a result with an error set |
| 218 | if Py_DEBUG: |
| 219 | code = textwrap.dedent(""" |
| 220 | import _testcapi |
| 221 | from test import support |
| 222 | |
| 223 | with support.SuppressCrashReport(): |
| 224 | _testcapi.return_result_with_error() |
| 225 | """) |
| 226 | rc, out, err = assert_python_failure('-c', code) |
Victor Stinner | 381a9bc | 2015-03-24 14:01:32 +0100 | [diff] [blame] | 227 | self.assertRegex(err.replace(b'\r', b''), |
Victor Stinner | 944fbcc | 2015-03-24 16:28:52 +0100 | [diff] [blame] | 228 | br'Fatal Python error: a function returned a ' |
| 229 | br'result with an error set\n' |
Victor Stinner | 1ce16fb | 2019-09-18 01:35:33 +0200 | [diff] [blame] | 230 | br'Python runtime state: initialized\n' |
Victor Stinner | 381a9bc | 2015-03-24 14:01:32 +0100 | [diff] [blame] | 231 | br'ValueError\n' |
| 232 | br'\n' |
Serhiy Storchaka | 467ab19 | 2016-10-21 17:09:17 +0300 | [diff] [blame] | 233 | br'The above exception was the direct cause ' |
| 234 | br'of the following exception:\n' |
Victor Stinner | 381a9bc | 2015-03-24 14:01:32 +0100 | [diff] [blame] | 235 | br'\n' |
| 236 | br'SystemError: <built-in ' |
| 237 | br'function return_result_with_error> ' |
| 238 | br'returned a result with an error set\n' |
| 239 | br'\n' |
| 240 | br'Current thread.*:\n' |
| 241 | br' File .*, line 6 in <module>') |
Victor Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 242 | else: |
| 243 | with self.assertRaises(SystemError) as cm: |
| 244 | _testcapi.return_result_with_error() |
| 245 | self.assertRegex(str(cm.exception), |
| 246 | 'return_result_with_error.* ' |
| 247 | 'returned a result with an error set') |
| 248 | |
Serhiy Storchaka | 13e602e | 2016-05-20 22:31:14 +0300 | [diff] [blame] | 249 | def test_buildvalue_N(self): |
| 250 | _testcapi.test_buildvalue_N() |
| 251 | |
xdegaye | 85f6430 | 2017-07-01 14:14:45 +0200 | [diff] [blame] | 252 | def test_set_nomemory(self): |
| 253 | code = """if 1: |
| 254 | import _testcapi |
| 255 | |
| 256 | class C(): pass |
| 257 | |
| 258 | # The first loop tests both functions and that remove_mem_hooks() |
| 259 | # can be called twice in a row. The second loop checks a call to |
| 260 | # set_nomemory() after a call to remove_mem_hooks(). The third |
| 261 | # loop checks the start and stop arguments of set_nomemory(). |
| 262 | for outer_cnt in range(1, 4): |
| 263 | start = 10 * outer_cnt |
| 264 | for j in range(100): |
| 265 | if j == 0: |
| 266 | if outer_cnt != 3: |
| 267 | _testcapi.set_nomemory(start) |
| 268 | else: |
| 269 | _testcapi.set_nomemory(start, start + 1) |
| 270 | try: |
| 271 | C() |
| 272 | except MemoryError as e: |
| 273 | if outer_cnt != 3: |
| 274 | _testcapi.remove_mem_hooks() |
| 275 | print('MemoryError', outer_cnt, j) |
| 276 | _testcapi.remove_mem_hooks() |
| 277 | break |
| 278 | """ |
| 279 | rc, out, err = assert_python_ok('-c', code) |
| 280 | self.assertIn(b'MemoryError 1 10', out) |
| 281 | self.assertIn(b'MemoryError 2 20', out) |
| 282 | self.assertIn(b'MemoryError 3 30', out) |
| 283 | |
Oren Milman | 0ccc0f6 | 2017-10-08 11:17:46 +0300 | [diff] [blame] | 284 | def test_mapping_keys_values_items(self): |
| 285 | class Mapping1(dict): |
| 286 | def keys(self): |
| 287 | return list(super().keys()) |
| 288 | def values(self): |
| 289 | return list(super().values()) |
| 290 | def items(self): |
| 291 | return list(super().items()) |
| 292 | class Mapping2(dict): |
| 293 | def keys(self): |
| 294 | return tuple(super().keys()) |
| 295 | def values(self): |
| 296 | return tuple(super().values()) |
| 297 | def items(self): |
| 298 | return tuple(super().items()) |
| 299 | dict_obj = {'foo': 1, 'bar': 2, 'spam': 3} |
| 300 | |
| 301 | for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(), |
| 302 | dict_obj, OrderedDict(dict_obj), |
| 303 | Mapping1(dict_obj), Mapping2(dict_obj)]: |
| 304 | self.assertListEqual(_testcapi.get_mapping_keys(mapping), |
| 305 | list(mapping.keys())) |
| 306 | self.assertListEqual(_testcapi.get_mapping_values(mapping), |
| 307 | list(mapping.values())) |
| 308 | self.assertListEqual(_testcapi.get_mapping_items(mapping), |
| 309 | list(mapping.items())) |
| 310 | |
| 311 | def test_mapping_keys_values_items_bad_arg(self): |
| 312 | self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None) |
| 313 | self.assertRaises(AttributeError, _testcapi.get_mapping_values, None) |
| 314 | self.assertRaises(AttributeError, _testcapi.get_mapping_items, None) |
| 315 | |
| 316 | class BadMapping: |
| 317 | def keys(self): |
| 318 | return None |
| 319 | def values(self): |
| 320 | return None |
| 321 | def items(self): |
| 322 | return None |
| 323 | bad_mapping = BadMapping() |
| 324 | self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping) |
| 325 | self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping) |
| 326 | self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping) |
| 327 | |
Victor Stinner | 18618e65 | 2018-10-25 17:28:11 +0200 | [diff] [blame] | 328 | @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'), |
| 329 | 'need _testcapi.negative_refcount') |
| 330 | def test_negative_refcount(self): |
| 331 | # bpo-35059: Check that Py_DECREF() reports the correct filename |
| 332 | # when calling _Py_NegativeRefcount() to abort Python. |
| 333 | code = textwrap.dedent(""" |
| 334 | import _testcapi |
| 335 | from test import support |
| 336 | |
| 337 | with support.SuppressCrashReport(): |
| 338 | _testcapi.negative_refcount() |
| 339 | """) |
| 340 | rc, out, err = assert_python_failure('-c', code) |
| 341 | self.assertRegex(err, |
Victor Stinner | 3ec9af7 | 2018-10-26 02:12:34 +0200 | [diff] [blame] | 342 | br'_testcapimodule\.c:[0-9]+: ' |
Victor Stinner | f1d002c | 2018-11-21 23:53:44 +0100 | [diff] [blame] | 343 | br'_Py_NegativeRefcount: Assertion failed: ' |
Victor Stinner | 3ec9af7 | 2018-10-26 02:12:34 +0200 | [diff] [blame] | 344 | br'object has negative ref count') |
Victor Stinner | 18618e65 | 2018-10-25 17:28:11 +0200 | [diff] [blame] | 345 | |
Jeroen Demeyer | 351c674 | 2019-05-10 19:21:11 +0200 | [diff] [blame] | 346 | def test_trashcan_subclass(self): |
| 347 | # bpo-35983: Check that the trashcan mechanism for "list" is NOT |
| 348 | # activated when its tp_dealloc is being called by a subclass |
| 349 | from _testcapi import MyList |
| 350 | L = None |
| 351 | for i in range(1000): |
| 352 | L = MyList((L,)) |
| 353 | |
| 354 | def test_trashcan_python_class1(self): |
| 355 | self.do_test_trashcan_python_class(list) |
| 356 | |
| 357 | def test_trashcan_python_class2(self): |
| 358 | from _testcapi import MyList |
| 359 | self.do_test_trashcan_python_class(MyList) |
| 360 | |
| 361 | def do_test_trashcan_python_class(self, base): |
| 362 | # Check that the trashcan mechanism works properly for a Python |
| 363 | # subclass of a class using the trashcan (this specific test assumes |
| 364 | # that the base class "base" behaves like list) |
| 365 | class PyList(base): |
| 366 | # Count the number of PyList instances to verify that there is |
| 367 | # no memory leak |
| 368 | num = 0 |
| 369 | def __init__(self, *args): |
| 370 | __class__.num += 1 |
| 371 | super().__init__(*args) |
| 372 | def __del__(self): |
| 373 | __class__.num -= 1 |
| 374 | |
| 375 | for parity in (0, 1): |
| 376 | L = None |
| 377 | # We need in the order of 2**20 iterations here such that a |
| 378 | # typical 8MB stack would overflow without the trashcan. |
| 379 | for i in range(2**20): |
| 380 | L = PyList((L,)) |
| 381 | L.attr = i |
| 382 | if parity: |
| 383 | # Add one additional nesting layer |
| 384 | L = (L,) |
| 385 | self.assertGreater(PyList.num, 0) |
| 386 | del L |
| 387 | self.assertEqual(PyList.num, 0) |
| 388 | |
Eddie Elizondo | ff023ed | 2019-09-11 05:17:13 -0400 | [diff] [blame] | 389 | def test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once(self): |
| 390 | class HeapGcCTypeSubclass(_testcapi.HeapGcCType): |
| 391 | def __init__(self): |
| 392 | self.value2 = 20 |
| 393 | super().__init__() |
| 394 | |
| 395 | subclass_instance = HeapGcCTypeSubclass() |
| 396 | type_refcnt = sys.getrefcount(HeapGcCTypeSubclass) |
| 397 | |
| 398 | # Test that subclass instance was fully created |
| 399 | self.assertEqual(subclass_instance.value, 10) |
| 400 | self.assertEqual(subclass_instance.value2, 20) |
| 401 | |
| 402 | # Test that the type reference count is only decremented once |
| 403 | del subclass_instance |
| 404 | self.assertEqual(type_refcnt - 1, sys.getrefcount(HeapGcCTypeSubclass)) |
| 405 | |
| 406 | def test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once(self): |
| 407 | class A(_testcapi.HeapGcCType): |
| 408 | def __init__(self): |
| 409 | self.value2 = 20 |
| 410 | super().__init__() |
| 411 | |
| 412 | class B(A): |
| 413 | def __init__(self): |
| 414 | super().__init__() |
| 415 | |
| 416 | def __del__(self): |
| 417 | self.__class__ = A |
| 418 | A.refcnt_in_del = sys.getrefcount(A) |
| 419 | B.refcnt_in_del = sys.getrefcount(B) |
| 420 | |
| 421 | subclass_instance = B() |
| 422 | type_refcnt = sys.getrefcount(B) |
| 423 | new_type_refcnt = sys.getrefcount(A) |
| 424 | |
| 425 | # Test that subclass instance was fully created |
| 426 | self.assertEqual(subclass_instance.value, 10) |
| 427 | self.assertEqual(subclass_instance.value2, 20) |
| 428 | |
| 429 | del subclass_instance |
| 430 | |
| 431 | # Test that setting __class__ modified the reference counts of the types |
| 432 | self.assertEqual(type_refcnt - 1, B.refcnt_in_del) |
| 433 | self.assertEqual(new_type_refcnt + 1, A.refcnt_in_del) |
| 434 | |
| 435 | # Test that the original type already has decreased its refcnt |
| 436 | self.assertEqual(type_refcnt - 1, sys.getrefcount(B)) |
| 437 | |
| 438 | # Test that subtype_dealloc decref the newly assigned __class__ only once |
| 439 | self.assertEqual(new_type_refcnt, sys.getrefcount(A)) |
| 440 | |
Eddie Elizondo | 3368f3c | 2019-09-19 09:29:05 -0700 | [diff] [blame] | 441 | def test_heaptype_with_dict(self): |
| 442 | inst = _testcapi.HeapCTypeWithDict() |
| 443 | inst.foo = 42 |
| 444 | self.assertEqual(inst.foo, 42) |
| 445 | self.assertEqual(inst.dictobj, inst.__dict__) |
| 446 | self.assertEqual(inst.dictobj, {"foo": 42}) |
| 447 | |
| 448 | inst = _testcapi.HeapCTypeWithDict() |
| 449 | self.assertEqual({}, inst.__dict__) |
| 450 | |
| 451 | def test_heaptype_with_negative_dict(self): |
| 452 | inst = _testcapi.HeapCTypeWithNegativeDict() |
| 453 | inst.foo = 42 |
| 454 | self.assertEqual(inst.foo, 42) |
| 455 | self.assertEqual(inst.dictobj, inst.__dict__) |
| 456 | self.assertEqual(inst.dictobj, {"foo": 42}) |
| 457 | |
| 458 | inst = _testcapi.HeapCTypeWithNegativeDict() |
| 459 | self.assertEqual({}, inst.__dict__) |
| 460 | |
| 461 | def test_heaptype_with_weakref(self): |
| 462 | inst = _testcapi.HeapCTypeWithWeakref() |
| 463 | ref = weakref.ref(inst) |
| 464 | self.assertEqual(ref(), inst) |
| 465 | self.assertEqual(inst.weakreflist, ref) |
| 466 | |
Eddie Elizondo | ff023ed | 2019-09-11 05:17:13 -0400 | [diff] [blame] | 467 | def test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once(self): |
| 468 | subclass_instance = _testcapi.HeapCTypeSubclass() |
| 469 | type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass) |
| 470 | |
| 471 | # Test that subclass instance was fully created |
| 472 | self.assertEqual(subclass_instance.value, 10) |
| 473 | self.assertEqual(subclass_instance.value2, 20) |
| 474 | |
| 475 | # Test that the type reference count is only decremented once |
| 476 | del subclass_instance |
| 477 | self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclass)) |
| 478 | |
| 479 | def test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once(self): |
| 480 | subclass_instance = _testcapi.HeapCTypeSubclassWithFinalizer() |
| 481 | type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer) |
| 482 | new_type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass) |
| 483 | |
| 484 | # Test that subclass instance was fully created |
| 485 | self.assertEqual(subclass_instance.value, 10) |
| 486 | self.assertEqual(subclass_instance.value2, 20) |
| 487 | |
| 488 | # The tp_finalize slot will set __class__ to HeapCTypeSubclass |
| 489 | del subclass_instance |
| 490 | |
| 491 | # Test that setting __class__ modified the reference counts of the types |
| 492 | self.assertEqual(type_refcnt - 1, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del) |
| 493 | self.assertEqual(new_type_refcnt + 1, _testcapi.HeapCTypeSubclass.refcnt_in_del) |
| 494 | |
| 495 | # Test that the original type already has decreased its refcnt |
| 496 | self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer)) |
| 497 | |
| 498 | # Test that subtype_dealloc decref the newly assigned __class__ only once |
| 499 | self.assertEqual(new_type_refcnt, sys.getrefcount(_testcapi.HeapCTypeSubclass)) |
| 500 | |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 501 | |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 502 | class TestPendingCalls(unittest.TestCase): |
| 503 | |
| 504 | def pendingcalls_submit(self, l, n): |
| 505 | def callback(): |
| 506 | #this function can be interrupted by thread switching so let's |
| 507 | #use an atomic operation |
| 508 | l.append(None) |
| 509 | |
| 510 | for i in range(n): |
| 511 | time.sleep(random.random()*0.02) #0.01 secs on average |
| 512 | #try submitting callback until successful. |
| 513 | #rely on regular interrupt to flush queue if we are |
| 514 | #unsuccessful. |
| 515 | while True: |
| 516 | if _testcapi._pending_threadfunc(callback): |
| 517 | break; |
| 518 | |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 519 | def pendingcalls_wait(self, l, n, context = None): |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 520 | #now, stick around until l[0] has grown to 10 |
| 521 | count = 0; |
| 522 | while len(l) != n: |
| 523 | #this busy loop is where we expect to be interrupted to |
| 524 | #run our callbacks. Note that callbacks are only run on the |
| 525 | #main thread |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 526 | if False and support.verbose: |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 527 | print("(%i)"%(len(l),),) |
| 528 | for i in range(1000): |
| 529 | a = i*i |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 530 | if context and not context.event.is_set(): |
| 531 | continue |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 532 | count += 1 |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 533 | self.assertTrue(count < 10000, |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 534 | "timeout waiting for %i callbacks, got %i"%(n, len(l))) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 535 | if False and support.verbose: |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 536 | print("(%i)"%(len(l),)) |
| 537 | |
| 538 | def test_pendingcalls_threaded(self): |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 539 | |
| 540 | #do every callback on a separate thread |
Victor Stinner | e225beb | 2019-06-03 18:14:24 +0200 | [diff] [blame] | 541 | n = 32 #total callbacks |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 542 | threads = [] |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 543 | class foo(object):pass |
| 544 | context = foo() |
| 545 | context.l = [] |
| 546 | context.n = 2 #submits per thread |
| 547 | context.nThreads = n // context.n |
| 548 | context.nFinished = 0 |
| 549 | context.lock = threading.Lock() |
| 550 | context.event = threading.Event() |
| 551 | |
Serhiy Storchaka | 263dcd2 | 2015-04-01 13:01:14 +0300 | [diff] [blame] | 552 | threads = [threading.Thread(target=self.pendingcalls_thread, |
| 553 | args=(context,)) |
| 554 | for i in range(context.nThreads)] |
| 555 | with support.start_threads(threads): |
| 556 | self.pendingcalls_wait(context.l, n, context) |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 557 | |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 558 | def pendingcalls_thread(self, context): |
| 559 | try: |
| 560 | self.pendingcalls_submit(context.l, context.n) |
| 561 | finally: |
| 562 | with context.lock: |
| 563 | context.nFinished += 1 |
| 564 | nFinished = context.nFinished |
| 565 | if False and support.verbose: |
| 566 | print("finished threads: ", nFinished) |
| 567 | if nFinished == context.nThreads: |
| 568 | context.event.set() |
| 569 | |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 570 | def test_pendingcalls_non_threaded(self): |
Ezio Melotti | 1392500 | 2011-03-16 11:05:33 +0200 | [diff] [blame] | 571 | #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] | 572 | #once. It is ok to ask for too many, because we loop until we find a slot. |
| 573 | #the loop can be interrupted to dispatch. |
| 574 | #there are only 32 dispatch slots, so we go for twice that! |
| 575 | l = [] |
| 576 | n = 64 |
| 577 | self.pendingcalls_submit(l, n) |
| 578 | self.pendingcalls_wait(l, n) |
| 579 | |
Antoine Pitrou | 7a2572c | 2013-08-01 20:43:26 +0200 | [diff] [blame] | 580 | |
| 581 | class SubinterpreterTest(unittest.TestCase): |
| 582 | |
Antoine Pitrou | 2f828f2 | 2012-01-18 00:21:11 +0100 | [diff] [blame] | 583 | def test_subinterps(self): |
Antoine Pitrou | 2f828f2 | 2012-01-18 00:21:11 +0100 | [diff] [blame] | 584 | import builtins |
| 585 | r, w = os.pipe() |
| 586 | code = """if 1: |
| 587 | import sys, builtins, pickle |
| 588 | with open({:d}, "wb") as f: |
| 589 | pickle.dump(id(sys.modules), f) |
| 590 | pickle.dump(id(builtins), f) |
| 591 | """.format(w) |
| 592 | with open(r, "rb") as f: |
Victor Stinner | ed3b0bc | 2013-11-23 12:27:24 +0100 | [diff] [blame] | 593 | ret = support.run_in_subinterp(code) |
Antoine Pitrou | 2f828f2 | 2012-01-18 00:21:11 +0100 | [diff] [blame] | 594 | self.assertEqual(ret, 0) |
| 595 | self.assertNotEqual(pickle.load(f), id(sys.modules)) |
| 596 | self.assertNotEqual(pickle.load(f), id(builtins)) |
| 597 | |
Marcel Plch | 33e71e0 | 2019-05-22 13:51:26 +0200 | [diff] [blame] | 598 | def test_mutate_exception(self): |
| 599 | """ |
| 600 | Exceptions saved in global module state get shared between |
| 601 | individual module instances. This test checks whether or not |
| 602 | a change in one interpreter's module gets reflected into the |
| 603 | other ones. |
| 604 | """ |
| 605 | import binascii |
| 606 | |
| 607 | support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'") |
| 608 | |
| 609 | self.assertFalse(hasattr(binascii.Error, "foobar")) |
| 610 | |
Antoine Pitrou | 7a2572c | 2013-08-01 20:43:26 +0200 | [diff] [blame] | 611 | |
Ezio Melotti | 29267c8 | 2013-02-23 05:52:46 +0200 | [diff] [blame] | 612 | class TestThreadState(unittest.TestCase): |
| 613 | |
| 614 | @support.reap_threads |
| 615 | def test_thread_state(self): |
| 616 | # some extra thread-state tests driven via _testcapi |
| 617 | def target(): |
| 618 | idents = [] |
| 619 | |
| 620 | def callback(): |
Ezio Melotti | 35246bd | 2013-02-23 05:58:38 +0200 | [diff] [blame] | 621 | idents.append(threading.get_ident()) |
Ezio Melotti | 29267c8 | 2013-02-23 05:52:46 +0200 | [diff] [blame] | 622 | |
| 623 | _testcapi._test_thread_state(callback) |
| 624 | a = b = callback |
| 625 | time.sleep(1) |
| 626 | # Check our main thread is in the list exactly 3 times. |
Ezio Melotti | 35246bd | 2013-02-23 05:58:38 +0200 | [diff] [blame] | 627 | self.assertEqual(idents.count(threading.get_ident()), 3, |
Ezio Melotti | 29267c8 | 2013-02-23 05:52:46 +0200 | [diff] [blame] | 628 | "Couldn't find main thread correctly in the list") |
| 629 | |
| 630 | target() |
| 631 | t = threading.Thread(target=target) |
| 632 | t.start() |
| 633 | t.join() |
| 634 | |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 635 | |
Zachary Ware | c12f09e | 2013-11-11 22:47:04 -0600 | [diff] [blame] | 636 | class Test_testcapi(unittest.TestCase): |
Serhiy Storchaka | 8f7bb10 | 2018-08-06 16:50:19 +0300 | [diff] [blame] | 637 | locals().update((name, getattr(_testcapi, name)) |
| 638 | for name in dir(_testcapi) |
| 639 | if name.startswith('test_') and not name.endswith('_code')) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 640 | |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 641 | |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 642 | class PyMemDebugTests(unittest.TestCase): |
| 643 | PYTHONMALLOC = 'debug' |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 644 | # '0x04c06e0' or '04C06E0' |
Victor Stinner | 08572f6 | 2016-03-14 21:55:43 +0100 | [diff] [blame] | 645 | PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 646 | |
| 647 | def check(self, code): |
| 648 | with support.SuppressCrashReport(): |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 649 | out = assert_python_failure('-c', code, |
| 650 | PYTHONMALLOC=self.PYTHONMALLOC) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 651 | stderr = out.err |
| 652 | return stderr.decode('ascii', 'replace') |
| 653 | |
| 654 | def test_buffer_overflow(self): |
| 655 | out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()') |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 656 | regex = (r"Debug memory block at address p={ptr}: API 'm'\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 657 | r" 16 bytes originally requested\n" |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 658 | r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n" |
| 659 | 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] | 660 | r" at tail\+0: 0x78 \*\*\* OUCH\n" |
Victor Stinner | 4c409be | 2019-04-11 13:01:15 +0200 | [diff] [blame] | 661 | r" at tail\+1: 0xfd\n" |
| 662 | r" at tail\+2: 0xfd\n" |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 663 | r" .*\n" |
Victor Stinner | e8f9acf | 2019-04-12 21:54:06 +0200 | [diff] [blame] | 664 | 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] | 665 | r" Data at p: cd cd cd .*\n" |
Victor Stinner | 6453e9e | 2016-03-15 23:36:28 +0100 | [diff] [blame] | 666 | r"\n" |
Victor Stinner | f966e53 | 2018-11-13 15:14:58 +0100 | [diff] [blame] | 667 | r"Enable tracemalloc to get the memory block allocation traceback\n" |
| 668 | r"\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 669 | r"Fatal Python error: bad trailing pad byte") |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 670 | regex = regex.format(ptr=self.PTR_REGEX) |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 671 | regex = re.compile(regex, flags=re.DOTALL) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 672 | self.assertRegex(out, regex) |
| 673 | |
| 674 | def test_api_misuse(self): |
| 675 | out = self.check('import _testcapi; _testcapi.pymem_api_misuse()') |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 676 | regex = (r"Debug memory block at address p={ptr}: API 'm'\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 677 | r" 16 bytes originally requested\n" |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 678 | r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n" |
| 679 | 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] | 680 | 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] | 681 | r" Data at p: cd cd cd .*\n" |
Victor Stinner | 6453e9e | 2016-03-15 23:36:28 +0100 | [diff] [blame] | 682 | r"\n" |
Victor Stinner | f966e53 | 2018-11-13 15:14:58 +0100 | [diff] [blame] | 683 | r"Enable tracemalloc to get the memory block allocation traceback\n" |
| 684 | r"\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 685 | r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n") |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 686 | regex = regex.format(ptr=self.PTR_REGEX) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 687 | self.assertRegex(out, regex) |
| 688 | |
Victor Stinner | ad52437 | 2016-03-16 12:12:53 +0100 | [diff] [blame] | 689 | def check_malloc_without_gil(self, code): |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 690 | out = self.check(code) |
| 691 | expected = ('Fatal Python error: Python memory allocator called ' |
| 692 | 'without holding the GIL') |
| 693 | self.assertIn(expected, out) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 694 | |
Victor Stinner | ad52437 | 2016-03-16 12:12:53 +0100 | [diff] [blame] | 695 | def test_pymem_malloc_without_gil(self): |
| 696 | # Debug hooks must raise an error if PyMem_Malloc() is called |
| 697 | # without holding the GIL |
| 698 | code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()' |
| 699 | self.check_malloc_without_gil(code) |
| 700 | |
| 701 | def test_pyobject_malloc_without_gil(self): |
| 702 | # Debug hooks must raise an error if PyObject_Malloc() is called |
| 703 | # without holding the GIL |
| 704 | code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()' |
| 705 | self.check_malloc_without_gil(code) |
| 706 | |
Victor Stinner | 3bf0f3a | 2019-06-07 16:22:21 +0200 | [diff] [blame] | 707 | def check_pyobject_is_freed(self, func_name): |
| 708 | code = textwrap.dedent(f''' |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 709 | import gc, os, sys, _testcapi |
| 710 | # Disable the GC to avoid crash on GC collection |
| 711 | gc.disable() |
Victor Stinner | 3bf0f3a | 2019-06-07 16:22:21 +0200 | [diff] [blame] | 712 | try: |
| 713 | _testcapi.{func_name}() |
| 714 | # Exit immediately to avoid a crash while deallocating |
| 715 | # the invalid object |
| 716 | os._exit(0) |
| 717 | except _testcapi.error: |
| 718 | os._exit(1) |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 719 | ''') |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 720 | assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC) |
| 721 | |
Victor Stinner | 6876257 | 2019-10-07 18:42:01 +0200 | [diff] [blame] | 722 | def test_pyobject_null_is_freed(self): |
| 723 | self.check_pyobject_is_freed('check_pyobject_null_is_freed') |
| 724 | |
Victor Stinner | 3bf0f3a | 2019-06-07 16:22:21 +0200 | [diff] [blame] | 725 | def test_pyobject_uninitialized_is_freed(self): |
| 726 | self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed') |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 727 | |
Victor Stinner | 3bf0f3a | 2019-06-07 16:22:21 +0200 | [diff] [blame] | 728 | def test_pyobject_forbidden_bytes_is_freed(self): |
| 729 | self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed') |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 730 | |
Victor Stinner | 3bf0f3a | 2019-06-07 16:22:21 +0200 | [diff] [blame] | 731 | def test_pyobject_freed_is_freed(self): |
| 732 | self.check_pyobject_is_freed('check_pyobject_freed_is_freed') |
Victor Stinner | 2b00db6 | 2019-04-11 11:33:27 +0200 | [diff] [blame] | 733 | |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 734 | |
| 735 | class PyMemMallocDebugTests(PyMemDebugTests): |
| 736 | PYTHONMALLOC = 'malloc_debug' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 737 | |
| 738 | |
Victor Stinner | 5d39e04 | 2017-11-29 17:20:38 +0100 | [diff] [blame] | 739 | @unittest.skipUnless(support.with_pymalloc(), 'need pymalloc') |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 740 | class PyMemPymallocDebugTests(PyMemDebugTests): |
| 741 | PYTHONMALLOC = 'pymalloc_debug' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 742 | |
| 743 | |
| 744 | @unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG') |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 745 | class PyMemDefaultTests(PyMemDebugTests): |
| 746 | # test default allocator of Python compiled in debug mode |
| 747 | PYTHONMALLOC = '' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 748 | |
| 749 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 750 | if __name__ == "__main__": |
Zachary Ware | c12f09e | 2013-11-11 22:47:04 -0600 | [diff] [blame] | 751 | unittest.main() |