| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright © 2024 Intel Corporation |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
import subprocess |
| 6 |
import os |
| 7 |
import shutil |
| 8 |
import unittest |
| 9 |
import functools |
| 10 |
import re |
| 11 |
import typing as T |
| 12 |
import zipfile |
| 13 |
from pathlib import Path |
| 14 |
from contextlib import contextmanager |
| 15 |
from unittest import mock |
| 16 |
|
| 17 |
from mesonbuild.compilers import compiler_from_language |
| 18 |
from mesonbuild.mesonlib import ( |
| 19 |
MachineChoice, is_osx, is_cygwin, OrderedSet, EnvironmentException, |
| 20 |
) |
| 21 |
from mesonbuild.options import OptionKey |
| 22 |
from run_tests import get_fake_env |
| 23 |
|
| 24 |
if T.TYPE_CHECKING: |
| 25 |
from typing_extensions import ParamSpec |
| 26 |
|
| 27 |
from mesonbuild.compilers import Compiler |
| 28 |
from mesonbuild.compilers.compilers import CompilerDict, Language |
| 29 |
|
| 30 |
P = ParamSpec('P') |
| 31 |
R = T.TypeVar('R') |
| 32 |
|
| 33 |
|
| 34 |
IS_CI = os.environ.get('MESON_CI_JOBNAME', 'thirdparty') != 'thirdparty' |
| 35 |
|
| 36 |
|
| 37 |
class _CompilerSkip: |
| 38 |
|
| 39 |
"""Helper class for skipping based on whether the C compiler supports a |
| 40 |
compiler option. |
| 41 |
|
| 42 |
Known limits: |
| 43 |
- only checks a C compiler |
| 44 |
- only checks the host machine |
| 45 |
""" |
| 46 |
|
| 47 |
def __init__(self) -> None: |
| 48 |
self._env = get_fake_env() |
| 49 |
self._cache: CompilerDict = {} |
| 50 |
|
| 51 |
def _compiler(self, lang: Language) -> T.Optional[Compiler]: |
| 52 |
try: |
| 53 |
return self._cache[lang] |
| 54 |
except KeyError: |
| 55 |
try: |
| 56 |
comp = compiler_from_language(self._env, lang, MachineChoice.HOST) |
| 57 |
except EnvironmentException: |
| 58 |
comp = None |
| 59 |
self._cache[lang] = comp |
| 60 |
return comp |
| 61 |
|
| 62 |
def require_base_opt(self, feature: str) -> T.Callable[[T.Callable[P, R]], T.Callable[P, R]]: |
| 63 |
"""Skip tests if the compiler does not support a given base option. |
| 64 |
|
| 65 |
for example, ICC doesn't currently support b_sanitize. |
| 66 |
""" |
| 67 |
def actual(f: T.Callable[P, R]) -> T.Callable[P, R]: |
| 68 |
key = OptionKey(feature) |
| 69 |
|
| 70 |
@functools.wraps(f) |
| 71 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> R: |
| 72 |
comp = self._compiler('c') |
| 73 |
assert comp is not None |
| 74 |
if key not in comp.base_options: |
| 75 |
raise unittest.SkipTest( |
| 76 |
f'{feature} not available with {comp.id}') |
| 77 |
|
| 78 |
return f(*args, **kwargs) |
| 79 |
return wrapped |
| 80 |
return actual |
| 81 |
|
| 82 |
def require_language(self, lang: Language) -> T.Callable[[T.Callable[P, R]], T.Callable[P, R]]: |
| 83 |
def wrapper(func: T.Callable[P, R]) -> T.Callable[P, R]: |
| 84 |
@functools.wraps(func) |
| 85 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> R: |
| 86 |
if not self._compiler(lang): |
| 87 |
raise unittest.SkipTest(f'No {lang} compiler found.') |
| 88 |
return func(*args, **kwargs) |
| 89 |
return wrapped |
| 90 |
return wrapper |
| 91 |
|
| 92 |
|
| 93 |
_compiler = _CompilerSkip() |
| 94 |
skip_if_not_base_option = _compiler.require_base_opt |
| 95 |
skip_if_not_language = _compiler.require_language |
| 96 |
|
| 97 |
|
| 98 |
class _PkgConfigSkip: |
| 99 |
|
| 100 |
def __init__(self) -> None: |
| 101 |
self.pkgconf = shutil.which('pkg-config') or shutil.which('pkgconf') |
| 102 |
self.depcache: T.Dict[str, bool] = {} |
| 103 |
|
| 104 |
def require_pkgconf(self, f: T.Callable[P, R]) -> T.Callable[P, R]: |
| 105 |
''' |
| 106 |
Skip this test if no pkg-config is found, unless we're on CI. |
| 107 |
This allows users to run our test suite without having |
| 108 |
pkg-config installed on, f.ex., macOS, while ensuring that our CI does not |
| 109 |
silently skip the test because of misconfiguration. |
| 110 |
|
| 111 |
Note: Yes, we provide pkg-config even while running Windows CI |
| 112 |
''' |
| 113 |
if IS_CI: |
| 114 |
return f |
| 115 |
|
| 116 |
@functools.wraps(f) |
| 117 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> R: |
| 118 |
if self.pkgconf is None: |
| 119 |
raise unittest.SkipTest('pkg-config not found') |
| 120 |
return f(*args, **kwargs) |
| 121 |
return wrapped |
| 122 |
|
| 123 |
def _has_dep(self, depname: str) -> bool: |
| 124 |
try: |
| 125 |
return self.depcache[depname] |
| 126 |
except KeyError: |
| 127 |
found = subprocess.call([self.pkgconf, '--exists', depname]) == 0 |
| 128 |
self.depcache[depname] = found |
| 129 |
return found |
| 130 |
|
| 131 |
def require_dep(self, depname: str) -> T.Callable[[T.Callable[P, R]], T.Callable[P, R]]: |
| 132 |
''' |
| 133 |
Skip this test if the given pkg-config dep is not found, unless we're on CI. |
| 134 |
''' |
| 135 |
def wrapper(func: T.Callable[P, R]) -> T.Callable[P, R]: |
| 136 |
if IS_CI: |
| 137 |
return func |
| 138 |
|
| 139 |
@functools.wraps(func) |
| 140 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> R: |
| 141 |
if self.pkgconf is None: |
| 142 |
raise unittest.SkipTest('pkg-config not found') |
| 143 |
if not self._has_dep(depname): |
| 144 |
raise unittest.SkipTest(f'pkg-config dependency {depname} not found.') |
| 145 |
return func(*args, **kwargs) |
| 146 |
return wrapped |
| 147 |
return wrapper |
| 148 |
|
| 149 |
|
| 150 |
_pkgconf = _PkgConfigSkip() |
| 151 |
skipIfNoPkgconfig = _pkgconf.require_pkgconf |
| 152 |
skipIfNoPkgconfigDep = _pkgconf.require_dep |
| 153 |
|
| 154 |
|
| 155 |
class _ExecutableHelper: |
| 156 |
|
| 157 |
def __init__(self) -> None: |
| 158 |
self._cache: T.Dict[str, bool] = {} |
| 159 |
|
| 160 |
def _exists(self, name: str) -> bool: |
| 161 |
try: |
| 162 |
return self._cache[name] |
| 163 |
except KeyError: |
| 164 |
found = shutil.which(name) is not None |
| 165 |
self._cache[name] = found |
| 166 |
return found |
| 167 |
|
| 168 |
def require_cmake(self, f: T.Callable[P, R]) -> T.Callable[P, R]: |
| 169 |
''' |
| 170 |
Skip this test if no cmake is found, unless we're on CI. |
| 171 |
This allows users to run our test suite without having |
| 172 |
cmake installed on, f.ex., macOS, while ensuring that our CI does not |
| 173 |
silently skip the test because of misconfiguration. |
| 174 |
''' |
| 175 |
if IS_CI: |
| 176 |
return f |
| 177 |
|
| 178 |
@functools.wraps(f) |
| 179 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> R: |
| 180 |
if not self._exists('cmake'): |
| 181 |
raise unittest.SkipTest('cmake not found') |
| 182 |
return f(*args, **kwargs) |
| 183 |
return wrapped |
| 184 |
|
| 185 |
def require_executable(self, exename: str) -> T.Callable[[T.Callable[P, R]], T.Callable[P, R]]: |
| 186 |
''' |
| 187 |
Skip this test if the given executable is not found. |
| 188 |
''' |
| 189 |
def wrapper(func: T.Callable[P, R]) -> T.Callable[P, R]: |
| 190 |
@functools.wraps(func) |
| 191 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> R: |
| 192 |
if not self._exists(exename): |
| 193 |
raise unittest.SkipTest(exename + ' not found') |
| 194 |
return func(*args, **kwargs) |
| 195 |
return wrapped |
| 196 |
return wrapper |
| 197 |
|
| 198 |
|
| 199 |
_exe = _ExecutableHelper() |
| 200 |
skip_if_no_cmake = _exe.require_cmake |
| 201 |
skipIfNoExecutable = _exe.require_executable |
| 202 |
|
| 203 |
|
| 204 |
def skip_if_env_set(key: str) -> T.Callable[[T.Callable[P, R]], T.Callable[P, R]]: |
| 205 |
''' |
| 206 |
Skip a test if a particular env is set, except when running under CI |
| 207 |
''' |
| 208 |
def wrapper(func: T.Callable[P, R]) -> T.Callable[P, R]: |
| 209 |
@functools.wraps(func) |
| 210 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> R: |
| 211 |
if not IS_CI and key in os.environ: |
| 212 |
raise unittest.SkipTest(f'Env var {key!r} set, skipping') |
| 213 |
with mock.patch.dict(os.environ): |
| 214 |
os.environ.pop(key, None) |
| 215 |
return func(*args, **kwargs) |
| 216 |
return wrapped |
| 217 |
return wrapper |
| 218 |
|
| 219 |
|
| 220 |
def is_tarball() -> bool: |
| 221 |
return not os.path.isdir('docs') |
| 222 |
|
| 223 |
|
| 224 |
@contextmanager |
| 225 |
def chdir(path: str) -> T.Iterator[None]: |
| 226 |
curdir = os.getcwd() |
| 227 |
os.chdir(path) |
| 228 |
try: |
| 229 |
yield |
| 230 |
finally: |
| 231 |
os.chdir(curdir) |
| 232 |
|
| 233 |
|
| 234 |
def get_dynamic_section_entry(fname: str, entry: str) -> T.Optional[str]: |
| 235 |
if is_cygwin() or is_osx(): |
| 236 |
raise unittest.SkipTest('Test only applicable to ELF platforms') |
| 237 |
|
| 238 |
try: |
| 239 |
raw_out = subprocess.check_output(['readelf', '-d', fname], |
| 240 |
encoding='utf-8', universal_newlines=True) |
| 241 |
except FileNotFoundError: |
| 242 |
# FIXME: Try using depfixer.py:Elf() as a fallback |
| 243 |
raise unittest.SkipTest('readelf not found') |
| 244 |
pattern = re.compile(entry + r': \[(.*?)\]') |
| 245 |
for line in raw_out.split('\n'): |
| 246 |
m = pattern.search(line) |
| 247 |
if m is not None: |
| 248 |
return str(m.group(1)) |
| 249 |
return None # The file did not contain the specified entry. |
| 250 |
|
| 251 |
|
| 252 |
def get_soname(fname: str) -> T.Optional[str]: |
| 253 |
return get_dynamic_section_entry(fname, 'soname') |
| 254 |
|
| 255 |
|
| 256 |
def get_rpath(fname: str) -> T.Optional[str]: |
| 257 |
raw = get_dynamic_section_entry(fname, r'(?:rpath|runpath)') |
| 258 |
# Get both '' and None here |
| 259 |
if not raw: |
| 260 |
return None |
| 261 |
# nix/nixos adds a bunch of stuff to the rpath out of necessity that we |
| 262 |
# don't check for, so clear those |
| 263 |
final = ':'.join([e for e in raw.split(':') if not e.startswith('/nix')]) |
| 264 |
# If we didn't end up anything but nix paths, return None here |
| 265 |
if not final: |
| 266 |
return None |
| 267 |
return final |
| 268 |
|
| 269 |
|
| 270 |
def get_classpath(fname: str) -> T.Optional[str]: |
| 271 |
with zipfile.ZipFile(fname) as zip: |
| 272 |
with zip.open('META-INF/MANIFEST.MF') as member: |
| 273 |
contents = member.read().decode().strip() |
| 274 |
lines: T.List[str] = [] |
| 275 |
for line in contents.splitlines(): |
| 276 |
if line.startswith(' '): |
| 277 |
# continuation line |
| 278 |
lines[-1] += line[1:] |
| 279 |
else: |
| 280 |
lines.append(line) |
| 281 |
manifest = { |
| 282 |
k.lower(): v.strip() for k, v in [l.split(':', 1) for l in lines] |
| 283 |
} |
| 284 |
return manifest.get('class-path') |
| 285 |
|
| 286 |
|
| 287 |
def get_path_without_cmd(cmd: str, path: str) -> str: |
| 288 |
pathsep = os.pathsep |
| 289 |
paths = OrderedSet([Path(p).resolve() for p in path.split(pathsep)]) |
| 290 |
while True: |
| 291 |
full_path = shutil.which(cmd, path=path) |
| 292 |
if full_path is None: |
| 293 |
break |
| 294 |
dirname = Path(full_path).resolve().parent |
| 295 |
paths.discard(dirname) |
| 296 |
path = pathsep.join([str(p) for p in paths]) |
| 297 |
return path |
| 298 |
|
| 299 |
|
| 300 |
def xfail_if_jobname(name: str) -> T.Callable[[T.Callable[P, R]], T.Callable[P, R]]: |
| 301 |
if os.environ.get('MESON_CI_JOBNAME') == name: |
| 302 |
return unittest.expectedFailure |
| 303 |
|
| 304 |
def wrapper(func: T.Callable[P, R]) -> T.Callable[P, R]: |
| 305 |
return func |
| 306 |
return wrapper |