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