blob: 0d5c97dcc2a4aa9e7c7d9643f2301b4454f91743 [file] [log] [blame]
Tim Petersd66595f2001-02-04 03:09:53 +00001# Run the _testcapi module tests (tests for the Python/C API): by defn,
Guido van Rossum361c5352001-04-13 17:03:04 +00002# these are all functions _testcapi exports whose name begins with 'test_'.
Tim Peters9ea17ac2001-02-02 05:57:15 +00003
Nick Coghlan39f0bb52017-11-28 08:11:51 +10004from collections import OrderedDict
Antoine Pitrou8e605772011-04-25 21:21:07 +02005import os
Antoine Pitrou2f828f22012-01-18 00:21:11 +01006import pickle
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00007import random
Victor Stinnerb3adb1a2016-03-14 17:40:09 +01008import re
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +00009import subprocess
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +000010import sys
Victor Stinnerefde1462015-03-21 15:04:43 +010011import textwrap
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020012import threading
Benjamin Petersona54c9092009-01-13 02:11:23 +000013import time
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000014import unittest
Eddie Elizondo3368f3c2019-09-19 09:29:05 -070015import weakref
Petr Viktorine1becf42020-05-07 15:39:59 +020016import importlib.machinery
17import importlib.util
Benjamin Petersonee8712c2008-05-20 21:35:26 +000018from test import support
Larry Hastingsfcafe432013-11-23 17:35:48 -080019from test.support import MISSING_C_DOCSTRINGS
Hai Shi883bc632020-07-06 17:12:49 +080020from test.support import import_helper
Hai Shie80697d2020-05-28 06:10:27 +080021from test.support import threading_helper
Inada Naoki902356a2020-07-20 12:02:50 +090022from test.support import warnings_helper
xdegaye85f64302017-07-01 14:14:45 +020023from test.support.script_helper import assert_python_failure, assert_python_ok
Victor Stinner45df8202010-04-28 22:31:17 +000024try:
Stefan Krahfd24f9e2012-08-20 11:04:24 +020025 import _posixsubprocess
26except ImportError:
27 _posixsubprocess = None
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020028
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +020029# Skip this test if the _testcapi module isn't available.
Hai Shi883bc632020-07-06 17:12:49 +080030_testcapi = import_helper.import_module('_testcapi')
Tim Peters9ea17ac2001-02-02 05:57:15 +000031
Victor Stinner1ae035b2020-04-17 17:47:20 +020032import _testinternalcapi
33
Victor Stinnerefde1462015-03-21 15:04:43 +010034# Were we compiled --with-pydebug or with #define Py_DEBUG?
35Py_DEBUG = hasattr(sys, 'gettotalrefcount')
36
Benjamin Petersona54c9092009-01-13 02:11:23 +000037
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000038def testfunction(self):
39 """some doc"""
40 return self
41
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +020042
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000043class InstanceMethod:
44 id = _testcapi.instancemethod(id)
45 testfunction = _testcapi.instancemethod(testfunction)
46
47class CAPITest(unittest.TestCase):
48
49 def test_instancemethod(self):
50 inst = InstanceMethod()
51 self.assertEqual(id(inst), inst.id())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000052 self.assertTrue(inst.testfunction() is inst)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000053 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 Yasskin8e0bdfd2010-05-13 18:31:05 +000060 def test_no_FatalError_infinite_loop(self):
Antoine Pitrou77e904e2013-10-08 23:04:32 +020061 with support.SuppressCrashReport():
Ezio Melotti25a40452013-03-05 20:26:17 +020062 p = subprocess.Popen([sys.executable, "-c",
Ezio Melottie1857d92013-03-05 20:31:34 +020063 'import _testcapi;'
64 '_testcapi.crash_no_current_thread()'],
65 stdout=subprocess.PIPE,
66 stderr=subprocess.PIPE)
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +000067 (out, err) = p.communicate()
68 self.assertEqual(out, b'')
69 # This used to cause an infinite loop.
Vinay Sajip73954042012-05-06 11:34:50 +010070 self.assertTrue(err.rstrip().startswith(
Victor Stinner9e5d30c2020-03-07 00:54:20 +010071 b'Fatal Python error: '
Victor Stinner23ef89d2020-03-18 02:26:04 +010072 b'PyThreadState_Get: '
Victor Stinner3026cad2020-06-01 16:02:40 +020073 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 Yasskin8e0bdfd2010-05-13 18:31:05 +000077
Antoine Pitrou915605c2011-02-24 20:53:48 +000078 def test_memoryview_from_NULL_pointer(self):
79 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
Benjamin Peterson9b6df6a2008-10-16 23:56:29 +000080
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020081 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 Krahfd24f9e2012-08-20 11:04:24 +0200104 @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. Smithf3751ef2019-10-12 13:24:56 -0700111 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)
Stefan Krah7cacd2e2012-08-21 08:16:09 +0200112 # 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. Smithf3751ef2019-10-12 13:24:56 -0700119 1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)
Stefan Krahfd24f9e2012-08-20 11:04:24 +0200120
Stefan Krahdb579d72012-08-20 14:36:47 +0200121 @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. Smithf3751ef2019-10-12 13:24:56 -0700129 Z(),[b'1'],3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)
Stefan Krahdb579d72012-08-20 14:36:47 +0200130
Larry Hastingsfcafe432013-11-23 17:35:48 -0800131 @unittest.skipIf(MISSING_C_DOCSTRINGS,
132 "Signature information for builtins requires docstrings")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800133 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 Ware8ef887c2015-04-13 18:22:35 -0500138 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800139 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 Hastings2623c8c2014-02-08 22:15:29 -0800146 "docstring_with_invalid_signature($module, /, boo)\n"
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800147 "\n"
148 "This docstring has an invalid signature."
149 )
150 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
151
Larry Hastings2623c8c2014-02-08 22:15:29 -0800152 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 Hastings44e2eaa2013-11-23 15:37:55 -0800161 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
162 "This docstring has a valid signature.")
Larry Hastings2623c8c2014-02-08 22:15:29 -0800163 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800164
Zachary Ware8ef887c2015-04-13 18:22:35 -0500165 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 Hastings44e2eaa2013-11-23 15:37:55 -0800169 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800170 "\nThis docstring has a valid signature and some extra newlines.")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800171 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800172 "($module, /, parameter)")
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800173
Benjamin Petersond51374e2014-04-09 23:55:56 -0400174 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 Spytzc7f803b2019-05-31 03:46:36 -0600191 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 Stinnerefde1462015-03-21 15:04:43 +0100198 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 Stinner381a9bc2015-03-24 14:01:32 +0100210 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100211 br'Fatal Python error: _Py_CheckFunctionResult: '
212 br'a function returned NULL '
Victor Stinner944fbcc2015-03-24 16:28:52 +0100213 br'without setting an error\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200214 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100215 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 Stinnerefde1462015-03-21 15:04:43 +0100221 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 Stinner381a9bc2015-03-24 14:01:32 +0100239 self.assertRegex(err.replace(b'\r', b''),
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100240 br'Fatal Python error: _Py_CheckFunctionResult: '
241 br'a function returned a result '
242 br'with an error set\n'
Victor Stinner1ce16fb2019-09-18 01:35:33 +0200243 br'Python runtime state: initialized\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100244 br'ValueError\n'
245 br'\n'
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300246 br'The above exception was the direct cause '
247 br'of the following exception:\n'
Victor Stinner381a9bc2015-03-24 14:01:32 +0100248 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 Stinnerefde1462015-03-21 15:04:43 +0100255 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 Storchaka13e602e2016-05-20 22:31:14 +0300262 def test_buildvalue_N(self):
263 _testcapi.test_buildvalue_N()
264
xdegaye85f64302017-07-01 14:14:45 +0200265 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 Milman0ccc0f62017-10-08 11:17:46 +0300297 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 Stinner18618e652018-10-25 17:28:11 +0200341 @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 Stinner3ec9af72018-10-26 02:12:34 +0200355 br'_testcapimodule\.c:[0-9]+: '
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100356 br'_Py_NegativeRefcount: Assertion failed: '
Victor Stinner3ec9af72018-10-26 02:12:34 +0200357 br'object has negative ref count')
Victor Stinner18618e652018-10-25 17:28:11 +0200358
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200359 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 Stinner0127bb12019-11-21 12:54:02 +0100367 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200368 def test_trashcan_python_class1(self):
369 self.do_test_trashcan_python_class(list)
370
Victor Stinner0127bb12019-11-21 12:54:02 +0100371 @support.requires_resource('cpu')
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200372 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
Benjamin Peterson39403332020-09-02 11:29:06 -0500404 def test_heap_ctype_doc_and_text_signature(self):
405 self.assertEqual(_testcapi.HeapDocCType.__doc__, "somedoc")
406 self.assertEqual(_testcapi.HeapDocCType.__text_signature__, "(arg1, arg2)")
407
Hai Shi88c2cfd2020-11-07 00:04:47 +0800408 def test_null_type_doc(self):
409 self.assertEqual(_testcapi.NullTpDocType.__doc__, None)
410
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400411 def test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once(self):
412 class HeapGcCTypeSubclass(_testcapi.HeapGcCType):
413 def __init__(self):
414 self.value2 = 20
415 super().__init__()
416
417 subclass_instance = HeapGcCTypeSubclass()
418 type_refcnt = sys.getrefcount(HeapGcCTypeSubclass)
419
420 # Test that subclass instance was fully created
421 self.assertEqual(subclass_instance.value, 10)
422 self.assertEqual(subclass_instance.value2, 20)
423
424 # Test that the type reference count is only decremented once
425 del subclass_instance
426 self.assertEqual(type_refcnt - 1, sys.getrefcount(HeapGcCTypeSubclass))
427
428 def test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
429 class A(_testcapi.HeapGcCType):
430 def __init__(self):
431 self.value2 = 20
432 super().__init__()
433
434 class B(A):
435 def __init__(self):
436 super().__init__()
437
438 def __del__(self):
439 self.__class__ = A
440 A.refcnt_in_del = sys.getrefcount(A)
441 B.refcnt_in_del = sys.getrefcount(B)
442
443 subclass_instance = B()
444 type_refcnt = sys.getrefcount(B)
445 new_type_refcnt = sys.getrefcount(A)
446
447 # Test that subclass instance was fully created
448 self.assertEqual(subclass_instance.value, 10)
449 self.assertEqual(subclass_instance.value2, 20)
450
451 del subclass_instance
452
453 # Test that setting __class__ modified the reference counts of the types
454 self.assertEqual(type_refcnt - 1, B.refcnt_in_del)
455 self.assertEqual(new_type_refcnt + 1, A.refcnt_in_del)
456
457 # Test that the original type already has decreased its refcnt
458 self.assertEqual(type_refcnt - 1, sys.getrefcount(B))
459
460 # Test that subtype_dealloc decref the newly assigned __class__ only once
461 self.assertEqual(new_type_refcnt, sys.getrefcount(A))
462
Eddie Elizondo3368f3c2019-09-19 09:29:05 -0700463 def test_heaptype_with_dict(self):
464 inst = _testcapi.HeapCTypeWithDict()
465 inst.foo = 42
466 self.assertEqual(inst.foo, 42)
467 self.assertEqual(inst.dictobj, inst.__dict__)
468 self.assertEqual(inst.dictobj, {"foo": 42})
469
470 inst = _testcapi.HeapCTypeWithDict()
471 self.assertEqual({}, inst.__dict__)
472
473 def test_heaptype_with_negative_dict(self):
474 inst = _testcapi.HeapCTypeWithNegativeDict()
475 inst.foo = 42
476 self.assertEqual(inst.foo, 42)
477 self.assertEqual(inst.dictobj, inst.__dict__)
478 self.assertEqual(inst.dictobj, {"foo": 42})
479
480 inst = _testcapi.HeapCTypeWithNegativeDict()
481 self.assertEqual({}, inst.__dict__)
482
483 def test_heaptype_with_weakref(self):
484 inst = _testcapi.HeapCTypeWithWeakref()
485 ref = weakref.ref(inst)
486 self.assertEqual(ref(), inst)
487 self.assertEqual(inst.weakreflist, ref)
488
scoderf7c4e232020-06-06 21:35:10 +0200489 def test_heaptype_with_buffer(self):
490 inst = _testcapi.HeapCTypeWithBuffer()
491 b = bytes(inst)
492 self.assertEqual(b, b"1234")
493
Eddie Elizondoff023ed2019-09-11 05:17:13 -0400494 def test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once(self):
495 subclass_instance = _testcapi.HeapCTypeSubclass()
496 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
497
498 # Test that subclass instance was fully created
499 self.assertEqual(subclass_instance.value, 10)
500 self.assertEqual(subclass_instance.value2, 20)
501
502 # Test that the type reference count is only decremented once
503 del subclass_instance
504 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclass))
505
506 def test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
507 subclass_instance = _testcapi.HeapCTypeSubclassWithFinalizer()
508 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer)
509 new_type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
510
511 # Test that subclass instance was fully created
512 self.assertEqual(subclass_instance.value, 10)
513 self.assertEqual(subclass_instance.value2, 20)
514
515 # The tp_finalize slot will set __class__ to HeapCTypeSubclass
516 del subclass_instance
517
518 # Test that setting __class__ modified the reference counts of the types
519 self.assertEqual(type_refcnt - 1, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
520 self.assertEqual(new_type_refcnt + 1, _testcapi.HeapCTypeSubclass.refcnt_in_del)
521
522 # Test that the original type already has decreased its refcnt
523 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer))
524
525 # Test that subtype_dealloc decref the newly assigned __class__ only once
526 self.assertEqual(new_type_refcnt, sys.getrefcount(_testcapi.HeapCTypeSubclass))
527
scoder148f3292020-07-03 02:09:28 +0200528 def test_heaptype_with_setattro(self):
529 obj = _testcapi.HeapCTypeSetattr()
530 self.assertEqual(obj.pvalue, 10)
531 obj.value = 12
532 self.assertEqual(obj.pvalue, 12)
533 del obj.value
534 self.assertEqual(obj.pvalue, 0)
535
Serhiy Storchakae5ccc942020-03-09 20:03:38 +0200536 def test_pynumber_tobase(self):
537 from _testcapi import pynumber_tobase
538 self.assertEqual(pynumber_tobase(123, 2), '0b1111011')
539 self.assertEqual(pynumber_tobase(123, 8), '0o173')
540 self.assertEqual(pynumber_tobase(123, 10), '123')
541 self.assertEqual(pynumber_tobase(123, 16), '0x7b')
542 self.assertEqual(pynumber_tobase(-123, 2), '-0b1111011')
543 self.assertEqual(pynumber_tobase(-123, 8), '-0o173')
544 self.assertEqual(pynumber_tobase(-123, 10), '-123')
545 self.assertEqual(pynumber_tobase(-123, 16), '-0x7b')
546 self.assertRaises(TypeError, pynumber_tobase, 123.0, 10)
547 self.assertRaises(TypeError, pynumber_tobase, '123', 10)
548 self.assertRaises(SystemError, pynumber_tobase, 123, 0)
549
Victor Stinnere2320252021-01-18 18:24:29 +0100550 def test_fatal_error(self):
551 code = 'import _testcapi; _testcapi.fatal_error(b"MESSAGE")'
552 with support.SuppressCrashReport():
553 rc, out, err = assert_python_failure('-sSI', '-c', code)
554
555 err = err.replace(b'\r', b'').decode('ascii', 'replace')
556 self.assertIn('Fatal Python error: test_fatal_error: MESSAGE\n',
557 err)
558
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800559
Benjamin Petersona54c9092009-01-13 02:11:23 +0000560class TestPendingCalls(unittest.TestCase):
561
562 def pendingcalls_submit(self, l, n):
563 def callback():
564 #this function can be interrupted by thread switching so let's
565 #use an atomic operation
566 l.append(None)
567
568 for i in range(n):
569 time.sleep(random.random()*0.02) #0.01 secs on average
570 #try submitting callback until successful.
571 #rely on regular interrupt to flush queue if we are
572 #unsuccessful.
573 while True:
574 if _testcapi._pending_threadfunc(callback):
575 break;
576
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000577 def pendingcalls_wait(self, l, n, context = None):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000578 #now, stick around until l[0] has grown to 10
579 count = 0;
580 while len(l) != n:
581 #this busy loop is where we expect to be interrupted to
582 #run our callbacks. Note that callbacks are only run on the
583 #main thread
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000584 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000585 print("(%i)"%(len(l),),)
586 for i in range(1000):
587 a = i*i
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000588 if context and not context.event.is_set():
589 continue
Benjamin Petersona54c9092009-01-13 02:11:23 +0000590 count += 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000591 self.assertTrue(count < 10000,
Benjamin Petersona54c9092009-01-13 02:11:23 +0000592 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000593 if False and support.verbose:
Benjamin Petersona54c9092009-01-13 02:11:23 +0000594 print("(%i)"%(len(l),))
595
596 def test_pendingcalls_threaded(self):
Benjamin Petersona54c9092009-01-13 02:11:23 +0000597
598 #do every callback on a separate thread
Victor Stinnere225beb2019-06-03 18:14:24 +0200599 n = 32 #total callbacks
Benjamin Petersona54c9092009-01-13 02:11:23 +0000600 threads = []
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000601 class foo(object):pass
602 context = foo()
603 context.l = []
604 context.n = 2 #submits per thread
605 context.nThreads = n // context.n
606 context.nFinished = 0
607 context.lock = threading.Lock()
608 context.event = threading.Event()
609
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300610 threads = [threading.Thread(target=self.pendingcalls_thread,
611 args=(context,))
612 for i in range(context.nThreads)]
Hai Shie80697d2020-05-28 06:10:27 +0800613 with threading_helper.start_threads(threads):
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300614 self.pendingcalls_wait(context.l, n, context)
Benjamin Petersona54c9092009-01-13 02:11:23 +0000615
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000616 def pendingcalls_thread(self, context):
617 try:
618 self.pendingcalls_submit(context.l, context.n)
619 finally:
620 with context.lock:
621 context.nFinished += 1
622 nFinished = context.nFinished
623 if False and support.verbose:
624 print("finished threads: ", nFinished)
625 if nFinished == context.nThreads:
626 context.event.set()
627
Benjamin Petersona54c9092009-01-13 02:11:23 +0000628 def test_pendingcalls_non_threaded(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200629 #again, just using the main thread, likely they will all be dispatched at
Benjamin Petersona54c9092009-01-13 02:11:23 +0000630 #once. It is ok to ask for too many, because we loop until we find a slot.
631 #the loop can be interrupted to dispatch.
632 #there are only 32 dispatch slots, so we go for twice that!
633 l = []
634 n = 64
635 self.pendingcalls_submit(l, n)
636 self.pendingcalls_wait(l, n)
637
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200638
639class SubinterpreterTest(unittest.TestCase):
640
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100641 def test_subinterps(self):
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100642 import builtins
643 r, w = os.pipe()
644 code = """if 1:
645 import sys, builtins, pickle
646 with open({:d}, "wb") as f:
647 pickle.dump(id(sys.modules), f)
648 pickle.dump(id(builtins), f)
649 """.format(w)
650 with open(r, "rb") as f:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100651 ret = support.run_in_subinterp(code)
Antoine Pitrou2f828f22012-01-18 00:21:11 +0100652 self.assertEqual(ret, 0)
653 self.assertNotEqual(pickle.load(f), id(sys.modules))
654 self.assertNotEqual(pickle.load(f), id(builtins))
655
Guido van Rossum9d197c72020-06-27 17:33:49 -0700656 def test_subinterps_recent_language_features(self):
657 r, w = os.pipe()
658 code = """if 1:
659 import pickle
660 with open({:d}, "wb") as f:
661
662 @(lambda x:x) # Py 3.9
663 def noop(x): return x
664
665 a = (b := f'1{{2}}3') + noop('x') # Py 3.8 (:=) / 3.6 (f'')
666
667 async def foo(arg): return await arg # Py 3.5
668
669 pickle.dump(dict(a=a, b=b), f)
670 """.format(w)
671
672 with open(r, "rb") as f:
673 ret = support.run_in_subinterp(code)
674 self.assertEqual(ret, 0)
675 self.assertEqual(pickle.load(f), {'a': '123x', 'b': '123'})
676
Marcel Plch33e71e02019-05-22 13:51:26 +0200677 def test_mutate_exception(self):
678 """
679 Exceptions saved in global module state get shared between
680 individual module instances. This test checks whether or not
681 a change in one interpreter's module gets reflected into the
682 other ones.
683 """
684 import binascii
685
686 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
687
688 self.assertFalse(hasattr(binascii.Error, "foobar"))
689
Antoine Pitrou7a2572c2013-08-01 20:43:26 +0200690
Ezio Melotti29267c82013-02-23 05:52:46 +0200691class TestThreadState(unittest.TestCase):
692
Hai Shie80697d2020-05-28 06:10:27 +0800693 @threading_helper.reap_threads
Ezio Melotti29267c82013-02-23 05:52:46 +0200694 def test_thread_state(self):
695 # some extra thread-state tests driven via _testcapi
696 def target():
697 idents = []
698
699 def callback():
Ezio Melotti35246bd2013-02-23 05:58:38 +0200700 idents.append(threading.get_ident())
Ezio Melotti29267c82013-02-23 05:52:46 +0200701
702 _testcapi._test_thread_state(callback)
703 a = b = callback
704 time.sleep(1)
705 # Check our main thread is in the list exactly 3 times.
Ezio Melotti35246bd2013-02-23 05:58:38 +0200706 self.assertEqual(idents.count(threading.get_ident()), 3,
Ezio Melotti29267c82013-02-23 05:52:46 +0200707 "Couldn't find main thread correctly in the list")
708
709 target()
710 t = threading.Thread(target=target)
711 t.start()
712 t.join()
713
Victor Stinner34be8072016-03-14 12:04:26 +0100714
Zachary Warec12f09e2013-11-11 22:47:04 -0600715class Test_testcapi(unittest.TestCase):
Serhiy Storchaka8f7bb102018-08-06 16:50:19 +0300716 locals().update((name, getattr(_testcapi, name))
717 for name in dir(_testcapi)
718 if name.startswith('test_') and not name.endswith('_code'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000719
Inada Naoki902356a2020-07-20 12:02:50 +0900720 # Suppress warning from PyUnicode_FromUnicode().
721 @warnings_helper.ignore_warnings(category=DeprecationWarning)
722 def test_widechar(self):
723 _testcapi.test_widechar()
724
Victor Stinner34be8072016-03-14 12:04:26 +0100725
Victor Stinner1ae035b2020-04-17 17:47:20 +0200726class Test_testinternalcapi(unittest.TestCase):
727 locals().update((name, getattr(_testinternalcapi, name))
728 for name in dir(_testinternalcapi)
729 if name.startswith('test_'))
730
731
Victor Stinnerc4aec362016-03-14 22:26:53 +0100732class PyMemDebugTests(unittest.TestCase):
733 PYTHONMALLOC = 'debug'
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100734 # '0x04c06e0' or '04C06E0'
Victor Stinner08572f62016-03-14 21:55:43 +0100735 PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
Victor Stinner34be8072016-03-14 12:04:26 +0100736
737 def check(self, code):
738 with support.SuppressCrashReport():
Victor Stinnerc4aec362016-03-14 22:26:53 +0100739 out = assert_python_failure('-c', code,
740 PYTHONMALLOC=self.PYTHONMALLOC)
Victor Stinner34be8072016-03-14 12:04:26 +0100741 stderr = out.err
742 return stderr.decode('ascii', 'replace')
743
744 def test_buffer_overflow(self):
745 out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100746 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100747 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100748 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
749 r" The [0-9] pad bytes at tail={ptr} are not all FORBIDDENBYTE \(0x[0-9a-f]{{2}}\):\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100750 r" at tail\+0: 0x78 \*\*\* OUCH\n"
Victor Stinner4c409be2019-04-11 13:01:15 +0200751 r" at tail\+1: 0xfd\n"
752 r" at tail\+2: 0xfd\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100753 r" .*\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200754 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200755 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100756 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100757 r"Enable tracemalloc to get the memory block allocation traceback\n"
758 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100759 r"Fatal Python error: _PyMem_DebugRawFree: bad trailing pad byte")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100760 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100761 regex = re.compile(regex, flags=re.DOTALL)
Victor Stinner34be8072016-03-14 12:04:26 +0100762 self.assertRegex(out, regex)
763
764 def test_api_misuse(self):
765 out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100766 regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
Victor Stinner34be8072016-03-14 12:04:26 +0100767 r" 16 bytes originally requested\n"
Victor Stinnerb3adb1a2016-03-14 17:40:09 +0100768 r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
769 r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
Victor Stinnere8f9acf2019-04-12 21:54:06 +0200770 r"( The block was made by call #[0-9]+ to debug malloc/realloc.\n)?"
Victor Stinner4c409be2019-04-11 13:01:15 +0200771 r" Data at p: cd cd cd .*\n"
Victor Stinner6453e9e2016-03-15 23:36:28 +0100772 r"\n"
Victor Stinnerf966e532018-11-13 15:14:58 +0100773 r"Enable tracemalloc to get the memory block allocation traceback\n"
774 r"\n"
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100775 r"Fatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API 'm', verified using API 'r'\n")
Victor Stinnera1bc28a2016-03-14 17:10:36 +0100776 regex = regex.format(ptr=self.PTR_REGEX)
Victor Stinner34be8072016-03-14 12:04:26 +0100777 self.assertRegex(out, regex)
778
Victor Stinnerad524372016-03-16 12:12:53 +0100779 def check_malloc_without_gil(self, code):
Victor Stinnerc4aec362016-03-14 22:26:53 +0100780 out = self.check(code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100781 expected = ('Fatal Python error: _PyMem_DebugMalloc: '
782 'Python memory allocator called without holding the GIL')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100783 self.assertIn(expected, out)
Victor Stinner34be8072016-03-14 12:04:26 +0100784
Victor Stinnerad524372016-03-16 12:12:53 +0100785 def test_pymem_malloc_without_gil(self):
786 # Debug hooks must raise an error if PyMem_Malloc() is called
787 # without holding the GIL
788 code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
789 self.check_malloc_without_gil(code)
790
791 def test_pyobject_malloc_without_gil(self):
792 # Debug hooks must raise an error if PyObject_Malloc() is called
793 # without holding the GIL
794 code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
795 self.check_malloc_without_gil(code)
796
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200797 def check_pyobject_is_freed(self, func_name):
798 code = textwrap.dedent(f'''
Victor Stinner2b00db62019-04-11 11:33:27 +0200799 import gc, os, sys, _testcapi
800 # Disable the GC to avoid crash on GC collection
801 gc.disable()
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200802 try:
803 _testcapi.{func_name}()
804 # Exit immediately to avoid a crash while deallocating
805 # the invalid object
806 os._exit(0)
807 except _testcapi.error:
808 os._exit(1)
Victor Stinner2b00db62019-04-11 11:33:27 +0200809 ''')
Victor Stinner2b00db62019-04-11 11:33:27 +0200810 assert_python_ok('-c', code, PYTHONMALLOC=self.PYTHONMALLOC)
811
Victor Stinner68762572019-10-07 18:42:01 +0200812 def test_pyobject_null_is_freed(self):
813 self.check_pyobject_is_freed('check_pyobject_null_is_freed')
814
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200815 def test_pyobject_uninitialized_is_freed(self):
816 self.check_pyobject_is_freed('check_pyobject_uninitialized_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200817
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200818 def test_pyobject_forbidden_bytes_is_freed(self):
819 self.check_pyobject_is_freed('check_pyobject_forbidden_bytes_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200820
Victor Stinner3bf0f3a2019-06-07 16:22:21 +0200821 def test_pyobject_freed_is_freed(self):
822 self.check_pyobject_is_freed('check_pyobject_freed_is_freed')
Victor Stinner2b00db62019-04-11 11:33:27 +0200823
Victor Stinnerc4aec362016-03-14 22:26:53 +0100824
825class PyMemMallocDebugTests(PyMemDebugTests):
826 PYTHONMALLOC = 'malloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100827
828
Victor Stinner5d39e042017-11-29 17:20:38 +0100829@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100830class PyMemPymallocDebugTests(PyMemDebugTests):
831 PYTHONMALLOC = 'pymalloc_debug'
Victor Stinner34be8072016-03-14 12:04:26 +0100832
833
834@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
Victor Stinnerc4aec362016-03-14 22:26:53 +0100835class PyMemDefaultTests(PyMemDebugTests):
836 # test default allocator of Python compiled in debug mode
837 PYTHONMALLOC = ''
Victor Stinner34be8072016-03-14 12:04:26 +0100838
839
Petr Viktorine1becf42020-05-07 15:39:59 +0200840class Test_ModuleStateAccess(unittest.TestCase):
841 """Test access to module start (PEP 573)"""
842
843 # The C part of the tests lives in _testmultiphase, in a module called
844 # _testmultiphase_meth_state_access.
845 # This module has multi-phase initialization, unlike _testcapi.
846
847 def setUp(self):
848 fullname = '_testmultiphase_meth_state_access' # XXX
849 origin = importlib.util.find_spec('_testmultiphase').origin
850 loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
851 spec = importlib.util.spec_from_loader(fullname, loader)
852 module = importlib.util.module_from_spec(spec)
853 loader.exec_module(module)
854 self.module = module
855
856 def test_subclass_get_module(self):
857 """PyType_GetModule for defining_class"""
858 class StateAccessType_Subclass(self.module.StateAccessType):
859 pass
860
861 instance = StateAccessType_Subclass()
862 self.assertIs(instance.get_defining_module(), self.module)
863
864 def test_subclass_get_module_with_super(self):
865 class StateAccessType_Subclass(self.module.StateAccessType):
866 def get_defining_module(self):
867 return super().get_defining_module()
868
869 instance = StateAccessType_Subclass()
870 self.assertIs(instance.get_defining_module(), self.module)
871
872 def test_state_access(self):
873 """Checks methods defined with and without argument clinic
874
875 This tests a no-arg method (get_count) and a method with
876 both a positional and keyword argument.
877 """
878
879 a = self.module.StateAccessType()
880 b = self.module.StateAccessType()
881
882 methods = {
883 'clinic': a.increment_count_clinic,
884 'noclinic': a.increment_count_noclinic,
885 }
886
887 for name, increment_count in methods.items():
888 with self.subTest(name):
889 self.assertEqual(a.get_count(), b.get_count())
890 self.assertEqual(a.get_count(), 0)
891
892 increment_count()
893 self.assertEqual(a.get_count(), b.get_count())
894 self.assertEqual(a.get_count(), 1)
895
896 increment_count(3)
897 self.assertEqual(a.get_count(), b.get_count())
898 self.assertEqual(a.get_count(), 4)
899
900 increment_count(-2, twice=True)
901 self.assertEqual(a.get_count(), b.get_count())
902 self.assertEqual(a.get_count(), 0)
903
904 with self.assertRaises(TypeError):
905 increment_count(thrice=3)
906
907 with self.assertRaises(TypeError):
908 increment_count(1, 2, 3)
909
910
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000911if __name__ == "__main__":
Zachary Warec12f09e2013-11-11 22:47:04 -0600912 unittest.main()