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