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 | |
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 | |
| 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 | |
Victor Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 179 | def test_return_null_without_error(self): |
| 180 | # Issue #23571: A function must not return NULL without setting an |
| 181 | # error |
| 182 | if Py_DEBUG: |
| 183 | code = textwrap.dedent(""" |
| 184 | import _testcapi |
| 185 | from test import support |
| 186 | |
| 187 | with support.SuppressCrashReport(): |
| 188 | _testcapi.return_null_without_error() |
| 189 | """) |
| 190 | rc, out, err = assert_python_failure('-c', code) |
Victor Stinner | 381a9bc | 2015-03-24 14:01:32 +0100 | [diff] [blame] | 191 | self.assertRegex(err.replace(b'\r', b''), |
Victor Stinner | 944fbcc | 2015-03-24 16:28:52 +0100 | [diff] [blame] | 192 | br'Fatal Python error: a function returned NULL ' |
| 193 | br'without setting an error\n' |
Victor Stinner | 381a9bc | 2015-03-24 14:01:32 +0100 | [diff] [blame] | 194 | br'SystemError: <built-in function ' |
| 195 | br'return_null_without_error> returned NULL ' |
| 196 | br'without setting an error\n' |
| 197 | br'\n' |
| 198 | br'Current thread.*:\n' |
| 199 | br' File .*", line 6 in <module>') |
Victor Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 200 | else: |
| 201 | with self.assertRaises(SystemError) as cm: |
| 202 | _testcapi.return_null_without_error() |
| 203 | self.assertRegex(str(cm.exception), |
| 204 | 'return_null_without_error.* ' |
| 205 | 'returned NULL without setting an error') |
| 206 | |
| 207 | def test_return_result_with_error(self): |
| 208 | # Issue #23571: A function must not return a result with an error set |
| 209 | if Py_DEBUG: |
| 210 | code = textwrap.dedent(""" |
| 211 | import _testcapi |
| 212 | from test import support |
| 213 | |
| 214 | with support.SuppressCrashReport(): |
| 215 | _testcapi.return_result_with_error() |
| 216 | """) |
| 217 | rc, out, err = assert_python_failure('-c', code) |
Victor Stinner | 381a9bc | 2015-03-24 14:01:32 +0100 | [diff] [blame] | 218 | self.assertRegex(err.replace(b'\r', b''), |
Victor Stinner | 944fbcc | 2015-03-24 16:28:52 +0100 | [diff] [blame] | 219 | br'Fatal Python error: a function returned a ' |
| 220 | br'result with an error set\n' |
Victor Stinner | 381a9bc | 2015-03-24 14:01:32 +0100 | [diff] [blame] | 221 | br'ValueError\n' |
| 222 | br'\n' |
Serhiy Storchaka | 467ab19 | 2016-10-21 17:09:17 +0300 | [diff] [blame] | 223 | br'The above exception was the direct cause ' |
| 224 | br'of the following exception:\n' |
Victor Stinner | 381a9bc | 2015-03-24 14:01:32 +0100 | [diff] [blame] | 225 | br'\n' |
| 226 | br'SystemError: <built-in ' |
| 227 | br'function return_result_with_error> ' |
| 228 | br'returned a result with an error set\n' |
| 229 | br'\n' |
| 230 | br'Current thread.*:\n' |
| 231 | br' File .*, line 6 in <module>') |
Victor Stinner | efde146 | 2015-03-21 15:04:43 +0100 | [diff] [blame] | 232 | else: |
| 233 | with self.assertRaises(SystemError) as cm: |
| 234 | _testcapi.return_result_with_error() |
| 235 | self.assertRegex(str(cm.exception), |
| 236 | 'return_result_with_error.* ' |
| 237 | 'returned a result with an error set') |
| 238 | |
Serhiy Storchaka | 13e602e | 2016-05-20 22:31:14 +0300 | [diff] [blame] | 239 | def test_buildvalue_N(self): |
| 240 | _testcapi.test_buildvalue_N() |
| 241 | |
xdegaye | 85f6430 | 2017-07-01 14:14:45 +0200 | [diff] [blame] | 242 | def test_set_nomemory(self): |
| 243 | code = """if 1: |
| 244 | import _testcapi |
| 245 | |
| 246 | class C(): pass |
| 247 | |
| 248 | # The first loop tests both functions and that remove_mem_hooks() |
| 249 | # can be called twice in a row. The second loop checks a call to |
| 250 | # set_nomemory() after a call to remove_mem_hooks(). The third |
| 251 | # loop checks the start and stop arguments of set_nomemory(). |
| 252 | for outer_cnt in range(1, 4): |
| 253 | start = 10 * outer_cnt |
| 254 | for j in range(100): |
| 255 | if j == 0: |
| 256 | if outer_cnt != 3: |
| 257 | _testcapi.set_nomemory(start) |
| 258 | else: |
| 259 | _testcapi.set_nomemory(start, start + 1) |
| 260 | try: |
| 261 | C() |
| 262 | except MemoryError as e: |
| 263 | if outer_cnt != 3: |
| 264 | _testcapi.remove_mem_hooks() |
| 265 | print('MemoryError', outer_cnt, j) |
| 266 | _testcapi.remove_mem_hooks() |
| 267 | break |
| 268 | """ |
| 269 | rc, out, err = assert_python_ok('-c', code) |
| 270 | self.assertIn(b'MemoryError 1 10', out) |
| 271 | self.assertIn(b'MemoryError 2 20', out) |
| 272 | self.assertIn(b'MemoryError 3 30', out) |
| 273 | |
Oren Milman | 0ccc0f6 | 2017-10-08 11:17:46 +0300 | [diff] [blame] | 274 | def test_mapping_keys_values_items(self): |
| 275 | class Mapping1(dict): |
| 276 | def keys(self): |
| 277 | return list(super().keys()) |
| 278 | def values(self): |
| 279 | return list(super().values()) |
| 280 | def items(self): |
| 281 | return list(super().items()) |
| 282 | class Mapping2(dict): |
| 283 | def keys(self): |
| 284 | return tuple(super().keys()) |
| 285 | def values(self): |
| 286 | return tuple(super().values()) |
| 287 | def items(self): |
| 288 | return tuple(super().items()) |
| 289 | dict_obj = {'foo': 1, 'bar': 2, 'spam': 3} |
| 290 | |
| 291 | for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(), |
| 292 | dict_obj, OrderedDict(dict_obj), |
| 293 | Mapping1(dict_obj), Mapping2(dict_obj)]: |
| 294 | self.assertListEqual(_testcapi.get_mapping_keys(mapping), |
| 295 | list(mapping.keys())) |
| 296 | self.assertListEqual(_testcapi.get_mapping_values(mapping), |
| 297 | list(mapping.values())) |
| 298 | self.assertListEqual(_testcapi.get_mapping_items(mapping), |
| 299 | list(mapping.items())) |
| 300 | |
| 301 | def test_mapping_keys_values_items_bad_arg(self): |
| 302 | self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None) |
| 303 | self.assertRaises(AttributeError, _testcapi.get_mapping_values, None) |
| 304 | self.assertRaises(AttributeError, _testcapi.get_mapping_items, None) |
| 305 | |
| 306 | class BadMapping: |
| 307 | def keys(self): |
| 308 | return None |
| 309 | def values(self): |
| 310 | return None |
| 311 | def items(self): |
| 312 | return None |
| 313 | bad_mapping = BadMapping() |
| 314 | self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping) |
| 315 | self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping) |
| 316 | self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping) |
| 317 | |
Larry Hastings | 44e2eaa | 2013-11-23 15:37:55 -0800 | [diff] [blame] | 318 | |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 319 | class TestPendingCalls(unittest.TestCase): |
| 320 | |
| 321 | def pendingcalls_submit(self, l, n): |
| 322 | def callback(): |
| 323 | #this function can be interrupted by thread switching so let's |
| 324 | #use an atomic operation |
| 325 | l.append(None) |
| 326 | |
| 327 | for i in range(n): |
| 328 | time.sleep(random.random()*0.02) #0.01 secs on average |
| 329 | #try submitting callback until successful. |
| 330 | #rely on regular interrupt to flush queue if we are |
| 331 | #unsuccessful. |
| 332 | while True: |
| 333 | if _testcapi._pending_threadfunc(callback): |
| 334 | break; |
| 335 | |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 336 | def pendingcalls_wait(self, l, n, context = None): |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 337 | #now, stick around until l[0] has grown to 10 |
| 338 | count = 0; |
| 339 | while len(l) != n: |
| 340 | #this busy loop is where we expect to be interrupted to |
| 341 | #run our callbacks. Note that callbacks are only run on the |
| 342 | #main thread |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 343 | if False and support.verbose: |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 344 | print("(%i)"%(len(l),),) |
| 345 | for i in range(1000): |
| 346 | a = i*i |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 347 | if context and not context.event.is_set(): |
| 348 | continue |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 349 | count += 1 |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 350 | self.assertTrue(count < 10000, |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 351 | "timeout waiting for %i callbacks, got %i"%(n, len(l))) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 352 | if False and support.verbose: |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 353 | print("(%i)"%(len(l),)) |
| 354 | |
| 355 | def test_pendingcalls_threaded(self): |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 356 | |
| 357 | #do every callback on a separate thread |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 358 | n = 32 #total callbacks |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 359 | threads = [] |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 360 | class foo(object):pass |
| 361 | context = foo() |
| 362 | context.l = [] |
| 363 | context.n = 2 #submits per thread |
| 364 | context.nThreads = n // context.n |
| 365 | context.nFinished = 0 |
| 366 | context.lock = threading.Lock() |
| 367 | context.event = threading.Event() |
| 368 | |
Serhiy Storchaka | 263dcd2 | 2015-04-01 13:01:14 +0300 | [diff] [blame] | 369 | threads = [threading.Thread(target=self.pendingcalls_thread, |
| 370 | args=(context,)) |
| 371 | for i in range(context.nThreads)] |
| 372 | with support.start_threads(threads): |
| 373 | self.pendingcalls_wait(context.l, n, context) |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 374 | |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 375 | def pendingcalls_thread(self, context): |
| 376 | try: |
| 377 | self.pendingcalls_submit(context.l, context.n) |
| 378 | finally: |
| 379 | with context.lock: |
| 380 | context.nFinished += 1 |
| 381 | nFinished = context.nFinished |
| 382 | if False and support.verbose: |
| 383 | print("finished threads: ", nFinished) |
| 384 | if nFinished == context.nThreads: |
| 385 | context.event.set() |
| 386 | |
Benjamin Peterson | a54c909 | 2009-01-13 02:11:23 +0000 | [diff] [blame] | 387 | def test_pendingcalls_non_threaded(self): |
Ezio Melotti | 1392500 | 2011-03-16 11:05:33 +0200 | [diff] [blame] | 388 | #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] | 389 | #once. It is ok to ask for too many, because we loop until we find a slot. |
| 390 | #the loop can be interrupted to dispatch. |
| 391 | #there are only 32 dispatch slots, so we go for twice that! |
| 392 | l = [] |
| 393 | n = 64 |
| 394 | self.pendingcalls_submit(l, n) |
| 395 | self.pendingcalls_wait(l, n) |
| 396 | |
Antoine Pitrou | 7a2572c | 2013-08-01 20:43:26 +0200 | [diff] [blame] | 397 | |
| 398 | class SubinterpreterTest(unittest.TestCase): |
| 399 | |
Antoine Pitrou | 2f828f2 | 2012-01-18 00:21:11 +0100 | [diff] [blame] | 400 | def test_subinterps(self): |
Antoine Pitrou | 2f828f2 | 2012-01-18 00:21:11 +0100 | [diff] [blame] | 401 | import builtins |
| 402 | r, w = os.pipe() |
| 403 | code = """if 1: |
| 404 | import sys, builtins, pickle |
| 405 | with open({:d}, "wb") as f: |
| 406 | pickle.dump(id(sys.modules), f) |
| 407 | pickle.dump(id(builtins), f) |
| 408 | """.format(w) |
| 409 | with open(r, "rb") as f: |
Victor Stinner | ed3b0bc | 2013-11-23 12:27:24 +0100 | [diff] [blame] | 410 | ret = support.run_in_subinterp(code) |
Antoine Pitrou | 2f828f2 | 2012-01-18 00:21:11 +0100 | [diff] [blame] | 411 | self.assertEqual(ret, 0) |
| 412 | self.assertNotEqual(pickle.load(f), id(sys.modules)) |
| 413 | self.assertNotEqual(pickle.load(f), id(builtins)) |
| 414 | |
Antoine Pitrou | 7a2572c | 2013-08-01 20:43:26 +0200 | [diff] [blame] | 415 | |
Ezio Melotti | 29267c8 | 2013-02-23 05:52:46 +0200 | [diff] [blame] | 416 | class TestThreadState(unittest.TestCase): |
| 417 | |
| 418 | @support.reap_threads |
| 419 | def test_thread_state(self): |
| 420 | # some extra thread-state tests driven via _testcapi |
| 421 | def target(): |
| 422 | idents = [] |
| 423 | |
| 424 | def callback(): |
Ezio Melotti | 35246bd | 2013-02-23 05:58:38 +0200 | [diff] [blame] | 425 | idents.append(threading.get_ident()) |
Ezio Melotti | 29267c8 | 2013-02-23 05:52:46 +0200 | [diff] [blame] | 426 | |
| 427 | _testcapi._test_thread_state(callback) |
| 428 | a = b = callback |
| 429 | time.sleep(1) |
| 430 | # Check our main thread is in the list exactly 3 times. |
Ezio Melotti | 35246bd | 2013-02-23 05:58:38 +0200 | [diff] [blame] | 431 | self.assertEqual(idents.count(threading.get_ident()), 3, |
Ezio Melotti | 29267c8 | 2013-02-23 05:52:46 +0200 | [diff] [blame] | 432 | "Couldn't find main thread correctly in the list") |
| 433 | |
| 434 | target() |
| 435 | t = threading.Thread(target=target) |
| 436 | t.start() |
| 437 | t.join() |
| 438 | |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 439 | |
Zachary Ware | c12f09e | 2013-11-11 22:47:04 -0600 | [diff] [blame] | 440 | class Test_testcapi(unittest.TestCase): |
Serhiy Storchaka | 8f7bb10 | 2018-08-06 16:50:19 +0300 | [diff] [blame] | 441 | locals().update((name, getattr(_testcapi, name)) |
| 442 | for name in dir(_testcapi) |
| 443 | if name.startswith('test_') and not name.endswith('_code')) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 444 | |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 445 | |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 446 | class PyMemDebugTests(unittest.TestCase): |
| 447 | PYTHONMALLOC = 'debug' |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 448 | # '0x04c06e0' or '04C06E0' |
Victor Stinner | 08572f6 | 2016-03-14 21:55:43 +0100 | [diff] [blame] | 449 | PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 450 | |
| 451 | def check(self, code): |
| 452 | with support.SuppressCrashReport(): |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 453 | out = assert_python_failure('-c', code, |
| 454 | PYTHONMALLOC=self.PYTHONMALLOC) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 455 | stderr = out.err |
| 456 | return stderr.decode('ascii', 'replace') |
| 457 | |
| 458 | def test_buffer_overflow(self): |
| 459 | out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()') |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 460 | regex = (r"Debug memory block at address p={ptr}: API 'm'\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 461 | r" 16 bytes originally requested\n" |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 462 | r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n" |
| 463 | 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] | 464 | r" at tail\+0: 0x78 \*\*\* OUCH\n" |
| 465 | r" at tail\+1: 0xfb\n" |
| 466 | r" at tail\+2: 0xfb\n" |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 467 | r" .*\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 468 | r" The block was made by call #[0-9]+ to debug malloc/realloc.\n" |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 469 | r" Data at p: cb cb cb .*\n" |
Victor Stinner | 6453e9e | 2016-03-15 23:36:28 +0100 | [diff] [blame] | 470 | r"\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 471 | r"Fatal Python error: bad trailing pad byte") |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 472 | regex = regex.format(ptr=self.PTR_REGEX) |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 473 | regex = re.compile(regex, flags=re.DOTALL) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 474 | self.assertRegex(out, regex) |
| 475 | |
| 476 | def test_api_misuse(self): |
| 477 | out = self.check('import _testcapi; _testcapi.pymem_api_misuse()') |
Victor Stinner | a1bc28a | 2016-03-14 17:10:36 +0100 | [diff] [blame] | 478 | regex = (r"Debug memory block at address p={ptr}: API 'm'\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 479 | r" 16 bytes originally requested\n" |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 480 | r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n" |
| 481 | r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 482 | r" The block was made by call #[0-9]+ to debug malloc/realloc.\n" |
Victor Stinner | b3adb1a | 2016-03-14 17:40:09 +0100 | [diff] [blame] | 483 | r" Data at p: cb cb cb .*\n" |
Victor Stinner | 6453e9e | 2016-03-15 23:36:28 +0100 | [diff] [blame] | 484 | r"\n" |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 485 | 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] | 486 | regex = regex.format(ptr=self.PTR_REGEX) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 487 | self.assertRegex(out, regex) |
| 488 | |
Victor Stinner | ad52437 | 2016-03-16 12:12:53 +0100 | [diff] [blame] | 489 | def check_malloc_without_gil(self, code): |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 490 | out = self.check(code) |
| 491 | expected = ('Fatal Python error: Python memory allocator called ' |
| 492 | 'without holding the GIL') |
| 493 | self.assertIn(expected, out) |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 494 | |
Victor Stinner | ad52437 | 2016-03-16 12:12:53 +0100 | [diff] [blame] | 495 | def test_pymem_malloc_without_gil(self): |
| 496 | # Debug hooks must raise an error if PyMem_Malloc() is called |
| 497 | # without holding the GIL |
| 498 | code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()' |
| 499 | self.check_malloc_without_gil(code) |
| 500 | |
| 501 | def test_pyobject_malloc_without_gil(self): |
| 502 | # Debug hooks must raise an error if PyObject_Malloc() is called |
| 503 | # without holding the GIL |
| 504 | code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()' |
| 505 | self.check_malloc_without_gil(code) |
| 506 | |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 507 | |
| 508 | class PyMemMallocDebugTests(PyMemDebugTests): |
| 509 | PYTHONMALLOC = 'malloc_debug' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 510 | |
| 511 | |
Victor Stinner | 5d39e04 | 2017-11-29 17:20:38 +0100 | [diff] [blame] | 512 | @unittest.skipUnless(support.with_pymalloc(), 'need pymalloc') |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 513 | class PyMemPymallocDebugTests(PyMemDebugTests): |
| 514 | PYTHONMALLOC = 'pymalloc_debug' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 515 | |
| 516 | |
| 517 | @unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG') |
Victor Stinner | c4aec36 | 2016-03-14 22:26:53 +0100 | [diff] [blame] | 518 | class PyMemDefaultTests(PyMemDebugTests): |
| 519 | # test default allocator of Python compiled in debug mode |
| 520 | PYTHONMALLOC = '' |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 521 | |
| 522 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 523 | if __name__ == "__main__": |
Zachary Ware | c12f09e | 2013-11-11 22:47:04 -0600 | [diff] [blame] | 524 | unittest.main() |