1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
|
# SPDX-FileCopyrightText: 2021 The meson-python developers
#
# SPDX-License-Identifier: MIT
import contextlib
import importlib.metadata
import os
import os.path
import pathlib
import re
import shutil
import subprocess
import sys
import sysconfig
import tempfile
import warnings
from venv import EnvBuilder
import packaging.metadata
import packaging.version
import pytest
import mesonpy
from mesonpy._util import chdir
_meson_ver_str = subprocess.run(['meson', '--version'], check=True, stdout=subprocess.PIPE, text=True).stdout
MESON_VERSION = tuple(map(int, _meson_ver_str.split('.')[:3]))
def metadata(data):
meta, other = packaging.metadata.parse_email(data)
# PEP-639 support requires packaging >= 24.1. Add minimal
# handling of PEP-639 fields here to allow testing with older
# packaging releases.
value = other.pop('license-expression', None)
if value is not None:
# The ``License-Expression`` header should appear only once.
assert len(value) == 1
meta['license-expression'] = value[0]
value = other.pop('license-file', None)
if value is not None:
meta['license-file'] = value
assert not other
return meta
def adjust_packaging_platform_tag(platform: str) -> str:
if platform.startswith(('manylinux', 'musllinux')):
# The packaging module generates overly specific platforms tags on
# Linux. The platforms tags on Linux evolved over time.
# meson-python uses more relaxed platform tags to maintain
# compatibility with old wheel installation tools. The relaxed
# platform tags match the ones generated by the wheel package.
# https://packaging.python.org/en/latest/specifications/platform-compatibility-tags/
return re.sub(r'^(many|musl)linux(1|2010|2014|_\d+_\d+)_(.*)$', r'linux_\3', platform)
if platform.startswith('macosx'):
# Python built with older macOS SDK on macOS 11, reports an
# unexising macOS 10.16 version instead of the real version.
# The packaging module introduced a workaround in version
# 22.0. Too maintain compatibility with older packaging
# releases we don't implement it. Reconcile this.
from platform import mac_ver
version = tuple(map(int, mac_ver()[0].split('.')))[:2]
if version == (10, 16):
return re.sub(r'^macosx_\d+_\d+_(.*)$', r'macosx_10_16_\1', platform)
return platform
package_dir = pathlib.Path(__file__).parent / 'packages'
@contextlib.contextmanager
def in_git_repo_context(path=os.path.curdir):
# Resist the temptation of using pathlib.Path here: it is not
# supported by subprocess in Python 3.7.
path = os.path.abspath(path)
shutil.rmtree(os.path.join(path, '.git'), ignore_errors=True)
try:
subprocess.run(['git', 'init', '-b', 'main', path], check=True)
subprocess.run(['git', 'config', 'user.email', 'author@example.com'], cwd=path, check=True)
subprocess.run(['git', 'config', 'user.name', 'A U Thor'], cwd=path, check=True)
subprocess.run(['git', 'add', '*'], cwd=path, check=True)
subprocess.run(['git', 'commit', '-q', '-m', 'Test'], cwd=path, check=True)
yield
finally:
# PermissionError raised on Windows.
with contextlib.suppress(PermissionError):
shutil.rmtree(os.path.join(path, '.git'))
@pytest.fixture(scope='session')
def tmp_path_session(tmp_path_factory):
return pathlib.Path(tempfile.mkdtemp(
prefix='mesonpy-test-',
dir=tmp_path_factory.mktemp('test'),
))
class VEnv(EnvBuilder):
def __init__(self, env_dir):
super().__init__(symlinks=True, with_pip=True)
# This warning is mistakenly generated by CPython 3.11.0
# https://github.com/python/cpython/pull/98743
with warnings.catch_warnings():
if sys.version_info[:3] == (3, 11, 0):
warnings.filterwarnings('ignore', 'check_home argument is deprecated and ignored.', DeprecationWarning)
self.create(env_dir)
# Free-threaded Python 3.13 requires pip 24.1b1 or later.
if sysconfig.get_config_var('Py_GIL_DISABLED'):
if packaging.version.Version(importlib.metadata.version('pip')) < packaging.version.Version('24.1b1'):
self.pip('install', '--upgrade', 'pip >= 24.1b1')
def ensure_directories(self, env_dir):
context = super().ensure_directories(env_dir)
# Store the path to the venv Python interpreter. There does
# not seem to be a way to do this without subclassing.
self.executable = context.env_exe
return context
def python(self, *args: str):
return subprocess.check_output([self.executable, *args]).decode()
def pip(self, *args: str):
return self.python('-m', 'pip', *args)
@pytest.fixture()
def venv(tmp_path_factory):
path = pathlib.Path(tmp_path_factory.mktemp('mesonpy-test-venv'))
return VEnv(path)
def generate_package_fixture(package):
@pytest.fixture
def fixture():
with chdir(package_dir / package) as new_path:
yield new_path
return fixture
def generate_sdist_fixture(package):
@pytest.fixture(scope='session')
def fixture(tmp_path_session):
with chdir(package_dir / package), in_git_repo_context():
return tmp_path_session / mesonpy.build_sdist(tmp_path_session)
return fixture
def generate_wheel_fixture(package):
@pytest.fixture(scope='session')
def fixture(tmp_path_session):
with chdir(package_dir / package):
return tmp_path_session / mesonpy.build_wheel(tmp_path_session)
return fixture
def generate_editable_fixture(package):
@pytest.fixture(scope='session')
def fixture(tmp_path_session):
shutil.rmtree(package_dir / package / '.mesonpy' / 'editable', ignore_errors=True)
with chdir(package_dir / package):
return tmp_path_session / mesonpy.build_editable(tmp_path_session)
return fixture
# inject {package,sdist,wheel}_* fixtures (https://github.com/pytest-dev/pytest/issues/2424)
for package in os.listdir(package_dir):
normalized = package.replace('-', '_')
globals()[f'package_{normalized}'] = generate_package_fixture(package)
globals()[f'sdist_{normalized}'] = generate_sdist_fixture(package)
globals()[f'wheel_{normalized}'] = generate_wheel_fixture(package)
globals()[f'editable_{normalized}'] = generate_editable_fixture(package)
@pytest.fixture(autouse=True, scope='session')
def disable_pip_version_check():
# Cannot use the 'monkeypatch' fixture because of scope mismatch.
mpatch = pytest.MonkeyPatch()
yield mpatch.setenv('PIP_DISABLE_PIP_VERSION_CHECK', '1')
mpatch.undo()
@pytest.fixture(autouse=True, scope='session')
def cleanenv():
# Cannot use the 'monkeypatch' fixture because of scope mismatch.
mpatch = pytest.MonkeyPatch()
# $MACOSX_DEPLOYMENT_TARGET affects the computation of the platform tag on macOS.
yield mpatch.delenv('MACOSX_DEPLOYMENT_TARGET', raising=False)
mpatch.undo()
@pytest.fixture(autouse=True, scope='session')
def meson_fatal_warnings():
# Cannot use the 'monkeypatch' fixture because of scope mismatch.
mpatch = pytest.MonkeyPatch()
mesonpy_project_init = mesonpy.Project.__init__
def __init__(self, source_dir, build_dir, meson_args=None, editable_verbose=False):
if pathlib.Path(source_dir).absolute().name not in {
# The CMake subproject emits ``WARNING: CMake Toolchain:
# Failed to determine CMake compilers state`` on some
# systems. This is probably related to missing Rust or ObjC
# toolchains.
'cmake-subproject',
# The ``link-against-local-lib`` package uses linker arguments
# to add RPATH entries. This functionality is deprecated in
# Meson but it is used in the wild thus we should make sure it
# keeps working.
'link-against-local-lib',
}:
if meson_args is None:
meson_args = {}
meson_args.setdefault('setup', []).append('--fatal-meson-warnings')
mesonpy_project_init(self, source_dir, build_dir, meson_args, editable_verbose)
mpatch.setattr(mesonpy.Project, '__init__', __init__)
|