Debian Codegraph @

run_tests.py

raw
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: Apache-2.0
3 # Copyright 2012-2021 The Meson development team
4 # Copyright © 2023-2024 Intel Corporation
5
6 from __future__ import annotations
7
8 # Work around some pathlib bugs...
9 from mesonbuild import _pathlib
10 import sys
11 sys.modules['pathlib'] = _pathlib
12
13 import collections
14 import os
15 import time
16 import shutil
17 import subprocess
18 import platform
19 import argparse
20 import traceback
21 from io import StringIO
22 from enum import Enum
23 from glob import glob
24 from pathlib import Path
25 from unittest import mock
26 import typing as T
27
28 from mesonbuild.compilers.c import CCompiler
29 from mesonbuild.compilers.detect import detect_c_compiler
30 from mesonbuild.dependencies.pkgconfig import PkgConfigInterface
31 from mesonbuild import mesonlib
32 from mesonbuild import mesonmain
33 from mesonbuild import mtest
34 from mesonbuild import mlog
35 from mesonbuild.environment import Environment
36 from mesonbuild.envconfig import detect_machine_info
37 from mesonbuild.tooldetect import detect_ninja
38 from mesonbuild.coredata import version as meson_version
39 from mesonbuild.options import backendlist
40 from mesonbuild.mesonlib import setup_vsenv
41 from mesonbuild.options import OptionKey
42
43 if T.TYPE_CHECKING:
44 from mesonbuild.coredata import SharedCMDOptions
45
46 NINJA_1_12_OR_NEWER = False
47 NINJA_CMD = None
48 # If we're on CI, detecting ninja for every subprocess unit test that we run is slow
49 # Optimize this by respecting $NINJA and skipping detection, then exporting it on
50 # first run.
51 try:
52 NINJA_1_12_OR_NEWER = bool(int(os.environ['NINJA_1_12_OR_NEWER']))
53 NINJA_CMD = [os.environ['NINJA']]
54 except (KeyError, ValueError):
55 # Look for 1.12, which removes -w dupbuild=err
56 NINJA_CMD = detect_ninja('1.12')
57 if NINJA_CMD is not None:
58 NINJA_1_12_OR_NEWER = True
59 else:
60 NINJA_CMD = detect_ninja()
61
62 if NINJA_CMD is not None:
63 os.environ['NINJA_1_12_OR_NEWER'] = str(int(NINJA_1_12_OR_NEWER))
64 os.environ['NINJA'] = NINJA_CMD[0]
65 else:
66 raise RuntimeError('Could not find Ninja.')
67
68 # Emulate running meson with -X utf8 by making sure all open() calls have a
69 # sane encoding. This should be a python default, but PEP 540 considered it not
70 # backwards compatible. Instead, much line noise in diffs to update this, and in
71 # python 3.10 we can also make it a warning when absent.
72 os.environ['PYTHONWARNDEFAULTENCODING'] = '1'
73 # work around https://bugs.python.org/issue34624
74 os.environ['MESON_RUNNING_IN_PROJECT_TESTS'] = '1'
75 # python 3.11 adds a warning that in 3.15, UTF-8 mode will be default.
76 # This is fantastic news, we'd love that. Less fantastic: this warning is silly,
77 # we *want* these checks to be affected. Plus, the recommended alternative API
78 # would (in addition to warning people when UTF-8 mode removed the problem) also
79 # require using a minimum python version of 3.11 (in which the warning was added)
80 # or add verbose if/else soup.
81 if sys.version_info >= (3, 10):
82 import warnings
83 warnings.filterwarnings('ignore', message="UTF-8 Mode affects .*getpreferredencoding", category=EncodingWarning)
84
85 def guess_backend(backend_str: str, msbuild_exe: str) -> T.Tuple['Backend', T.List[str]]:
86 # Auto-detect backend if unspecified
87 backend_flags = []
88 if backend_str is None:
89 if msbuild_exe is not None and (mesonlib.is_windows() and not _using_intelcl()):
90 backend_str = 'vs' # Meson will auto-detect VS version to use
91 else:
92 backend_str = 'ninja'
93
94 # Set backend arguments for Meson
95 if backend_str.startswith('vs'):
96 backend_flags = ['--backend=' + backend_str]
97 backend = Backend.vs
98 elif backend_str == 'xcode':
99 backend_flags = ['--backend=xcode']
100 backend = Backend.xcode
101 elif backend_str == 'ninja':
102 backend_flags = ['--backend=ninja']
103 backend = Backend.ninja
104 else:
105 raise RuntimeError(f'Unknown backend: {backend_str!r}')
106 return (backend, backend_flags)
107
108
109 def _using_intelcl() -> bool:
110 """
111 detect if intending to using Intel-Cl compilers (Intel compilers on Windows)
112 Sufficient evidence of intent is that user is working in the Intel compiler
113 shell environment, otherwise this function returns False
114 """
115 if not mesonlib.is_windows():
116 return False
117 # handle where user tried to "blank" MKLROOT and left space(s)
118 if not os.environ.get('MKLROOT', '').strip():
119 return False
120 if (os.environ.get('CC') == 'icl' or
121 os.environ.get('CXX') == 'icl' or
122 os.environ.get('FC') == 'ifort'):
123 return True
124 # Intel-Cl users might not have the CC,CXX,FC envvars set,
125 # but because they're in Intel shell, the exe's below are on PATH
126 if shutil.which('icl') or shutil.which('ifort'):
127 return True
128 mlog.warning('It appears you might be intending to use Intel compiler on Windows '
129 'since non-empty environment variable MKLROOT is set to {} '
130 'However, Meson cannot find the Intel WIndows compiler executables (icl,ifort).'
131 'Please try using the Intel shell.'.format(os.environ.get('MKLROOT')))
132 return False
133
134
135 # Fake classes and objects for mocking
136 class FakeBuild:
137 def __init__(self, env):
138 self.environment = env
139 self.machine_map = env.machine_map
140
141 def get_fake_options(prefix: str = '') -> SharedCMDOptions:
142 opts = T.cast('SharedCMDOptions', argparse.Namespace())
143 opts.native_file = []
144 opts.cross_file = None
145 opts.wrap_mode = None
146 opts.prefix = prefix
147 opts.cmd_line_options = {}
148 return opts
149
150 def get_fake_env(sdir: str = '', bdir: T.Optional[str] = None, prefix: str = '',
151 opts: T.Optional[SharedCMDOptions] = None) -> Environment:
152 if opts is None:
153 opts = get_fake_options(prefix)
154 env = Environment(sdir, bdir, opts)
155 env.machines.host.cpu_family = 'x86_64' # Used on macOS inside find_library
156 # Invalidate cache when using a different Environment object.
157 clear_meson_configure_class_caches()
158 return env
159
160 def get_convincing_fake_env_and_cc(bdir, prefix):
161 '''
162 Return a fake env and C compiler with the fake env
163 machine info properly detected using that compiler.
164 Useful for running compiler checks in the unit tests.
165 '''
166 env = get_fake_env('', bdir, prefix)
167 cc = detect_c_compiler(env, mesonlib.MachineChoice.HOST)
168 # Detect machine info
169 env.machines.host = detect_machine_info({'c':cc})
170 return (env, cc)
171
172 Backend = Enum('Backend', 'ninja vs xcode')
173
174 if 'MESON_EXE' in os.environ:
175 meson_exe = mesonlib.split_args(os.environ['MESON_EXE'])
176 else:
177 meson_exe = None
178
179 if mesonlib.is_windows() or mesonlib.is_cygwin():
180 exe_suffix = '.exe'
181 else:
182 exe_suffix = ''
183
184 def handle_meson_skip_test(out: str) -> T.Tuple[bool, str]:
185 for line in out.splitlines():
186 for prefix in {'Problem encountered', 'Assert failed', 'Failed to configure the CMake subproject'}:
187 if f'{prefix}: MESON_SKIP_TEST' in line:
188 offset = line.index('MESON_SKIP_TEST') + 16
189 reason = line[offset:].strip()
190 return (True, reason)
191 return (False, '')
192
193 def get_meson_script() -> str:
194 '''
195 Guess the meson that corresponds to the `mesonbuild` that has been imported
196 so we can run configure and other commands in-process, since mesonmain.run
197 needs to know the meson_command to use.
198
199 Also used by run_unittests.py to determine what meson to run when not
200 running in-process (which is the default).
201 '''
202 # Is there a meson.py next to the mesonbuild currently in use?
203 mesonbuild_dir = Path(mesonmain.__file__).resolve().parent.parent
204 meson_script = mesonbuild_dir / 'meson.py'
205 if meson_script.is_file():
206 return str(meson_script)
207 # Then if mesonbuild is in PYTHONPATH, meson must be in PATH
208 mlog.warning('Could not find meson.py next to the mesonbuild module. '
209 'Trying system meson...')
210 meson_cmd = shutil.which('meson')
211 if meson_cmd:
212 return meson_cmd
213 raise RuntimeError(f'Could not find {meson_script!r} or a meson in PATH')
214
215 def get_backend_args_for_dir(backend: Backend, builddir: str) -> T.List[str]:
216 '''
217 Visual Studio backend needs to be given the solution to build
218 '''
219 if backend is Backend.vs:
220 sln_name = glob(os.path.join(builddir, '*.sln'))[0]
221 return [os.path.split(sln_name)[-1]]
222 return []
223
224 def find_vcxproj_with_target(builddir, target):
225 import re, fnmatch
226 t, ext = os.path.splitext(target)
227 if ext:
228 p = fr'<TargetName>{t}</TargetName>\s*<TargetExt>\{ext}</TargetExt>'
229 else:
230 p = fr'<TargetName>{t}</TargetName>'
231 for _, _, files in os.walk(builddir):
232 for f in fnmatch.filter(files, '*.vcxproj'):
233 f = os.path.join(builddir, f)
234 with open(f, encoding='utf-8') as o:
235 if re.search(p, o.read(), flags=re.MULTILINE):
236 return f
237 raise RuntimeError(f'No vcxproj matching {p!r} in {builddir!r}')
238
239 def get_builddir_target_args(backend: Backend, builddir, target):
240 dir_args = []
241 if not target:
242 dir_args = get_backend_args_for_dir(backend, builddir)
243 if target is None:
244 return dir_args
245 if backend is Backend.vs:
246 vcxproj = find_vcxproj_with_target(builddir, target)
247 target_args = [vcxproj]
248 elif backend is Backend.xcode:
249 target_args = ['-target', target]
250 elif backend is Backend.ninja:
251 target_args = [target]
252 else:
253 raise AssertionError(f'Unknown backend: {backend!r}')
254 return target_args + dir_args
255
256 def get_backend_commands(backend: Backend, debug: bool = False) -> \
257 T.Tuple[T.List[str], T.List[str], T.List[str], T.List[str], T.List[str]]:
258 install_cmd: T.List[str] = []
259 uninstall_cmd: T.List[str] = []
260 clean_cmd: T.List[str]
261 cmd: T.List[str]
262 test_cmd: T.List[str]
263 if backend is Backend.vs:
264 cmd = ['msbuild']
265 clean_cmd = cmd + ['/target:Clean']
266 test_cmd = cmd + ['RUN_TESTS.vcxproj']
267 elif backend is Backend.xcode:
268 cmd = ['xcodebuild']
269 clean_cmd = cmd + ['-alltargets', 'clean']
270 test_cmd = cmd + ['-target', 'RUN_TESTS']
271 elif backend is Backend.ninja:
272 global NINJA_CMD
273 cmd = NINJA_CMD + ['-d', 'explain']
274 if not NINJA_1_12_OR_NEWER:
275 cmd += ['-w', 'dupbuild=err']
276 if debug:
277 cmd += ['-v']
278 clean_cmd = cmd + ['clean']
279 test_cmd = cmd + ['test', 'benchmark']
280 install_cmd = cmd + ['install']
281 uninstall_cmd = cmd + ['uninstall']
282 else:
283 raise AssertionError(f'Unknown backend: {backend!r}')
284 return cmd, clean_cmd, test_cmd, install_cmd, uninstall_cmd
285
286 def run_mtest_inprocess(commandlist: T.List[str]) -> T.Tuple[int, str]:
287 out = StringIO()
288 with mock.patch.object(sys, 'stdout', out), mock.patch.object(sys, 'stderr', out):
289 returncode = mtest.run_with_args(commandlist)
290 return returncode, out.getvalue()
291
292 def clear_meson_configure_class_caches() -> None:
293 CCompiler.find_library_cache.clear()
294 CCompiler.find_framework_cache.clear()
295 PkgConfigInterface.class_impl.assign({}, {})
296 mesonlib.project_meson_versions.clear()
297
298 def run_configure_inprocess(commandlist: T.List[str], env: T.Optional[T.Dict[str, str]] = None, catch_exception: bool = False) -> T.Tuple[int, str, str]:
299 stderr = StringIO()
300 stdout = StringIO()
301 returncode = 0
302 with mock.patch.dict(os.environ, env or {}), mock.patch.object(sys, 'stdout', stdout), mock.patch.object(sys, 'stderr', stderr):
303 try:
304 returncode = mesonmain.run(commandlist, get_meson_script())
305 except Exception:
306 if catch_exception:
307 returncode = 1
308 traceback.print_exc()
309 else:
310 raise
311 finally:
312 clear_meson_configure_class_caches()
313 return returncode, stdout.getvalue(), stderr.getvalue()
314
315 def run_configure_external(full_command: T.List[str], env: T.Optional[T.Dict[str, str]] = None) -> T.Tuple[int, str, str]:
316 pc, o, e = mesonlib.Popen_safe(full_command, env=env)
317 return pc.returncode, o, e
318
319 def run_configure(commandlist: T.List[str], env: T.Optional[T.Dict[str, str]] = None, catch_exception: bool = False) -> T.Tuple[bool, T.Tuple[int, str, str]]:
320 global meson_exe
321 if meson_exe:
322 return (False, run_configure_external(meson_exe + commandlist, env=env))
323 return (True, run_configure_inprocess(commandlist, env=env, catch_exception=catch_exception))
324
325 def print_system_info():
326 print(mlog.bold('System information.'))
327 print('Architecture:', platform.architecture())
328 print('Machine:', platform.machine())
329 print('Platform:', platform.system())
330 print('Processor:', platform.processor())
331 print('System:', platform.system())
332 print('')
333 print(flush=True)
334
335 def subprocess_call(cmd, **kwargs):
336 print(f'$ {mesonlib.join_args(cmd)}')
337 return subprocess.call(cmd, **kwargs)
338
339 def main():
340 print_system_info()
341 parser = argparse.ArgumentParser()
342 parser.add_argument('--backend', default=None, dest='backend',
343 choices=backendlist)
344 parser.add_argument('--cross', default=[], dest='cross', action='append')
345 parser.add_argument('--cross-only', action='store_true')
346 parser.add_argument('--failfast', action='store_true')
347 parser.add_argument('--no-unittests', action='store_true', default=False)
348 (options, _) = parser.parse_known_args()
349 returncode = 0
350 _, backend_flags = guess_backend(options.backend, shutil.which('msbuild'))
351 no_unittests = options.no_unittests
352 # Running on a developer machine? Be nice!
353 if not mesonlib.is_windows() and not mesonlib.is_haiku() and 'CI' not in os.environ:
354 os.nice(20)
355 # Appveyor sets the `platform` environment variable which completely messes
356 # up building with the vs2010 and vs2015 backends.
357 #
358 # Specifically, MSBuild reads the `platform` environment variable to set
359 # the configured value for the platform (Win32/x64/arm), which breaks x86
360 # builds.
361 #
362 # Appveyor setting this also breaks our 'native build arch' detection for
363 # Windows in environment.py:detect_windows_arch() by overwriting the value
364 # of `platform` set by vcvarsall.bat.
365 #
366 # While building for x86, `platform` should be unset.
367 if 'APPVEYOR' in os.environ and os.environ['arch'] == 'x86':
368 os.environ.pop('platform')
369 # Run tests
370 # Can't pass arguments to unit tests, so set the backend to use in the environment
371 env = os.environ.copy()
372 if not options.cross:
373 cmd = mesonlib.python_command + ['run_meson_command_tests.py', '-v']
374 if options.failfast:
375 cmd += ['--failfast']
376 returncode += subprocess_call(cmd, env=env)
377 if options.failfast and returncode != 0:
378 return returncode
379 if no_unittests:
380 print('Skipping all unit tests.')
381 print(flush=True)
382 returncode = 0
383 else:
384 print(mlog.bold('Running unittests.'))
385 print(flush=True)
386 cmd = mesonlib.python_command + ['run_unittests.py'] + backend_flags
387 if options.failfast:
388 cmd += ['--failfast']
389 returncode += subprocess_call(cmd, env=env)
390 if options.failfast and returncode != 0:
391 return returncode
392 cmd = mesonlib.python_command + ['run_project_tests.py'] + sys.argv[1:]
393 returncode += subprocess_call(cmd, env=env)
394 else:
395 cross_test_args = mesonlib.python_command + ['run_cross_test.py']
396 for cf in options.cross:
397 print(mlog.bold(f'Running {cf} cross tests.'))
398 print(flush=True)
399 cmd = cross_test_args + ['cross/' + cf]
400 if options.failfast:
401 cmd += ['--failfast']
402 if options.cross_only:
403 cmd += ['--cross-only']
404 returncode += subprocess_call(cmd, env=env)
405 if options.failfast and returncode != 0:
406 return returncode
407 return returncode
408
409 if __name__ == '__main__':
410 setup_vsenv()
411 print('Meson build system', meson_version, 'Project and Unit Tests')
412 raise SystemExit(main())