]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-116303: Skip test module dependent tests if test modules are unavailable (#117341)
authorErlend E. Aasland <erlend@python.org>
Wed, 3 Apr 2024 13:11:36 +0000 (15:11 +0200)
committerGitHub <noreply@github.com>
Wed, 3 Apr 2024 13:11:36 +0000 (15:11 +0200)
57 files changed:
Lib/test/support/__init__.py
Lib/test/test_audit.py
Lib/test/test_call.py
Lib/test/test_capi/__init__.py
Lib/test/test_code.py
Lib/test/test_coroutines.py
Lib/test/test_ctypes/test_as_parameter.py
Lib/test/test_ctypes/test_bitfields.py
Lib/test/test_ctypes/test_callbacks.py
Lib/test/test_ctypes/test_cfuncs.py
Lib/test/test_ctypes/test_checkretval.py
Lib/test/test_ctypes/test_funcptr.py
Lib/test/test_ctypes/test_functions.py
Lib/test/test_ctypes/test_libc.py
Lib/test/test_ctypes/test_loading.py
Lib/test/test_ctypes/test_parameters.py
Lib/test/test_ctypes/test_pickling.py
Lib/test/test_ctypes/test_pointers.py
Lib/test/test_ctypes/test_prototypes.py
Lib/test/test_ctypes/test_refcounts.py
Lib/test/test_ctypes/test_returnfuncptrs.py
Lib/test/test_ctypes/test_slicing.py
Lib/test/test_ctypes/test_stringptr.py
Lib/test/test_ctypes/test_structures.py
Lib/test/test_ctypes/test_unicode.py
Lib/test/test_ctypes/test_values.py
Lib/test/test_ctypes/test_win32.py
Lib/test/test_embed.py
Lib/test/test_exceptions.py
Lib/test/test_external_inspection.py
Lib/test/test_faulthandler.py
Lib/test/test_fcntl.py
Lib/test/test_fileio.py
Lib/test/test_finalization.py
Lib/test/test_format.py
Lib/test/test_gc.py
Lib/test/test_genericclass.py
Lib/test/test_import/__init__.py
Lib/test/test_importlib/util.py
Lib/test/test_inspect/test_inspect.py
Lib/test/test_monitoring.py
Lib/test/test_multibytecodec.py
Lib/test/test_opcache.py
Lib/test/test_os.py
Lib/test/test_perfmaps.py
Lib/test/test_poll.py
Lib/test/test_pydoc/test_pydoc.py
Lib/test/test_regrtest.py
Lib/test/test_repl.py
Lib/test/test_socket.py
Lib/test/test_sqlite3/test_dbapi.py
Lib/test/test_stable_abi_ctypes.py
Lib/test/test_sys.py
Lib/test/test_threading.py
Lib/test/test_tools/test_makefile.py
Lib/test/test_weakref.py
Tools/build/stable_abi.py

index 9640d5d831b874082f243b8ca8db17945f0ed143..d7bc416ab04086fccaa4e445dcd0709cf4c87f18 100644 (file)
@@ -1168,6 +1168,10 @@ def requires_limited_api(test):
         return unittest.skip('needs _testcapi and _testlimitedcapi modules')(test)
     return test
 
+
+TEST_MODULES_ENABLED = sysconfig.get_config_var('TEST_MODULES') == 'yes'
+
+
 def requires_specialization(test):
     return unittest.skipUnless(
         _opcode.ENABLE_SPECIALIZATION, "requires specialization")(test)
index c24c8213924196f0893c131faaed2850ce113c32..e163c7ad25cc7bba1852f0db9eedb887f530efbc 100644 (file)
@@ -89,6 +89,7 @@ class AuditTest(unittest.TestCase):
         )
 
     def test_unraisablehook(self):
+        import_helper.import_module("_testcapi")
         returncode, events, stderr = self.run_python("test_unraisablehook")
         if returncode:
             self.fail(stderr)
index eaf919584b4c64cb808e6ceaa55e62b57d8533b6..d3f4d6c29c553675d62fc7d0db8fd70c53bef5ea 100644 (file)
@@ -1,6 +1,6 @@
 import unittest
 from test.support import (cpython_only, is_wasi, requires_limited_api, Py_DEBUG,
-                          set_recursion_limit, skip_on_s390x)
+                          set_recursion_limit, skip_on_s390x, import_helper)
 try:
     import _testcapi
 except ImportError:
@@ -244,6 +244,7 @@ class CFunctionCallsErrorMessages(unittest.TestCase):
         self.assertRaisesRegex(TypeError, msg, mod)
 
 
+@unittest.skipIf(_testcapi is None, "requires _testcapi")
 class TestCallingConventions(unittest.TestCase):
     """Test calling using various C calling conventions (METH_*) from Python
 
@@ -441,6 +442,7 @@ PYTHON_INSTANCE = PythonClass()
 
 NULL_OR_EMPTY = object()
 
+
 class FastCallTests(unittest.TestCase):
     """Test calling using various callables from C
     """
@@ -484,42 +486,43 @@ class FastCallTests(unittest.TestCase):
     ]
 
     # Add all the calling conventions and variants of C callables
-    _instance = _testcapi.MethInstance()
-    for obj, expected_self in (
-        (_testcapi, _testcapi),  # module-level function
-        (_instance, _instance),  # bound method
-        (_testcapi.MethClass, _testcapi.MethClass),  # class method on class
-        (_testcapi.MethClass(), _testcapi.MethClass),  # class method on inst.
-        (_testcapi.MethStatic, None),  # static method
-    ):
-        CALLS_POSARGS.extend([
-            (obj.meth_varargs, (1, 2), (expected_self, (1, 2))),
-            (obj.meth_varargs_keywords,
-                (1, 2), (expected_self, (1, 2), NULL_OR_EMPTY)),
-            (obj.meth_fastcall, (1, 2), (expected_self, (1, 2))),
-            (obj.meth_fastcall, (), (expected_self, ())),
-            (obj.meth_fastcall_keywords,
-                (1, 2), (expected_self, (1, 2), NULL_OR_EMPTY)),
-            (obj.meth_fastcall_keywords,
-                (), (expected_self, (), NULL_OR_EMPTY)),
-            (obj.meth_noargs, (), expected_self),
-            (obj.meth_o, (123, ), (expected_self, 123)),
-        ])
-
-        CALLS_KWARGS.extend([
-            (obj.meth_varargs_keywords,
-                (1, 2), {'x': 'y'}, (expected_self, (1, 2), {'x': 'y'})),
-            (obj.meth_varargs_keywords,
-                (), {'x': 'y'}, (expected_self, (), {'x': 'y'})),
-            (obj.meth_varargs_keywords,
-                (1, 2), {}, (expected_self, (1, 2), NULL_OR_EMPTY)),
-            (obj.meth_fastcall_keywords,
-                (1, 2), {'x': 'y'}, (expected_self, (1, 2), {'x': 'y'})),
-            (obj.meth_fastcall_keywords,
-                (), {'x': 'y'}, (expected_self, (), {'x': 'y'})),
-            (obj.meth_fastcall_keywords,
-                (1, 2), {}, (expected_self, (1, 2), NULL_OR_EMPTY)),
-        ])
+    if _testcapi:
+        _instance = _testcapi.MethInstance()
+        for obj, expected_self in (
+            (_testcapi, _testcapi),  # module-level function
+            (_instance, _instance),  # bound method
+            (_testcapi.MethClass, _testcapi.MethClass),  # class method on class
+            (_testcapi.MethClass(), _testcapi.MethClass),  # class method on inst.
+            (_testcapi.MethStatic, None),  # static method
+        ):
+            CALLS_POSARGS.extend([
+                (obj.meth_varargs, (1, 2), (expected_self, (1, 2))),
+                (obj.meth_varargs_keywords,
+                    (1, 2), (expected_self, (1, 2), NULL_OR_EMPTY)),
+                (obj.meth_fastcall, (1, 2), (expected_self, (1, 2))),
+                (obj.meth_fastcall, (), (expected_self, ())),
+                (obj.meth_fastcall_keywords,
+                    (1, 2), (expected_self, (1, 2), NULL_OR_EMPTY)),
+                (obj.meth_fastcall_keywords,
+                    (), (expected_self, (), NULL_OR_EMPTY)),
+                (obj.meth_noargs, (), expected_self),
+                (obj.meth_o, (123, ), (expected_self, 123)),
+            ])
+
+            CALLS_KWARGS.extend([
+                (obj.meth_varargs_keywords,
+                    (1, 2), {'x': 'y'}, (expected_self, (1, 2), {'x': 'y'})),
+                (obj.meth_varargs_keywords,
+                    (), {'x': 'y'}, (expected_self, (), {'x': 'y'})),
+                (obj.meth_varargs_keywords,
+                    (1, 2), {}, (expected_self, (1, 2), NULL_OR_EMPTY)),
+                (obj.meth_fastcall_keywords,
+                    (1, 2), {'x': 'y'}, (expected_self, (1, 2), {'x': 'y'})),
+                (obj.meth_fastcall_keywords,
+                    (), {'x': 'y'}, (expected_self, (), {'x': 'y'})),
+                (obj.meth_fastcall_keywords,
+                    (1, 2), {}, (expected_self, (1, 2), NULL_OR_EMPTY)),
+            ])
 
     def check_result(self, result, expected):
         if isinstance(expected, tuple) and expected[-1] is NULL_OR_EMPTY:
@@ -527,6 +530,7 @@ class FastCallTests(unittest.TestCase):
                 expected = (*expected[:-1], result[-1])
         self.assertEqual(result, expected)
 
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_vectorcall_dict(self):
         # Test PyObject_VectorcallDict()
 
@@ -546,6 +550,7 @@ class FastCallTests(unittest.TestCase):
                 result = _testcapi.pyobject_fastcalldict(func, args, kwargs)
                 self.check_result(result, expected)
 
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_vectorcall(self):
         # Test PyObject_Vectorcall()
 
@@ -610,6 +615,7 @@ def testfunction_kw(self, *, kw):
 ADAPTIVE_WARMUP_DELAY = 2
 
 
+@unittest.skipIf(_testcapi is None, "requires _testcapi")
 class TestPEP590(unittest.TestCase):
 
     def test_method_descriptor_flag(self):
@@ -1022,6 +1028,7 @@ class TestRecursion(unittest.TestCase):
 
     @skip_on_s390x
     @unittest.skipIf(is_wasi and Py_DEBUG, "requires deep stack")
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_super_deep(self):
 
         def recurse(n):
index 4b16ecc31156a512db4a28fe272e5339994a4538..5a8ba6845399e03bd3b2739fcde7eb98e9db5fbb 100644 (file)
@@ -1,5 +1,12 @@
 import os
+import unittest
 from test.support import load_package_tests
+from test.support import TEST_MODULES_ENABLED
+
+
+if not TEST_MODULES_ENABLED:
+    raise unittest.SkipTest("requires test modules")
+
 
 def load_tests(*args):
     return load_package_tests(os.path.dirname(__file__), *args)
index 46bebfc7af675b157e17fec912ae27b271728d6e..ecd1e82a6dbef9e22af5798cab6968bb7303b44a 100644 (file)
@@ -143,9 +143,8 @@ from test.support import (cpython_only,
                           check_impl_detail, requires_debug_ranges,
                           gc_collect)
 from test.support.script_helper import assert_python_ok
-from test.support import threading_helper
-from test.support.bytecode_helper import (BytecodeTestCase,
-                                          instructions_with_positions)
+from test.support import threading_helper, import_helper
+from test.support.bytecode_helper import instructions_with_positions
 from opcode import opmap, opname
 COPY_FREE_VARS = opmap['COPY_FREE_VARS']
 
@@ -176,7 +175,7 @@ class CodeTest(unittest.TestCase):
 
     @cpython_only
     def test_newempty(self):
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         co = _testcapi.code_newempty("filename", "funcname", 15)
         self.assertEqual(co.co_filename, "filename")
         self.assertEqual(co.co_name, "funcname")
index d848bfbd46c83bded033d0a767eb15e878268824..f705f4f5bfbd8848502184097245da8558eb7150 100644 (file)
@@ -11,6 +11,10 @@ from test import support
 from test.support import import_helper
 from test.support import warnings_helper
 from test.support.script_helper import assert_python_ok
+try:
+    import _testcapi
+except ImportError:
+    _testcapi = None
 
 
 class AsyncYieldFrom:
@@ -2445,6 +2449,7 @@ class UnawaitedWarningDuringShutdownTest(unittest.TestCase):
 
 
 @support.cpython_only
+@unittest.skipIf(_testcapi is None, "requires _testcapi")
 class CAPITest(unittest.TestCase):
 
     def test_tp_await_1(self):
index ca75e748256083b4983539f5791e12380c23ad98..cc62b1a22a3b0614e1d471d976f8a191f7ae1123 100644 (file)
@@ -1,4 +1,3 @@
-import _ctypes_test
 import ctypes
 import unittest
 from ctypes import (Structure, CDLL, CFUNCTYPE,
@@ -6,6 +5,8 @@ from ctypes import (Structure, CDLL, CFUNCTYPE,
                     c_short, c_int, c_long, c_longlong,
                     c_byte, c_wchar, c_float, c_double,
                     ArgumentError)
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 dll = CDLL(_ctypes_test.__file__)
index d43c56ad371fbd350fb549c0b73e0e9d52a75579..0332544b5827e6c1015f11beac1c206de7029c1d 100644 (file)
@@ -1,4 +1,3 @@
-import _ctypes_test
 import os
 import unittest
 from ctypes import (CDLL, Structure, sizeof, POINTER, byref, alignment,
@@ -7,6 +6,8 @@ from ctypes import (CDLL, Structure, sizeof, POINTER, byref, alignment,
                     c_uint32, c_uint64,
                     c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong)
 from test import support
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 class BITS(Structure):
index 8038169afe4304d5bb44ad51723b525e69c2be6f..8f483dfe1db801960152c0e32bbc50e7b482d156 100644 (file)
@@ -1,4 +1,3 @@
-import _ctypes_test
 import ctypes
 import functools
 import gc
@@ -14,6 +13,8 @@ from ctypes import (CDLL, cdll, Structure, CFUNCTYPE,
                     c_float, c_double, c_longdouble, py_object)
 from ctypes.util import find_library
 from test import support
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 class Callbacks(unittest.TestCase):
index 6ff0878a35da2f0ac5018b9d0c1cf49aac20fc96..48330c4b0a763bf6545cf80c4ba7e4dc7d848754 100644 (file)
@@ -1,4 +1,3 @@
-import _ctypes_test
 import ctypes
 import unittest
 from ctypes import (CDLL,
@@ -6,6 +5,8 @@ from ctypes import (CDLL,
                     c_short, c_ushort, c_int, c_uint,
                     c_long, c_ulong, c_longlong, c_ulonglong,
                     c_float, c_double, c_longdouble)
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 class CFunctions(unittest.TestCase):
index 5dc9e25aa38226d328b40d8bef513049f42d14b1..9d6bfdb845e6c797f7a7498dd56a2e4e6bca65b1 100644 (file)
@@ -1,7 +1,8 @@
-import _ctypes_test
 import ctypes
 import unittest
 from ctypes import CDLL, c_int
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 class CHECKED(c_int):
index 03cfddea6ea61a90078aa286c0ea0b8f1e4bc214..8362fb16d94dcd1dc300d036fa3ab3f007ab76e6 100644 (file)
@@ -1,8 +1,9 @@
-import _ctypes_test
 import ctypes
 import unittest
 from ctypes import (CDLL, Structure, CFUNCTYPE, sizeof, _CFuncPtr,
                     c_void_p, c_char_p, c_char, c_int, c_uint, c_long)
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 from ._support import (_CData, PyCFuncPtrType, Py_TPFLAGS_DISALLOW_INSTANTIATION,
                        Py_TPFLAGS_IMMUTABLETYPE)
 
index 04e8582ff1e427197729b127fc5a8c1a43c11f9f..63e393f7b7cb6a337af9fb87ca479b01e8292524 100644 (file)
@@ -1,4 +1,3 @@
-import _ctypes_test
 import ctypes
 import sys
 import unittest
@@ -7,6 +6,8 @@ from ctypes import (CDLL, Structure, Array, CFUNCTYPE,
                     c_char, c_wchar, c_byte, c_char_p, c_wchar_p,
                     c_short, c_int, c_long, c_longlong, c_void_p,
                     c_float, c_double, c_longdouble)
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 from _ctypes import _Pointer,  _SimpleCData
 
 
index 09c76db0bd0b174fb4ea54e97c42d6829b8a40ad..7716100b08f78e49de94f1e6b7fb77bb8343e94f 100644 (file)
@@ -1,8 +1,9 @@
-import _ctypes_test
 import math
 import unittest
 from ctypes import (CDLL, CFUNCTYPE, POINTER, create_string_buffer, sizeof,
                     c_void_p, c_char, c_int, c_double, c_size_t)
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 lib = CDLL(_ctypes_test.__file__)
index b218e9e7720c79abe66bf1f90caac622537a61e6..b25e81b65cf10334e117be82ba772e88aaf0fc6d 100644 (file)
@@ -1,5 +1,4 @@
 import _ctypes
-import _ctypes_test
 import ctypes
 import os
 import shutil
@@ -10,6 +9,7 @@ import unittest
 from ctypes import CDLL, cdll, addressof, c_void_p, c_char_p
 from ctypes.util import find_library
 from test.support import import_helper, os_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 libc_name = None
index d1eeee6b0306fea6c8046780a82161bef212726c..effb8db418f7908c4826bcb2337929497b9073eb 100644 (file)
@@ -1,4 +1,3 @@
-import _ctypes_test
 import unittest
 import test.support
 from ctypes import (CDLL, PyDLL, ArgumentError,
@@ -14,6 +13,8 @@ from ctypes import (CDLL, PyDLL, ArgumentError,
                     c_long, c_ulong,
                     c_longlong, c_ulonglong,
                     c_float, c_double, c_longdouble)
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 class SimpleTypesTestCase(unittest.TestCase):
index 0ca42a68f0675f952b5ed7d5d9c24dd859aad7f5..9d433fc69de3912647cc2caadeeae69823248d8f 100644 (file)
@@ -1,9 +1,10 @@
-import _ctypes_test
 import pickle
 import unittest
 from ctypes import (CDLL, Structure, CFUNCTYPE, pointer,
                     c_void_p, c_char_p, c_wchar_p,
                     c_char, c_wchar, c_int, c_double)
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 dll = CDLL(_ctypes_test.__file__)
index 3a5f3660dbbe239614b282e50496b169b43bf4b7..fc558e10ba40c57344b082b89e4a26115a0322f7 100644 (file)
@@ -1,4 +1,3 @@
-import _ctypes_test
 import array
 import ctypes
 import sys
@@ -10,6 +9,8 @@ from ctypes import (CDLL, CFUNCTYPE, Structure,
                     c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint,
                     c_long, c_ulong, c_longlong, c_ulonglong,
                     c_float, c_double)
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 from ._support import (_CData, PyCPointerType, Py_TPFLAGS_DISALLOW_INSTANTIATION,
                        Py_TPFLAGS_IMMUTABLETYPE)
 
index 81eb4562c740fd633c3f85e78662fe57e1039275..63ae799ea86ab2d62cfff525e8d9bb0981de6f57 100644 (file)
 #
 # In this case, there would have to be an additional reference to the argument...
 
-import _ctypes_test
 import unittest
 from ctypes import (CDLL, CFUNCTYPE, POINTER, ArgumentError,
                     pointer, byref, sizeof, addressof, create_string_buffer,
                     c_void_p, c_char_p, c_wchar_p, c_char, c_wchar,
                     c_short, c_int, c_long, c_longlong, c_double)
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 testdll = CDLL(_ctypes_test.__file__)
index a90588ca9bb1b6c627c09d50007c46e2bb005578..e6427d4a295b15c1d3466a45b368e61f37d8932a 100644 (file)
@@ -1,9 +1,10 @@
-import _ctypes_test
 import ctypes
 import gc
 import sys
 import unittest
 from test import support
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
index 4010e511e75ade687f9b900649c2d2dd3604b612..337801b226ab06ba79e7ccd2ac6d671f92cc950b 100644 (file)
@@ -1,6 +1,7 @@
-import _ctypes_test
 import unittest
 from ctypes import CDLL, CFUNCTYPE, ArgumentError, c_char_p, c_void_p, c_char
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 class ReturnFuncPtrTestCase(unittest.TestCase):
index a592d911cbe6ca98012907782b8422b3c513fd24..66f9e530104cacc3504772a6bf74fe9438a9880a 100644 (file)
@@ -1,7 +1,8 @@
-import _ctypes_test
 import unittest
 from ctypes import (CDLL, POINTER, sizeof,
                     c_byte, c_short, c_int, c_long, c_char, c_wchar, c_char_p)
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 class SlicesTestCase(unittest.TestCase):
index 67c61c6c3e17e639328ccff223a14f8ca3545e71..bb6045b250ffce2358cc977c82c233b28d2d0e00 100644 (file)
@@ -1,9 +1,10 @@
-import _ctypes_test
 import sys
 import unittest
 from test import support
 from ctypes import (CDLL, Structure, POINTER, create_string_buffer,
                     c_char, c_char_p)
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 lib = CDLL(_ctypes_test.__file__)
index 8d83ce4f281b169cca0e3749429d86cb767d25fe..7650c80273f812446c9adda126ef07bf4618d5db 100644 (file)
@@ -1,4 +1,3 @@
-import _ctypes_test
 from platform import architecture as _architecture
 import struct
 import sys
@@ -12,6 +11,8 @@ from ctypes.util import find_library
 from struct import calcsize
 from collections import namedtuple
 from test import support
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 from ._support import (_CData, PyCStructType, Py_TPFLAGS_DISALLOW_INSTANTIATION,
                        Py_TPFLAGS_IMMUTABLETYPE)
 
index 2ddc7c56544e3513277a9629cd3f13210fa8688d..d9e17371d1357246edd735a39ae2dc5cfe760b72 100644 (file)
@@ -1,6 +1,7 @@
-import _ctypes_test
 import ctypes
 import unittest
+from test.support import import_helper
+_ctypes_test = import_helper.import_module("_ctypes_test")
 
 
 class UnicodeTestCase(unittest.TestCase):
index d0b4803dff8529a84bdedf64d218e57f8f9b8203..1b757e020d5ce28ff0cc915cbd7f9b52f2d2533d 100644 (file)
@@ -2,7 +2,6 @@
 A testcase which accesses *values* in a dll.
 """
 
-import _ctypes_test
 import _imp
 import importlib.util
 import sys
@@ -15,10 +14,14 @@ from test.support import import_helper
 
 class ValuesTestCase(unittest.TestCase):
 
+    def setUp(self):
+        _ctypes_test = import_helper.import_module("_ctypes_test")
+        self.ctdll = CDLL(_ctypes_test.__file__)
+
     def test_an_integer(self):
         # This test checks and changes an integer stored inside the
         # _ctypes_test dll/shared lib.
-        ctdll = CDLL(_ctypes_test.__file__)
+        ctdll = self.ctdll
         an_integer = c_int.in_dll(ctdll, "an_integer")
         x = an_integer.value
         self.assertEqual(x, ctdll.get_an_integer())
@@ -30,8 +33,7 @@ class ValuesTestCase(unittest.TestCase):
         self.assertEqual(x, ctdll.get_an_integer())
 
     def test_undefined(self):
-        ctdll = CDLL(_ctypes_test.__file__)
-        self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol")
+        self.assertRaises(ValueError, c_int.in_dll, self.ctdll, "Undefined_Symbol")
 
 
 class PythonValuesTestCase(unittest.TestCase):
index 4aaecd8d38f98f4c4158e65ce7eccf2f7f09a518..31919118670613e17da43463c11b8e8841093009 100644 (file)
@@ -1,6 +1,5 @@
 # Windows specific tests
 
-import _ctypes_test
 import ctypes
 import errno
 import sys
@@ -9,6 +8,7 @@ from ctypes import (CDLL, Structure, POINTER, pointer, sizeof, byref,
                     _pointer_type_cache,
                     c_void_p, c_char, c_int, c_long)
 from test import support
+from test.support import import_helper
 from ._support import Py_TPFLAGS_DISALLOW_INSTANTIATION, Py_TPFLAGS_IMMUTABLETYPE
 
 
@@ -36,6 +36,7 @@ class FunctionCallTestCase(unittest.TestCase):
 @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test')
 class ReturnStructSizesTestCase(unittest.TestCase):
     def test_sizes(self):
+        _ctypes_test = import_helper.import_module("_ctypes_test")
         dll = CDLL(_ctypes_test.__file__)
         for i in range(1, 11):
             fields = [ (f"f{f}", c_char) for f in range(1, i + 1)]
@@ -116,6 +117,7 @@ class Structures(unittest.TestCase):
                         ("right", c_long),
                         ("bottom", c_long)]
 
+        _ctypes_test = import_helper.import_module("_ctypes_test")
         dll = CDLL(_ctypes_test.__file__)
 
         pt = POINT(15, 25)
index ab1d579ed12755e9ea4105db7f272211e8b10763..ec928f935655f9030afcb8f639afb0048f95e9a3 100644 (file)
@@ -19,6 +19,13 @@ import textwrap
 if not support.has_subprocess_support:
     raise unittest.SkipTest("test module requires subprocess")
 
+
+try:
+    import _testinternalcapi
+except ImportError:
+    _testinternalcapi = None
+
+
 MACOS = (sys.platform == 'darwin')
 PYMEM_ALLOCATOR_NOT_SET = 0
 PYMEM_ALLOCATOR_DEBUG = 2
@@ -352,6 +359,7 @@ class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
         self.assertEqual(out, 'Finalized\n' * INIT_LOOPS)
 
     @support.requires_specialization
+    @unittest.skipUnless(support.TEST_MODULES_ENABLED, "requires test modules")
     def test_specialized_static_code_gets_unspecialized_at_Py_FINALIZE(self):
         # https://github.com/python/cpython/issues/92031
 
@@ -396,6 +404,8 @@ class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
         out, err = self.run_embedded_interpreter("test_repeated_init_exec", code)
         self.assertEqual(out, '9\n' * INIT_LOOPS)
 
+
+@unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
 class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
     maxDiff = 4096
     UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape')
@@ -1588,7 +1598,6 @@ class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
         # The global path configuration (_Py_path_config) must be a copy
         # of the path configuration of PyInterpreter.config (PyConfig).
         ctypes = import_helper.import_module('ctypes')
-        _testinternalcapi = import_helper.import_module('_testinternalcapi')
 
         def get_func(name):
             func = getattr(ctypes.pythonapi, name)
@@ -1784,6 +1793,7 @@ class MiscTests(EmbeddingTestsMixin, unittest.TestCase):
     # See bpo-44133
     @unittest.skipIf(os.name == 'nt',
                      'Py_FrozenMain is not exported on Windows')
+    @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
     def test_frozenmain(self):
         env = dict(os.environ)
         env['PYTHONUNBUFFERED'] = '1'
index c5eff8ad8ccca172cec24fa9add44d201d8b0944..6ad6acc61563e529ac690f1bc0095d8ebc28c869 100644 (file)
@@ -19,12 +19,13 @@ from test.support.warnings_helper import check_warnings
 from test import support
 
 try:
+    import _testcapi
     from _testcapi import INT_MAX
 except ImportError:
+    _testcapi = None
     INT_MAX = 2**31 - 1
 
 
-
 class NaiveException(Exception):
     def __init__(self, x):
         self.x = x
@@ -345,8 +346,8 @@ class ExceptionTests(unittest.TestCase):
         class InvalidException:
             pass
 
+        @unittest.skipIf(_testcapi is None, "requires _testcapi")
         def test_capi1():
-            import _testcapi
             try:
                 _testcapi.raise_exception(BadException, 1)
             except TypeError as err:
@@ -356,8 +357,8 @@ class ExceptionTests(unittest.TestCase):
             else:
                 self.fail("Expected exception")
 
+        @unittest.skipIf(_testcapi is None, "requires _testcapi")
         def test_capi2():
-            import _testcapi
             try:
                 _testcapi.raise_exception(BadException, 0)
             except RuntimeError as err:
@@ -370,8 +371,8 @@ class ExceptionTests(unittest.TestCase):
             else:
                 self.fail("Expected exception")
 
+        @unittest.skipIf(_testcapi is None, "requires _testcapi")
         def test_capi3():
-            import _testcapi
             self.assertRaises(SystemError, _testcapi.raise_exception,
                               InvalidException, 1)
 
@@ -1381,6 +1382,7 @@ class ExceptionTests(unittest.TestCase):
 
     @cpython_only
     def test_recursion_normalizing_exception(self):
+        import_module("_testinternalcapi")
         # Issue #22898.
         # Test that a RecursionError is raised when tstate->recursion_depth is
         # equal to recursion_limit in PyErr_NormalizeException() and check
@@ -1435,6 +1437,7 @@ class ExceptionTests(unittest.TestCase):
         self.assertIn(b'Done.', out)
 
     @cpython_only
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_recursion_normalizing_infinite_exception(self):
         # Issue #30697. Test that a RecursionError is raised when
         # maximum recursion depth has been exceeded when creating
@@ -1503,6 +1506,7 @@ class ExceptionTests(unittest.TestCase):
     # Python built with Py_TRACE_REFS fail with a fatal error in
     # _PyRefchain_Trace() on memory allocation error.
     @unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build')
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_recursion_normalizing_with_no_memory(self):
         # Issue #30697. Test that in the abort that occurs when there is no
         # memory left and the size of the Python frames stack is greater than
@@ -1525,6 +1529,7 @@ class ExceptionTests(unittest.TestCase):
             self.assertIn(b'MemoryError', err)
 
     @cpython_only
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_MemoryError(self):
         # PyErr_NoMemory always raises the same exception instance.
         # Check that the traceback is not doubled.
@@ -1544,8 +1549,8 @@ class ExceptionTests(unittest.TestCase):
         self.assertEqual(tb1, tb2)
 
     @cpython_only
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_exception_with_doc(self):
-        import _testcapi
         doc2 = "This is a test docstring."
         doc4 = "This is another test docstring."
 
@@ -1584,6 +1589,7 @@ class ExceptionTests(unittest.TestCase):
         self.assertEqual(error5.__doc__, "")
 
     @cpython_only
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_memory_error_cleanup(self):
         # Issue #5437: preallocated MemoryError instances should not keep
         # traceback objects alive.
@@ -1674,6 +1680,7 @@ class ExceptionTests(unittest.TestCase):
     # Python built with Py_TRACE_REFS fail with a fatal error in
     # _PyRefchain_Trace() on memory allocation error.
     @unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build')
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_memory_error_in_PyErr_PrintEx(self):
         code = """if 1:
             import _testcapi
@@ -1792,6 +1799,7 @@ class ExceptionTests(unittest.TestCase):
 
             gc_collect()
 
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_memory_error_in_subinterp(self):
         # gh-109894: subinterpreters shouldn't count on last resort memory error
         # when MemoryError is raised through PyErr_NoMemory() call,
index 86c07de507e39cbbbcf24d1032717dacee0848df..d896fec73d19719b2857b7247d8f8506b4f74b29 100644 (file)
@@ -14,7 +14,7 @@ try:
     from _testexternalinspection import PROCESS_VM_READV_SUPPORTED
     from _testexternalinspection import get_stack_trace
 except ImportError:
-    unittest.skip("Test only runs when _testexternalinspection is available")
+    raise unittest.SkipTest("Test only runs when _testexternalinspection is available")
 
 def _make_test_script(script_dir, script_basename, source):
     to_return = make_script(script_dir, script_basename, source)
index d0473500a177357c3c088e3c304bcbbe3f519d04..200f34d18ca60a603e2749e30e1d8bda8e801092 100644 (file)
@@ -266,6 +266,7 @@ class FaultHandlerTests(unittest.TestCase):
             5,
             'Illegal instruction')
 
+    @unittest.skipIf(_testcapi is None, 'need _testcapi')
     def check_fatal_error_func(self, release_gil):
         # Test that Py_FatalError() dumps a traceback
         with support.SuppressCrashReport():
index 5fae0de7423c878124dfe47c13924e9439e5d22b..84c0e5bc4800a1f890c9accfd23948b27daa7b4a 100644 (file)
@@ -117,7 +117,9 @@ class TestFcntl(unittest.TestCase):
 
     @cpython_only
     def test_fcntl_bad_file_overflow(self):
-        from _testcapi import INT_MAX, INT_MIN
+        _testcapi = import_module("_testcapi")
+        INT_MAX = _testcapi.INT_MAX
+        INT_MIN = _testcapi.INT_MIN
         # Issue 15989
         with self.assertRaises(OverflowError):
             fcntl.fcntl(INT_MAX + 1, fcntl.F_SETFL, os.O_NONBLOCK)
@@ -189,7 +191,7 @@ class TestFcntl(unittest.TestCase):
 
     @cpython_only
     def test_flock_overflow(self):
-        import _testcapi
+        _testcapi = import_module("_testcapi")
         self.assertRaises(OverflowError, fcntl.flock, _testcapi.INT_MAX+1,
                           fcntl.LOCK_SH)
 
index 06d5a8abf320835dbed1080d45043b49c7d90498..0611d1749f41c156cab8c517d783385c2af56a3d 100644 (file)
@@ -17,6 +17,7 @@ from test.support.os_helper import (
     TESTFN, TESTFN_ASCII, TESTFN_UNICODE, make_bad_fd,
     )
 from test.support.warnings_helper import check_warnings
+from test.support.import_helper import import_module
 from collections import UserList
 
 import _io  # C implementation of io
@@ -597,7 +598,7 @@ class COtherFileTests(OtherFileTests, unittest.TestCase):
     @cpython_only
     def testInvalidFd_overflow(self):
         # Issue 15989
-        import _testcapi
+        _testcapi = import_module("_testcapi")
         self.assertRaises(TypeError, self.FileIO, _testcapi.INT_MAX + 1)
         self.assertRaises(TypeError, self.FileIO, _testcapi.INT_MIN - 1)
 
index 1d134430909d8487b5beb939515bce61e82a6093..42871f8a09b16bb6158c0b2f837132cc6272b697 100644 (file)
@@ -13,7 +13,7 @@ except ImportError:
     def with_tp_del(cls):
         class C(object):
             def __new__(cls, *args, **kwargs):
-                raise TypeError('requires _testcapi.with_tp_del')
+                raise unittest.SkipTest('requires _testcapi.with_tp_del')
         return C
 
 try:
@@ -22,7 +22,7 @@ except ImportError:
     def without_gc(cls):
         class C:
             def __new__(cls, *args, **kwargs):
-                raise TypeError('requires _testcapi.without_gc')
+                raise unittest.SkipTest('requires _testcapi.without_gc')
         return C
 
 from test import support
index 6fa49dbc0b730ca8380f0c804e0faa22534ea566..8cef621bd716aca6076859282d7e1550285f2969 100644 (file)
@@ -4,6 +4,7 @@ import sys
 import re
 import test.support as support
 import unittest
+from test.support.import_helper import import_module
 
 maxsize = support.MAX_Py_ssize_t
 
@@ -478,7 +479,8 @@ class FormatTest(unittest.TestCase):
 
     @support.cpython_only
     def test_precision_c_limits(self):
-        from _testcapi import INT_MAX
+        _testcapi = import_module("_testcapi")
+        INT_MAX = _testcapi.INT_MAX
 
         f = 1.2
         with self.assertRaises(ValueError) as cm:
index fa8e50fccb2c7b4c9ad72324cc545ded86771731..3a01013b7710821528b60ddc95cccd5e6c9b617e 100644 (file)
@@ -16,17 +16,16 @@ import time
 import weakref
 
 try:
+    import _testcapi
     from _testcapi import with_tp_del
+    from _testcapi import ContainerNoGC
 except ImportError:
+    _testcapi = None
     def with_tp_del(cls):
         class C(object):
             def __new__(cls, *args, **kwargs):
-                raise TypeError('requires _testcapi.with_tp_del')
+                raise unittest.SkipTest('requires _testcapi.with_tp_del')
         return C
-
-try:
-    from _testcapi import ContainerNoGC
-except ImportError:
     ContainerNoGC = None
 
 ### Support code
@@ -681,6 +680,7 @@ class GCTests(unittest.TestCase):
 
     @cpython_only
     @requires_subprocess()
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_garbage_at_shutdown(self):
         import subprocess
         code = """if 1:
index aece757fc1933ec9022f7502f0b179fa62b4d082..e530b463966819adf2e0702fb669169eff88c111 100644 (file)
@@ -1,5 +1,6 @@
 import unittest
 from test import support
+from test.support.import_helper import import_module
 
 
 class TestMROEntry(unittest.TestCase):
@@ -277,7 +278,9 @@ class TestClassGetitem(unittest.TestCase):
 class CAPITest(unittest.TestCase):
 
     def test_c_class(self):
-        from _testcapi import Generic, GenericAlias
+        _testcapi = import_module("_testcapi")
+        Generic = _testcapi.Generic
+        GenericAlias = _testcapi.GenericAlias
         self.assertIsInstance(Generic.__class_getitem__(int), GenericAlias)
 
         IntGeneric = Generic[int]
index 3c387d973ce0f9ee4797d4996e9ccdb8d02c063b..6678548a0ffaca95525769b44f3426e843c09942 100644 (file)
@@ -33,7 +33,7 @@ from test.support import (
     is_wasi, run_in_subinterp, run_in_subinterp_with_config, Py_TRACE_REFS)
 from test.support.import_helper import (
     forget, make_legacy_pyc, unlink, unload, ready_to_import,
-    DirsOnSysPath, CleanImport)
+    DirsOnSysPath, CleanImport, import_module)
 from test.support.os_helper import (
     TESTFN, rmtree, temp_umask, TESTFN_UNENCODABLE)
 from test.support import script_helper
@@ -363,7 +363,7 @@ class ImportTests(unittest.TestCase):
 
     @cpython_only
     def test_from_import_missing_attr_has_name_and_so_path(self):
-        import _testcapi
+        _testcapi = import_module("_testcapi")
         with self.assertRaises(ImportError) as cm:
             from _testcapi import i_dont_exist
         self.assertEqual(cm.exception.name, '_testcapi')
@@ -1870,6 +1870,7 @@ class SubinterpImportTests(unittest.TestCase):
             f'ImportError: module {name} does not support loading in subinterpreters',
         )
 
+    @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
     def test_builtin_compat(self):
         # For now we avoid using sys or builtins
         # since they still don't implement multi-phase init.
@@ -1881,6 +1882,7 @@ class SubinterpImportTests(unittest.TestCase):
             self.check_compatible_here(module, strict=True)
 
     @cpython_only
+    @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
     def test_frozen_compat(self):
         module = '_frozen_importlib'
         require_frozen(module, skip=True)
@@ -1951,6 +1953,7 @@ class SubinterpImportTests(unittest.TestCase):
             self.check_compatible_here(modname, filename,
                                        strict=False, isolated=False)
 
+    @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
     def test_python_compat(self):
         module = 'threading'
         require_pure_python(module)
@@ -1996,6 +1999,7 @@ class SubinterpImportTests(unittest.TestCase):
         with self.subTest('config: check disabled; override: disabled'):
             check_compatible(False, -1)
 
+    @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
     def test_isolated_config(self):
         module = 'threading'
         require_pure_python(module)
@@ -2741,7 +2745,7 @@ class CAPITests(unittest.TestCase):
     def test_pyimport_addmodule(self):
         # gh-105922: Test PyImport_AddModuleRef(), PyImport_AddModule()
         # and PyImport_AddModuleObject()
-        import _testcapi
+        _testcapi = import_module("_testcapi")
         for name in (
             'sys',     # frozen module
             'test',    # package
@@ -2751,7 +2755,7 @@ class CAPITests(unittest.TestCase):
 
     def test_pyimport_addmodule_create(self):
         # gh-105922: Test PyImport_AddModuleRef(), create a new module
-        import _testcapi
+        _testcapi = import_module("_testcapi")
         name = 'dontexist'
         self.assertNotIn(name, sys.modules)
         self.addCleanup(unload, name)
index 89272484009c56f7d99c8e3c622854ab73270814..edbe78545a2536a1c61cd49b67d5add27a8da061 100644 (file)
@@ -15,6 +15,8 @@ import sys
 import tempfile
 import types
 
+_testsinglephase = import_helper.import_module("_testsinglephase")
+
 
 BUILTINS = types.SimpleNamespace()
 BUILTINS.good_name = None
index dc46c0bc8ed35305959ef57283a82ba8983cd8bc..6494842c2176626b65655c21862f244cf7412a58 100644 (file)
@@ -32,7 +32,7 @@ try:
 except ImportError:
     ThreadPoolExecutor = None
 
-from test.support import cpython_only
+from test.support import cpython_only, import_helper
 from test.support import MISSING_C_DOCSTRINGS, ALWAYS_EQ
 from test.support.import_helper import DirsOnSysPath, ready_to_import
 from test.support.os_helper import TESTFN, temp_cwd
@@ -668,7 +668,10 @@ class TestRetrievingSourceCode(GetSourceBase):
 
     @cpython_only
     def test_c_cleandoc(self):
-        import _testinternalcapi
+        try:
+            import _testinternalcapi
+        except ImportError:
+            return unittest.skip("requires _testinternalcapi")
         func = _testinternalcapi.compiler_cleandoc
         for i, (input, expected) in enumerate(self.cleandoc_testdata):
             with self.subTest(i=i):
@@ -1220,7 +1223,7 @@ class TestClassesAndFunctions(unittest.TestCase):
     @unittest.skipIf(MISSING_C_DOCSTRINGS,
                      "Signature information for builtins requires docstrings")
     def test_getfullargspec_builtin_func(self):
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         builtin = _testcapi.docstring_with_signature_with_defaults
         spec = inspect.getfullargspec(builtin)
         self.assertEqual(spec.defaults[0], 'avocado')
@@ -1229,7 +1232,7 @@ class TestClassesAndFunctions(unittest.TestCase):
     @unittest.skipIf(MISSING_C_DOCSTRINGS,
                      "Signature information for builtins requires docstrings")
     def test_getfullargspec_builtin_func_no_signature(self):
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         builtin = _testcapi.docstring_no_signature
         with self.assertRaises(TypeError):
             inspect.getfullargspec(builtin)
@@ -2890,7 +2893,7 @@ class TestSignatureObject(unittest.TestCase):
     @unittest.skipIf(MISSING_C_DOCSTRINGS,
                      "Signature information for builtins requires docstrings")
     def test_signature_on_builtins(self):
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
 
         def test_unbound_method(o):
             """Use this to test unbound methods (things that should have a self)"""
@@ -2971,7 +2974,7 @@ class TestSignatureObject(unittest.TestCase):
     @unittest.skipIf(MISSING_C_DOCSTRINGS,
                      "Signature information for builtins requires docstrings")
     def test_signature_on_decorated_builtins(self):
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         func = _testcapi.docstring_with_signature_with_defaults
 
         def decorator(func):
@@ -2992,7 +2995,7 @@ class TestSignatureObject(unittest.TestCase):
 
     @cpython_only
     def test_signature_on_builtins_no_signature(self):
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         with self.assertRaisesRegex(ValueError,
                                     'no signature found for builtin'):
             inspect.signature(_testcapi.docstring_no_signature)
index 58441ef8b82fd05be91a120146573569d9be967e..11c61bc2e0688d3bf51b837385ba523365c16244 100644 (file)
@@ -11,6 +11,7 @@ import unittest
 import asyncio
 from test import support
 from test.support import requires_specialization, script_helper
+from test.support.import_helper import import_module
 
 PAIR = (0,1)
 
@@ -1829,15 +1830,15 @@ class TestRegressions(MonitoringTestBase, unittest.TestCase):
 class TestOptimizer(MonitoringTestBase, unittest.TestCase):
 
     def setUp(self):
-        import _testinternalcapi
+        _testinternalcapi = import_module("_testinternalcapi")
         self.old_opt = _testinternalcapi.get_optimizer()
         opt = _testinternalcapi.new_counter_optimizer()
         _testinternalcapi.set_optimizer(opt)
         super(TestOptimizer, self).setUp()
 
     def tearDown(self):
-        import _testinternalcapi
         super(TestOptimizer, self).tearDown()
+        import _testinternalcapi
         _testinternalcapi.set_optimizer(self.old_opt)
 
     def test_for_loop(self):
index ccdf3a6cdc0dc779840031fcaf57dbab8ae4a53f..1b55f1e70b32f5f4e5ac114dbc76eb7d797fd831 100644 (file)
@@ -12,6 +12,7 @@ import unittest
 from test import support
 from test.support import os_helper
 from test.support.os_helper import TESTFN
+from test.support.import_helper import import_module
 
 ALL_CJKENCODINGS = [
 # _codecs_cn
@@ -212,7 +213,7 @@ class Test_IncrementalEncoder(unittest.TestCase):
     @support.cpython_only
     def test_subinterp(self):
         # bpo-42846: Test a CJK codec in a subinterpreter
-        import _testcapi
+        _testcapi = import_module("_testcapi")
         encoding = 'cp932'
         text = "Python の開発は、1990 年ごろから開始されています。"
         code = textwrap.dedent("""
index 8829c9a6d882616ce084ad59511d0a9b011c11c0..f4e954fd02148dddb233466bdec22458a2f7f8e7 100644 (file)
@@ -5,12 +5,13 @@ import threading
 import types
 import unittest
 from test.support import threading_helper, check_impl_detail, requires_specialization
+from test.support.import_helper import import_module
 
 # Skip this module on other interpreters, it is cpython specific:
 if check_impl_detail(cpython=False):
     raise unittest.SkipTest('implementation detail specific to cpython')
 
-import _testinternalcapi
+_testinternalcapi = import_module("_testinternalcapi")
 
 
 def disabling_optimizer(func):
index 00b415f43c49b8b3b9416d745bd461d6bea23150..094ac13a915e2d9d70ba6374c529a354e8668beb 100644 (file)
@@ -57,8 +57,10 @@ try:
 except (ImportError, AttributeError):
     all_users = []
 try:
+    import _testcapi
     from _testcapi import INT_MAX, PY_SSIZE_T_MAX
 except ImportError:
+    _testcapi = None
     INT_MAX = PY_SSIZE_T_MAX = sys.maxsize
 
 try:
@@ -5338,6 +5340,7 @@ class ForkTests(unittest.TestCase):
 
     @unittest.skipUnless(sys.platform in ("linux", "android", "darwin"),
                          "Only Linux and macOS detect this today.")
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_fork_warns_when_non_python_thread_exists(self):
         code = """if 1:
             import os, threading, warnings
index a17adb89f5536016f3dbcd2d510df3ddf1e76ecf..d4c6fe0124af1858283a5b9c5e50cee9cd250507 100644 (file)
@@ -2,7 +2,11 @@ import os
 import sys
 import unittest
 
-from _testinternalcapi import perf_map_state_teardown, write_perf_map_entry
+try:
+    from _testinternalcapi import perf_map_state_teardown, write_perf_map_entry
+except ImportError:
+    raise unittest.SkipTest("requires _testinternalcapi")
+
 
 if sys.platform != 'linux':
     raise unittest.SkipTest('Linux only')
index 1847ae95db9292636a04070e0eb7397be65963a6..5675db8d1cab6e91d489b8d10cafdefe3f255ac5 100644 (file)
@@ -172,7 +172,10 @@ class PollTests(unittest.TestCase):
 
     @cpython_only
     def test_poll_c_limits(self):
-        from _testcapi import USHRT_MAX, INT_MAX, UINT_MAX
+        try:
+            from _testcapi import USHRT_MAX, INT_MAX, UINT_MAX
+        except ImportError:
+            raise unittest.SkipTest("requires _testcapi")
         pollster = select.poll()
         pollster.register(1)
 
index 9d40234ed01697f1eee17cd351533627e4e744ee..436fdb38756ddd7c04db4355dd4806bc97215c29 100644 (file)
@@ -1372,7 +1372,7 @@ class TestDescriptions(unittest.TestCase):
     @support.cpython_only
     @requires_docstrings
     def test_module_level_callable_unrepresentable_default(self):
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         builtin = _testcapi.func_with_unrepresentable_signature
         self.assertEqual(self._get_summary_line(builtin),
             "func_with_unrepresentable_signature(a, b=<x>)")
@@ -1382,7 +1382,7 @@ class TestDescriptions(unittest.TestCase):
     def test_builtin_staticmethod_unrepresentable_default(self):
         self.assertEqual(self._get_summary_line(str.maketrans),
             "maketrans(x, y=<unrepresentable>, z=<unrepresentable>, /)")
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         cls = _testcapi.DocStringUnrepresentableSignatureTest
         self.assertEqual(self._get_summary_line(cls.staticmeth),
             "staticmeth(a, b=<x>)")
@@ -1393,7 +1393,7 @@ class TestDescriptions(unittest.TestCase):
         self.assertEqual(self._get_summary_line(dict.pop),
             "pop(self, key, default=<unrepresentable>, /) "
             "unbound builtins.dict method")
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         cls = _testcapi.DocStringUnrepresentableSignatureTest
         self.assertEqual(self._get_summary_line(cls.meth),
             "meth(self, /, a, b=<x>) unbound "
@@ -1405,7 +1405,7 @@ class TestDescriptions(unittest.TestCase):
         self.assertEqual(self._get_summary_line({}.pop),
             "pop(key, default=<unrepresentable>, /) "
             "method of builtins.dict instance")
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         obj = _testcapi.DocStringUnrepresentableSignatureTest()
         self.assertEqual(self._get_summary_line(obj.meth),
             "meth(a, b=<x>) "
@@ -1414,7 +1414,7 @@ class TestDescriptions(unittest.TestCase):
     @support.cpython_only
     @requires_docstrings
     def test_unbound_builtin_classmethod_unrepresentable_default(self):
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         cls = _testcapi.DocStringUnrepresentableSignatureTest
         descr = cls.__dict__['classmeth']
         self.assertEqual(self._get_summary_line(descr),
@@ -1424,7 +1424,7 @@ class TestDescriptions(unittest.TestCase):
     @support.cpython_only
     @requires_docstrings
     def test_bound_builtin_classmethod_unrepresentable_default(self):
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         cls = _testcapi.DocStringUnrepresentableSignatureTest
         self.assertEqual(self._get_summary_line(cls.classmeth),
             "classmeth(a, b=<x>) class method of "
index 6a6b21102fcae88f613eea997f1e76d8a13f2036..d222b3803fdba75d44e50d5dfcc27b3000617975 100644 (file)
@@ -1742,6 +1742,10 @@ class ArgsTestCase(BaseTestCase):
 
     @support.cpython_only
     def test_uncollectable(self):
+        try:
+            import _testcapi
+        except ImportError:
+            raise unittest.SkipTest("requires _testcapi")
         code = textwrap.dedent(r"""
             import _testcapi
             import gc
@@ -2124,6 +2128,10 @@ class ArgsTestCase(BaseTestCase):
 
     def check_add_python_opts(self, option):
         # --fast-ci and --slow-ci add "-u -W default -bb -E" options to Python
+        try:
+            import _testinternalcapi
+        except ImportError:
+            raise unittest.SkipTest("requires _testinternalcapi")
         code = textwrap.dedent(r"""
             import sys
             import unittest
index a28d1595f44533141eb0cdb3b4ada4a5c0bf9301..457279a4db687df8e7fa8ed90ea3677f7d6d9bf5 100644 (file)
@@ -8,6 +8,7 @@ from textwrap import dedent
 from test import support
 from test.support import cpython_only, has_subprocess_support, SuppressCrashReport
 from test.support.script_helper import kill_python
+from test.support.import_helper import import_module
 
 
 if not has_subprocess_support:
@@ -64,6 +65,7 @@ class TestInteractiveInterpreter(unittest.TestCase):
     # _PyRefchain_Trace() on memory allocation error.
     @unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build')
     def test_no_memory(self):
+        import_module("_testcapi")
         # Issue #30696: Fix the interactive interpreter looping endlessly when
         # no memory. Check also that the fix does not break the interactive
         # loop when an exception is raised.
index 661a859b0d0601515c8be56ed65ac21ede6cc782..0c4b3bb2ad4d812bd2a40e406c7bff60de2200f2 100644 (file)
@@ -3,7 +3,6 @@ from test import support
 from test.support import (
     is_apple, os_helper, refleak_helper, socket_helper, threading_helper
 )
-
 import _thread as thread
 import array
 import contextlib
@@ -37,6 +36,10 @@ try:
     import fcntl
 except ImportError:
     fcntl = None
+try:
+    import _testcapi
+except ImportError:
+    _testcapi = None
 
 support.requires_working_socket(module=True)
 
@@ -1173,6 +1176,7 @@ class GeneralModuleTests(unittest.TestCase):
             self.assertRaises(OverflowError, func, 1<<34)
 
     @support.cpython_only
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def testNtoHErrors(self):
         import _testcapi
         s_good_values = [0, 1, 2, 0xffff]
@@ -1638,6 +1642,7 @@ class GeneralModuleTests(unittest.TestCase):
             except socket.gaierror:
                 pass
 
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_getaddrinfo_int_port_overflow(self):
         # gh-74895: Test that getaddrinfo does not raise OverflowError on port.
         #
@@ -1831,6 +1836,7 @@ class GeneralModuleTests(unittest.TestCase):
             srv.listen()
 
     @support.cpython_only
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def test_listen_backlog_overflow(self):
         # Issue 15989
         import _testcapi
@@ -2712,22 +2718,29 @@ class BasicTCPTest(SocketConnectedTest):
     def _testDup(self):
         self.serv_conn.send(MSG)
 
-    def testShutdown(self):
-        # Testing shutdown()
+    def check_shutdown(self):
+        # Test shutdown() helper
         msg = self.cli_conn.recv(1024)
         self.assertEqual(msg, MSG)
-        # wait for _testShutdown to finish: on OS X, when the server
+        # wait for _testShutdown[_overflow] to finish: on OS X, when the server
         # closes the connection the client also becomes disconnected,
         # and the client's shutdown call will fail. (Issue #4397.)
         self.done.wait()
 
+    def testShutdown(self):
+        self.check_shutdown()
+
     def _testShutdown(self):
         self.serv_conn.send(MSG)
         self.serv_conn.shutdown(2)
 
-    testShutdown_overflow = support.cpython_only(testShutdown)
+    @support.cpython_only
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
+    def testShutdown_overflow(self):
+        self.check_shutdown()
 
     @support.cpython_only
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def _testShutdown_overflow(self):
         import _testcapi
         self.serv_conn.send(MSG)
@@ -4884,6 +4897,7 @@ class NonBlockingTCPTests(ThreadedTCPSocketTest):
         pass
 
     @support.cpython_only
+    @unittest.skipIf(_testcapi is None, "requires _testcapi")
     def testSetBlocking_overflow(self):
         # Issue 15989
         import _testcapi
index 588272448bbfda640d4316c320c66b2156ee9ad3..4182de246a071b065cfe84c70c75cd1a65e6a4ce 100644 (file)
@@ -34,8 +34,7 @@ from test.support import (
     is_apple, is_emscripten, is_wasi
 )
 from test.support import gc_collect
-from test.support import threading_helper
-from _testcapi import INT_MAX, ULLONG_MAX
+from test.support import threading_helper, import_helper
 from os import SEEK_SET, SEEK_CUR, SEEK_END
 from test.support.os_helper import TESTFN, TESTFN_UNDECODABLE, unlink, temp_dir, FakePath
 
@@ -1202,7 +1201,6 @@ class BlobTests(unittest.TestCase):
     def test_blob_seek_error(self):
         msg_oor = "offset out of blob range"
         msg_orig = "'origin' should be os.SEEK_SET, os.SEEK_CUR, or os.SEEK_END"
-        msg_of = "seek offset results in overflow"
 
         dataset = (
             (ValueError, msg_oor, lambda: self.blob.seek(1000)),
@@ -1214,12 +1212,15 @@ class BlobTests(unittest.TestCase):
             with self.subTest(exc=exc, msg=msg, fn=fn):
                 self.assertRaisesRegex(exc, msg, fn)
 
+    def test_blob_seek_overflow_error(self):
         # Force overflow errors
+        msg_of = "seek offset results in overflow"
+        _testcapi = import_helper.import_module("_testcapi")
         self.blob.seek(1, SEEK_SET)
         with self.assertRaisesRegex(OverflowError, msg_of):
-            self.blob.seek(INT_MAX, SEEK_CUR)
+            self.blob.seek(_testcapi.INT_MAX, SEEK_CUR)
         with self.assertRaisesRegex(OverflowError, msg_of):
-            self.blob.seek(INT_MAX, SEEK_END)
+            self.blob.seek(_testcapi.INT_MAX, SEEK_END)
 
     def test_blob_read(self):
         buf = self.blob.read()
@@ -1379,14 +1380,17 @@ class BlobTests(unittest.TestCase):
             with self.subTest(idx=idx):
                 with self.assertRaisesRegex(IndexError, "index out of range"):
                     self.blob[idx]
-        with self.assertRaisesRegex(IndexError, "cannot fit 'int'"):
-            self.blob[ULLONG_MAX]
 
         # Provoke read error
         self.cx.execute("update test set b='aaaa' where rowid=1")
         with self.assertRaises(sqlite.OperationalError):
             self.blob[0]
 
+    def test_blob_get_item_error_bigint(self):
+        _testcapi = import_helper.import_module("_testcapi")
+        with self.assertRaisesRegex(IndexError, "cannot fit 'int'"):
+            self.blob[_testcapi.ULLONG_MAX]
+
     def test_blob_set_item_error(self):
         with self.assertRaisesRegex(TypeError, "cannot be interpreted"):
             self.blob[0] = b"multiple"
index d0e4f3c71c15e070fd8ed3c1ce9ec769d26f6c07..d22698168615e288673f3c925a50c896f4595f66 100644 (file)
@@ -6,7 +6,10 @@
 import sys
 import unittest
 from test.support.import_helper import import_module
-from _testcapi import get_feature_macros
+try:
+    from _testcapi import get_feature_macros
+except ImportError:
+    raise unittest.SkipTest("requires _testcapi")
 
 feature_macros = get_feature_macros()
 
index f6f23b0afc34c67f9e4e740694eff271132af709..6a66df4e897e3fb3a349558605a23b763aaa7c81 100644 (file)
@@ -1390,7 +1390,7 @@ class SizeofTest(unittest.TestCase):
     def setUp(self):
         self.P = struct.calcsize('P')
         self.longdigit = sys.int_info.sizeof_digit
-        import _testinternalcapi
+        _testinternalcapi = import_helper.import_module("_testinternalcapi")
         self.gc_headsize = _testinternalcapi.SIZEOF_PYGC_HEAD
         self.managed_pre_header_size = _testinternalcapi.SIZEOF_MANAGED_PRE_HEADER
 
index 4414d2bb9cdb59a742e481db31031d7c8c816c67..84a946477818df1d390935636876734d3935fddd 100644 (file)
@@ -959,6 +959,7 @@ class ThreadTests(BaseTestCase):
 
     @cpython_only
     def test_frame_tstate_tracing(self):
+        _testcapi = import_module("_testcapi")
         # Issue #14432: Crash when a generator is created in a C thread that is
         # destroyed while the generator is still used. The issue was that a
         # generator contains a frame, and the frame kept a reference to the
@@ -986,7 +987,6 @@ class ThreadTests(BaseTestCase):
             threading.settrace(noop_trace)
 
             # Create a generator in a C thread which exits after the call
-            import _testcapi
             _testcapi.call_in_temporary_c_thread(callback)
 
             # Call the generator in a different Python thread, check that the
@@ -1490,6 +1490,7 @@ class SubinterpThreadingTests(BaseTestCase):
 
     @cpython_only
     def test_daemon_threads_fatal_error(self):
+        import_module("_testcapi")
         subinterp_code = f"""if 1:
             import os
             import threading
@@ -1516,6 +1517,7 @@ class SubinterpThreadingTests(BaseTestCase):
                        daemon_allowed=True,
                        daemon=False,
                        ):
+        import_module("_testinternalcapi")
         subinterp_code = textwrap.dedent(f"""
             import test.support
             import threading
index 17a1a6d0d38d7d9411fb4c1f2ae9f16371f6ff74..29f5c28e33bb2bcf43e57dac67603755ee720db2 100644 (file)
@@ -35,6 +35,7 @@ class TestMakefile(unittest.TestCase):
                     result.append(line.replace('\\', '').strip())
         return result
 
+    @unittest.skipUnless(support.TEST_MODULES_ENABLED, "requires test modules")
     def test_makefile_test_folders(self):
         test_dirs = self.list_test_dirs()
         idle_test = 'idlelib/idle_test'
index d6470fb6919cfd22750dda9e5e8d02e32dc93541..6fbd292c1e67936bc493711276b4afffb6327c59 100644 (file)
@@ -14,6 +14,7 @@ import random
 from test import support
 from test.support import script_helper, ALWAYS_EQ
 from test.support import gc_collect
+from test.support import import_helper
 from test.support import threading_helper
 
 # Used in ReferencesTestCase.test_ref_created_during_del() .
@@ -161,7 +162,7 @@ class ReferencesTestCase(TestBase):
 
     @support.cpython_only
     def test_cfunction(self):
-        import _testcapi
+        _testcapi = import_helper.import_module("_testcapi")
         create_cfunction = _testcapi.create_cfunction
         f = create_cfunction()
         wr = weakref.ref(f)
index 95fc4dfbf11e49fd7fe74c5a1806c8ccbc6ed57d..8b01c91e0d6bb3c0ac82746e87cc3678c193a8e7 100644 (file)
@@ -275,7 +275,10 @@ def gen_ctypes_test(manifest, args, outfile):
         import sys
         import unittest
         from test.support.import_helper import import_module
-        from _testcapi import get_feature_macros
+        try:
+            from _testcapi import get_feature_macros
+        except ImportError:
+            raise unittest.SkipTest("requires _testcapi")
 
         feature_macros = get_feature_macros()