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