Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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) }}
Expand Down Expand Up @@ -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) }}
Expand Down Expand Up @@ -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) }}
Expand All @@ -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

Expand Down Expand Up @@ -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) }}
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
10 changes: 8 additions & 2 deletions src/c/test_c.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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():
Expand Down Expand Up @@ -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")
Expand All @@ -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")
Expand Down
18 changes: 16 additions & 2 deletions src/cffi/verifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
13 changes: 9 additions & 4 deletions testing/cffi0/test_ownlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
28 changes: 24 additions & 4 deletions testing/cffi0/test_verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 <math.h>', 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 <math.h>', libraries=lib_m, modulename=modulename)
assert lib.cos(1.23) == math.cos(1.23)
assert not os.path.exists(cfile)
Comment thread
mattip marked this conversation as resolved.
Resolved
16 changes: 0 additions & 16 deletions testing/cffi0/test_verify2.py

This file was deleted.

13 changes: 0 additions & 13 deletions testing/cffi0/test_vgen2.py

This file was deleted.

9 changes: 5 additions & 4 deletions testing/cffi0/test_zdistutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -92,7 +93,7 @@ def test_compile_module_explicit_filename(self):
csrc = f'/*hi there {self}!2*/\n#include <math.h>\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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
)
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
)
13 changes: 10 additions & 3 deletions testing/cffi1/test_cffi_gen_src_meson.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
46 changes: 46 additions & 0 deletions testing/conftest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import pytest
import sys

Expand All @@ -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(
Expand Down
5 changes: 5 additions & 0 deletions testing/embedding/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import sys
import pytest

if sys.platform == "win32":
pytest.skip("XXX fixme", allow_module_level=True)
11 changes: 4 additions & 7 deletions testing/udir.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import sys, tempfile, os, atexit
import shutil, sys, tempfile, os, atexit
from pathlib import Path


Expand Down Expand Up @@ -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:
Expand Down
Loading