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)
)
def test_unraisablehook(self):
+ import_helper.import_module("_testcapi")
returncode, events, stderr = self.run_python("test_unraisablehook")
if returncode:
self.fail(stderr)
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:
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
NULL_OR_EMPTY = object()
+
class FastCallTests(unittest.TestCase):
"""Test calling using various callables from C
"""
]
# 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:
expected = (*expected[:-1], result[-1])
self.assertEqual(result, expected)
+ @unittest.skipIf(_testcapi is None, "requires _testcapi")
def test_vectorcall_dict(self):
# Test PyObject_VectorcallDict()
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()
ADAPTIVE_WARMUP_DELAY = 2
+@unittest.skipIf(_testcapi is None, "requires _testcapi")
class TestPEP590(unittest.TestCase):
def test_method_descriptor_flag(self):
@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):
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)
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']
@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")
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:
@support.cpython_only
+@unittest.skipIf(_testcapi is None, "requires _testcapi")
class CAPITest(unittest.TestCase):
def test_tp_await_1(self):
-import _ctypes_test
import ctypes
import unittest
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__)
-import _ctypes_test
import os
import unittest
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):
-import _ctypes_test
import ctypes
import functools
import gc
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):
-import _ctypes_test
import ctypes
import unittest
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):
-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):
-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)
-import _ctypes_test
import ctypes
import sys
import unittest
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
-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__)
import _ctypes
-import _ctypes_test
import ctypes
import os
import shutil
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
-import _ctypes_test
import unittest
import test.support
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):
-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__)
-import _ctypes_test
import array
import ctypes
import sys
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)
#
# 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__)
-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)
-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):
-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):
-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__)
-import _ctypes_test
from platform import architecture as _architecture
import struct
import sys
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)
-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):
A testcase which accesses *values* in a dll.
"""
-import _ctypes_test
import _imp
import importlib.util
import sys
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())
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):
# Windows specific tests
-import _ctypes_test
import ctypes
import errno
import sys
_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
@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)]
("right", c_long),
("bottom", c_long)]
+ _ctypes_test = import_helper.import_module("_ctypes_test")
dll = CDLL(_ctypes_test.__file__)
pt = POINT(15, 25)
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
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
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')
# 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)
# 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'
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
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:
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:
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)
@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
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
# 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
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.
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."
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.
# 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
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,
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)
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():
@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)
@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)
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
@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)
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:
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
import re
import test.support as support
import unittest
+from test.support.import_helper import import_module
maxsize = support.MAX_Py_ssize_t
@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:
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
@cpython_only
@requires_subprocess()
+ @unittest.skipIf(_testcapi is None, "requires _testcapi")
def test_garbage_at_shutdown(self):
import subprocess
code = """if 1:
import unittest
from test import support
+from test.support.import_helper import import_module
class TestMROEntry(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]
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
@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')
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.
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)
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)
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)
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
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)
import tempfile
import types
+_testsinglephase = import_helper.import_module("_testsinglephase")
+
BUILTINS = types.SimpleNamespace()
BUILTINS.good_name = None
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
@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):
@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')
@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)
@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)"""
@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):
@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)
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)
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):
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
@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("""
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):
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:
@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
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')
@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)
@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>)")
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>)")
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 "
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>) "
@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),
@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 "
@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
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
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:
# _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.
from test.support import (
is_apple, os_helper, refleak_helper, socket_helper, threading_helper
)
-
import _thread as thread
import array
import contextlib
import fcntl
except ImportError:
fcntl = None
+try:
+ import _testcapi
+except ImportError:
+ _testcapi = None
support.requires_working_socket(module=True)
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]
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.
#
srv.listen()
@support.cpython_only
+ @unittest.skipIf(_testcapi is None, "requires _testcapi")
def test_listen_backlog_overflow(self):
# Issue 15989
import _testcapi
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)
pass
@support.cpython_only
+ @unittest.skipIf(_testcapi is None, "requires _testcapi")
def testSetBlocking_overflow(self):
# Issue 15989
import _testcapi
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
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)),
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()
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"
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()
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
@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
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
@cpython_only
def test_daemon_threads_fatal_error(self):
+ import_module("_testcapi")
subinterp_code = f"""if 1:
import os
import threading
daemon_allowed=True,
daemon=False,
):
+ import_module("_testinternalcapi")
subinterp_code = textwrap.dedent(f"""
import test.support
import threading
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'
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() .
@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)
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()