diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 8bbf6c5a..23ab2e11 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -155,6 +155,7 @@ jobs: linux: needs: [python_sdist, make_linux_matrix] runs-on: ${{ (matrix.arch == 'aarch64') && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }} + timeout-minutes: 120 strategy: fail-fast: false matrix: ${{ fromJSON(needs.make_linux_matrix.outputs.matrix_json) }} @@ -261,6 +262,7 @@ jobs: run: shell: ${{ matrix.run_wrapper || 'bash --noprofile --norc -eo pipefail {0}' }} runs-on: ${{ matrix.runs_on || 'macos-26' }} + timeout-minutes: 45 strategy: fail-fast: false matrix: ${{ fromJSON(needs.make_macos_matrix.outputs.matrix_json) }} @@ -358,6 +360,7 @@ jobs: windows: needs: [python_sdist, make_windows_matrix] runs-on: ${{ matrix.runs_on || 'windows-2022' }} + timeout-minutes: 45 strategy: fail-fast: false matrix: ${{ fromJSON(needs.make_windows_matrix.outputs.matrix_json) }} @@ -380,12 +383,10 @@ jobs: CIBW_BUILD: ${{ matrix.spec }} CIBW_ENABLE: cpython-prerelease CIBW_TEST_REQUIRES: pytest setuptools meson-python ninja - CIBW_TEST_COMMAND: ${{ matrix.test_cmd || 'python -m pytest {package}/src/c' }} + CIBW_TEST_COMMAND: ${{ matrix.test_cmd || 'python -m pytest {package}/src {package}/testing' }} CIBW_ENVIRONMENT: >- _CL_="$_CL_ ${{ env.skip_artifact_upload == 'true' && '/UNDEBUG' || '/DNDEBUG' }}" CFFI_TEST_ASSERTIONS=${{ env.skip_artifact_upload == 'true' && '1' || '0' }} - # FIXME: /testing takes ~45min on Windows and has some failures... - # CIBW_TEST_COMMAND='python -m pytest {package}/src/c {package}/testing' run: | set -eux @@ -434,6 +435,7 @@ jobs: ios: needs: [python_sdist, make_ios_matrix] runs-on: macos-15 + timeout-minutes: 45 strategy: fail-fast: false matrix: ${{ fromJSON(needs.make_ios_matrix.outputs.matrix_json) }} @@ -556,6 +558,7 @@ jobs: matrix: ${{ fromJSON(needs.make_run_parallel_matrix.outputs.matrix_json) }} runs-on: ${{ matrix.runner }} + timeout-minutes: 30 steps: - name: clone repo uses: actions/checkout@v7 @@ -568,16 +571,17 @@ jobs: - name: build and install run: | - python -m pip install pytest setuptools meson-python ninja pytest-run-parallel + python -m pip install pytest setuptools meson-python ninja pytest-run-parallel pytest-timeout python -m pip install . - name: run tests under pytest-run-parallel run: | - python -m pytest --parallel-threads=4 --skip-thread-unsafe=True + python -m pytest --parallel-threads=4 --skip-thread-unsafe=True --timeout=300 --timeout-method=thread clang_TSAN: runs-on: ubuntu-24.04 container: ghcr.io/nascheme/numpy-tsan:3.15t-dev + timeout-minutes: 30 env: CFLAGS: -g -O0 -fsanitize=thread CPPFLAGS: -UNDEBUG diff --git a/src/c/test_c.py b/src/c/test_c.py index 61f055ff..c1b52372 100644 --- a/src/c/test_c.py +++ b/src/c/test_c.py @@ -1459,6 +1459,7 @@ def oops(*args): @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS") +@pytest.mark.thread_unsafe("mocks sys.unraiseablehook") def test_callback_return_type(): for rettype in ["signed char", "short", "int", "long", "long long", "unsigned char", "unsigned short", "unsigned int", @@ -1477,7 +1478,10 @@ def cb(n): max = (1 << (8*sizeof(BRet)-1)) - 1 assert f(min) == min + 1 assert f(max - 1) == max - assert f(max) == 42 + # the callback returns max + 1, which does not fit 'rettype', so the + # conversion back to C fails and the error_value is returned instead + with _assert_unraisable(OverflowError): + assert f(max) == 42 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS") def test_a_lot_of_callbacks(): @@ -1777,6 +1781,7 @@ def _hacked_pypy_uni4(): return 'PY_DOT_PY' in globals() and not pyuni4 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS") +@pytest.mark.thread_unsafe("mocks sys.unraiseablehook") def test_callback_returning_wchar_t(): BInt = new_primitive_type("int") BWChar = new_primitive_type("wchar_t") @@ -1793,7 +1798,8 @@ def cb(n): assert f(0x1234) == u+'\u1234' if sizeof(BWChar) == 4 and not _hacked_pypy_uni4(): assert f(-1) == u+'\U00012345' - assert f(-2) == u+'\x00' # and an exception printed to stderr + with _assert_unraisable(ValueError): + assert f(-2) == u+'\x00' def test_struct_with_bitfields(): BLong = new_primitive_type("long") diff --git a/src/cffi/verifier.py b/src/cffi/verifier.py index e0f30841..3b3f433b 100644 --- a/src/cffi/verifier.py +++ b/src/cffi/verifier.py @@ -195,8 +195,20 @@ def _write_source(self, file=None): def _compile_module(self): # compile this C source + # Note: compilation will create artifacts in tmpdir + sourcefilename + # This can exceed the windows MAXPATH quite easily. To make it shorter, + # cd into tmpdir and make the sourcefilename relative to tmdir tmpdir = os.path.dirname(self.sourcefilename) - outputfilename = ffiplatform.compile(tmpdir, self.get_extension()) + olddir = os.getcwd() + os.chdir(tmpdir) + self.sourcefilename_orig = self.sourcefilename + try: + self.sourcefilename = os.path.relpath(self.sourcefilename) + output_rel_filename = ffiplatform.compile(tmpdir, self.get_extension()) + outputfilename = os.path.join(tmpdir, output_rel_filename) + finally: + os.chdir(olddir) + self.sourcefilename = self.sourcefilename_orig try: same = ffiplatform.samefile(outputfilename, self.modulefilename) except OSError: @@ -270,7 +282,9 @@ def cleanup_tmpdir(tmpdir=None, keep_so=False): suffix = _get_so_suffixes()[0].lower() for fn in filelist: if fn.lower().startswith('_cffi_') and ( - fn.lower().endswith(suffix) or fn.lower().endswith('.c')): + fn.lower().endswith(suffix) or + fn.lower().endswith('.c') or + fn.lower().endswith('.o')): try: os.unlink(os.path.join(tmpdir, fn)) except OSError: diff --git a/testing/cffi0/test_ownlib.py b/testing/cffi0/test_ownlib.py index 852ac7d9..b9f547b6 100644 --- a/testing/cffi0/test_ownlib.py +++ b/testing/cffi0/test_ownlib.py @@ -142,10 +142,15 @@ def setup_class(cls): return # try (not too hard) to find the version used to compile this python # no mingw - from distutils.msvc9compiler import get_build_version - version = get_build_version() - toolskey = f"VS{version:0.0f}0COMNTOOLS" - toolsdir = os.environ.get(toolskey, None) + toolsdir = None + try: + # This will always fail on setuptools>73 which removes msvc9compiler + from distutils.msvc9compiler import get_build_version + version = get_build_version() + toolskey = "VS%0.f0COMNTOOLS" % version + toolsdir = os.environ.get(toolskey, None) + except Exception: + pass if toolsdir is None: return productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC") diff --git a/testing/cffi0/test_verify.py b/testing/cffi0/test_verify.py index 278b789d..0316698b 100644 --- a/testing/cffi0/test_verify.py +++ b/testing/cffi0/test_verify.py @@ -52,9 +52,11 @@ def test_module_type(): ffi = FFI() lib = ffi.verify() if hasattr(lib, '_cffi_python_module'): - print('verify got a PYTHON module') + pass + # print('verify got a PYTHON module') if hasattr(lib, '_cffi_generic_module'): - print('verify got a GENERIC module') + pass + # print('verify got a GENERIC module') expected_generic = (cffi.verifier._FORCE_GENERIC_ENGINE or '__pypy__' in sys.builtin_module_names) assert hasattr(lib, '_cffi_python_module') == (not expected_generic) @@ -2241,10 +2243,10 @@ def test_implicit_unicode_on_windows(): def test_use_local_dir(): ffi = FFI() - lib = ffi.verify("", modulename="test_use_local_dir") + lib = ffi.verify("", modulename="_cffi_test_use_local_dir") this_dir = os.path.dirname(__file__) pycache_files = os.listdir(os.path.join(this_dir, '__pycache__')) - assert any('test_use_local_dir' in s for s in pycache_files) + assert any('_cffi_test_use_local_dir' in s for s in pycache_files) def test_define_known_value(): ffi = FFI() @@ -2580,3 +2582,21 @@ def test_passing_large_list(): arg = list(range(20000000)) lib.passing_large_list(arg) # assert did not segfault + +def test_no_regen(): + from cffi.verifier import Verifier, _caller_dir_pycache, _FORCE_GENERIC_ENGINE + import os + ffi = FFI() + # make sure the module name is unique + modulename = "_cffi_test_no_regen" + str(_FORCE_GENERIC_ENGINE) + ffi.cdef("double cos(double x);") + lib = ffi.verify('#include ', libraries=lib_m, modulename=modulename) + assert lib.cos(1.23) == math.cos(1.23) + # Make sure that recompiling the same code does not rebuild the C file + cfile = os.path.join(ffi.verifier.tmpdir, f"{modulename}.c") + assert os.path.exists(cfile) + os.unlink(cfile) + assert not os.path.exists(cfile) + lib = ffi.verify('#include ', libraries=lib_m, modulename=modulename) + assert lib.cos(1.23) == math.cos(1.23) + assert not os.path.exists(cfile) diff --git a/testing/cffi0/test_verify2.py b/testing/cffi0/test_verify2.py deleted file mode 100644 index cbb7b9db..00000000 --- a/testing/cffi0/test_verify2.py +++ /dev/null @@ -1,16 +0,0 @@ -import pytest -from .test_verify import * - -pytestmark = [ - pytest.mark.thread_unsafe(reason="FFI verifier is not thread-safe"), - # eliminate warning noise from common test modules that are repeatedly re-imported - pytest.mark.filterwarnings("ignore:reimporting:UserWarning"), -] - -# This test file runs normally after test_verify. We only clean up the .c -# sources, to check that it also works when we have only the .so. The -# tests should run much faster than test_verify. - -def setup_module(): - import cffi.verifier - cffi.verifier.cleanup_tmpdir(keep_so=True) diff --git a/testing/cffi0/test_vgen2.py b/testing/cffi0/test_vgen2.py deleted file mode 100644 index 34147c87..00000000 --- a/testing/cffi0/test_vgen2.py +++ /dev/null @@ -1,13 +0,0 @@ -import cffi.verifier -from .test_vgen import * - -# This test file runs normally after test_vgen. We only clean up the .c -# sources, to check that it also works when we have only the .so. The -# tests should run much faster than test_vgen. - -def setup_module(): - cffi.verifier.cleanup_tmpdir(keep_so=True) - cffi.verifier._FORCE_GENERIC_ENGINE = True - -def teardown_module(): - cffi.verifier._FORCE_GENERIC_ENGINE = False diff --git a/testing/cffi0/test_zdistutils.py b/testing/cffi0/test_zdistutils.py index 404cafd8..a03cba9e 100644 --- a/testing/cffi0/test_zdistutils.py +++ b/testing/cffi0/test_zdistutils.py @@ -21,9 +21,10 @@ def setup_class(self): self.lib_m = 'msvcrt' def teardown_class(self): - if udir.is_dir(): - shutil.rmtree(udir) - udir.mkdir() + # udir is shared with the other test modules, and windows cannot + # delete a .pyd that is still loaded into this process + shutil.rmtree(udir, ignore_errors=True) + udir.mkdir(exist_ok=True) def test_locate_engine_class(self): cls = _locate_engine_class(FFI(), self.generic) @@ -92,7 +93,7 @@ def test_compile_module_explicit_filename(self): csrc = f'/*hi there {self}!2*/\n#include \n' v = Verifier(ffi, csrc, force_generic_engine=self.generic, libraries=[self.lib_m]) - basename = self.__class__.__name__[:10] + '_test_compile_module' + basename = self.__class__.__name__[:20] + '_test_compile_module' module_file = udir / (basename + '.so') v.modulefilename = str(module_file) v.compile_module() diff --git a/testing/cffi1/cffi_gen_src_examples/exec_python_example/meson.build b/testing/cffi1/cffi_gen_src_examples/exec_python_example/meson.build index dfcb10a6..cd2f63ef 100644 --- a/testing/cffi1/cffi_gen_src_examples/exec_python_example/meson.build +++ b/testing/cffi1/cffi_gen_src_examples/exec_python_example/meson.build @@ -39,4 +39,9 @@ py.extension_module( subdir: 'squared', install: true, dependencies: [square_dep], + # _cffi_include.h defines Py_LIMITED_API by default under MSVC, and + # pyconfig.h then asks the linker for python3.lib via a #pragma. Only + # meson's limited_api: kwarg puts that library on the link line, so build + # an ordinary extension instead. + c_args: ['-D_CFFI_NO_LIMITED_API'], ) diff --git a/testing/cffi1/cffi_gen_src_examples/read_sources_example/meson.build b/testing/cffi1/cffi_gen_src_examples/read_sources_example/meson.build index 05799fc1..827ae969 100644 --- a/testing/cffi1/cffi_gen_src_examples/read_sources_example/meson.build +++ b/testing/cffi1/cffi_gen_src_examples/read_sources_example/meson.build @@ -41,4 +41,9 @@ py.extension_module( subdir: 'squared', install: true, dependencies: [square_dep], + # _cffi_include.h defines Py_LIMITED_API by default under MSVC, and + # pyconfig.h then asks the linker for python3.lib via a #pragma. Only + # meson's limited_api: kwarg puts that library on the link line, so build + # an ordinary extension instead. + c_args: ['-D_CFFI_NO_LIMITED_API'], ) diff --git a/testing/cffi1/test_cffi_gen_src_meson.py b/testing/cffi1/test_cffi_gen_src_meson.py index ece55c1c..c32b3664 100644 --- a/testing/cffi1/test_cffi_gen_src_meson.py +++ b/testing/cffi1/test_cffi_gen_src_meson.py @@ -62,10 +62,17 @@ def test_meson_python_build(tmp_path, project): # --no-build-isolation so the build uses the bridged environment; # --no-index/--no-deps so pip cannot touch the network. - proc = subprocess.run([ + cmd = [ str(venv_python), "-m", "pip", "install", "-v", - "--no-index", "--no-deps", "--no-build-isolation", str(project_dir), - ], capture_output=True, text=True) + "--no-index", "--no-deps", "--no-build-isolation", + ] + if sys.platform == "win32": + # meson only activates the MSVC environment by itself when it finds + # no compiler at all, so without this it picks up any mingw gcc on + # PATH and then cannot build for a 32-bit or arm64 host + cmd.append("-Csetup-args=--vsenv") + proc = subprocess.run(cmd + [str(project_dir)], + capture_output=True, text=True) assert proc.returncode == 0, proc.stdout + proc.stderr # Confirm the built extension imports and behaves as expected. diff --git a/testing/conftest.py b/testing/conftest.py index 59efb54e..a2f21f53 100644 --- a/testing/conftest.py +++ b/testing/conftest.py @@ -1,3 +1,4 @@ +import os import pytest import sys @@ -9,7 +10,52 @@ except Exception: PARALLEL_RUN_AVAILABLE = False +def _msvc_env(): + """Query the MSVC environment for the platform we are running on.""" + from setuptools._distutils.util import get_platform + try: + # setuptools >= 80 + from setuptools._distutils.compilers.C.msvc import ( + _get_vc_env, _get_vcvars_spec) + from setuptools._distutils.util import get_host_platform + spec = _get_vcvars_spec(get_host_platform(), get_platform()) + except ImportError: + from setuptools._distutils._msvccompiler import ( + _get_vc_env, PLAT_TO_VCVARS) + spec = PLAT_TO_VCVARS[get_platform()] + return _get_vc_env(spec) + + +def _prime_msvc_env(): + """Put the MSVC environment in os.environ once, on windows. + + _get_vc_env() runs 'cmd /u /c vcvarsall.bat && set' and caches nothing, + and it is called from MSVCCompiler.initialize(), i.e. once per compiler + instance. cffi builds a fresh compiler for every ffi.verify(), so this + suite would spawn vcvarsall hundreds of times. Querying it once and + setting DISTUTILS_USE_SDK makes _get_vc_env() return os.environ instead. + + It also puts cl.exe on PATH, which is where meson looks for a compiler + before falling back to a stray mingw gcc. + """ + if sys.platform != 'win32' or os.environ.get('DISTUTILS_USE_SDK'): + return + try: + env = _msvc_env() + except Exception: + return # leave distutils to find the compiler by itself + # vcvarsall inherits our environment, so these already include whatever + # PATH/INCLUDE/LIB we were started with + wanted = {key: env.get(key.lower(), '') + for key in ('PATH', 'INCLUDE', 'LIB', 'LIBPATH')} + if not all(wanted[key] for key in ('PATH', 'INCLUDE', 'LIB')): + return + os.environ.update(wanted) + os.environ['DISTUTILS_USE_SDK'] = '1' + + def pytest_configure(config): + _prime_msvc_env() # Don't warn for `pytest-run-parallel` markers if they're not available if not PARALLEL_RUN_AVAILABLE: config.addinivalue_line( diff --git a/testing/embedding/__init__.py b/testing/embedding/__init__.py index e69de29b..13bb2072 100644 --- a/testing/embedding/__init__.py +++ b/testing/embedding/__init__.py @@ -0,0 +1,5 @@ +import sys +import pytest + +if sys.platform == "win32": + pytest.skip("XXX fixme", allow_module_level=True) diff --git a/testing/udir.py b/testing/udir.py index d5f2b88b..a890aa03 100644 --- a/testing/udir.py +++ b/testing/udir.py @@ -1,4 +1,4 @@ -import sys, tempfile, os, atexit +import shutil, sys, tempfile, os, atexit from pathlib import Path @@ -95,12 +95,9 @@ def try_remove_lockfile(): continue # skip directories still locked except FileNotFoundError: pass # assume that it means that there is no 'lf' - try: - path.remove(rec=1) - except KeyboardInterrupt: - raise - except: # this might be py.error.Error, WindowsError ... - pass + # ignore_errors: windows cannot delete a .pyd that is + # still loaded, but a later run will not have it loaded + shutil.rmtree(path, ignore_errors=True) # make link... try: