Debian Codegraph @

run_project_tests.py

raw
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: Apache-2.0
3 # Copyright 2012-2021 The Meson development team
4
5 from __future__ import annotations
6
7 # Work around some pathlib bugs...
8 from mesonbuild import _pathlib
9 import sys
10 sys.modules['pathlib'] = _pathlib
11
12 from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, CancelledError, as_completed
13 from enum import Enum
14 from io import StringIO
15 from pathlib import Path, PurePath
16 import argparse
17 import functools
18 import itertools
19 import json
20 import multiprocessing
21 import os
22 import re
23 import shlex
24 import shutil
25 import signal
26 import subprocess
27 import tempfile
28 import time
29 import typing as T
30 import collections
31 import importlib.util
32
33 # use lxml, if available, otherwise fallback to xml.etree
34 try:
35 import lxml.etree as ET
36 except ImportError:
37 # assert that happens somewhere in our CI (although not everywhere, as we
38 # don't want to have to always install lxml), so that the validation which
39 # requires it, gets run.
40 if os.environ.get('MESON_CI_JOBNAME', 'thirdparty') == 'linux-fedora-gcc':
41 raise
42
43 import xml.etree.ElementTree as ET # type: ignore
44
45 from mesonbuild import build
46 from mesonbuild import environment
47 from mesonbuild import compilers
48 from mesonbuild import mesonlib
49 from mesonbuild import mlog
50 from mesonbuild import mtest
51 from mesonbuild.compilers import detect_compiler_for
52 from mesonbuild.build import ConfigurationData
53 from mesonbuild.mesonlib import MachineChoice, Popen_safe, TemporaryDirectoryWinProof, setup_vsenv
54 from mesonbuild.mlog import blue, bold, cyan, green, red, yellow, normal_green
55 from mesonbuild.coredata import version as meson_version
56 from mesonbuild.options import backendlist
57 from mesonbuild.modules.python import PythonExternalProgram
58 from run_tests import (
59 get_fake_options, run_configure, get_meson_script, get_backend_commands,
60 get_backend_args_for_dir, Backend,
61 guess_backend, handle_meson_skip_test,
62 )
63
64
65 if T.TYPE_CHECKING:
66 from types import FrameType
67 from concurrent.futures import Future
68
69 from mesonbuild._typing import Protocol
70 from mesonbuild.compilers.compilers import Compiler, Language
71
72 class CompilerArgumentType(Protocol):
73 cross_file: str
74 native_file: str
75 use_tmpdir: bool
76
77
78 class ArgumentType(CompilerArgumentType):
79
80 """Typing information for command line arguments."""
81
82 extra_args: T.List[str]
83 backend: str
84 num_workers: int
85 failfast: bool
86 no_unittests: bool
87 only: T.List[str]
88 v: bool
89
90 ALL_TESTS = ['cmake', 'common', 'native', 'warning-meson', 'failing-meson', 'failing-build', 'failing-test',
91 'keyval', 'platform-osx', 'platform-windows', 'platform-linux', 'platform-android',
92 'java', 'C#', 'vala', 'cython', 'rust', 'd', 'objective c', 'objective c++',
93 'fortran', 'swift', 'cuda', 'python3', 'python', 'fpga', 'frameworks', 'nasm', 'wasm', 'wayland',
94 'format', 'snippets',
95 ]
96
97
98 class BuildStep(Enum):
99 configure = 1
100 build = 2
101 test = 3
102 install = 4
103 clean = 5
104 validate = 6
105
106 verbose_output = False
107
108 class TestResult(BaseException):
109 def __init__(self, cicmds: T.List[str]) -> None:
110 self.msg = '' # empty msg indicates test success
111 self.stdo = ''
112 self.stde = ''
113 self.mlog = ''
114 self.cicmds = cicmds
115 self.conftime: float = 0
116 self.buildtime: float = 0
117 self.testtime: float = 0
118
119 def add_step(self, step: BuildStep, stdo: str, stde: str, mlog: str = '', time: float = 0) -> None:
120 self.step = step
121 self.stdo += stdo
122 self.stde += stde
123 self.mlog += mlog
124 if step == BuildStep.configure:
125 self.conftime = time
126 elif step == BuildStep.build:
127 self.buildtime = time
128 elif step == BuildStep.test:
129 self.testtime = time
130
131 def fail(self, msg: str) -> None:
132 self.msg = msg
133
134 python = PythonExternalProgram(sys.executable)
135 python.sanity()
136
137 class InstalledFile:
138 def __init__(self, raw: T.Dict[str, str]):
139 self.path = raw['file']
140 self.typ = raw['type']
141 self.platform = raw.get('platform', None)
142 self.language = raw.get('language', 'c')
143
144 version = raw.get('version', '')
145 if version:
146 self.version = version.split('.')
147 else:
148 # split on '' will return [''], we want an empty list though
149 self.version = []
150
151 def get_path(self, compiler: compilers.Compiler, env: environment.Environment) -> T.Optional[Path]:
152 p = Path(self.path)
153 canonical_compiler = compiler.get_id()
154 if ((canonical_compiler in ['clang-cl', 'intel-cl']) or
155 (env.machines.host.is_windows() and canonical_compiler in {'pgi', 'dmd', 'ldc'})):
156 canonical_compiler = 'msvc'
157
158 python_suffix = python.info['suffix']
159 python_limited_suffix = python.info['limited_api_suffix']
160 has_pdb = False
161 if self.language in {'c', 'cpp'}:
162 has_pdb = canonical_compiler == 'msvc'
163 elif self.language == 'd':
164 # dmd's optlink does not generate pdb files
165 has_pdb = env.coredata.compilers.host['d'].linker.id in {'link', 'lld-link'}
166
167 # Abort if the platform does not match
168 matches = {
169 'msvc': canonical_compiler == 'msvc',
170 'gcc': canonical_compiler != 'msvc',
171 'cygwin': env.machines.host.is_cygwin(),
172 '!cygwin': not env.machines.host.is_cygwin(),
173 'windows': env.machines.host.is_windows() or env.machines.host.is_cygwin(),
174 '!windows': not (env.machines.host.is_windows() or env.machines.host.is_cygwin()),
175 }.get(self.platform or '', True)
176 if not matches:
177 return None
178
179 # Handle the different types
180 if self.typ in {'py_implib', 'py_limited_implib', 'python_lib', 'python_limited_lib', 'python_file', 'python_bytecode'}:
181 val = p.as_posix()
182 val = val.replace('@PYTHON_PLATLIB@', python.platlib)
183 val = val.replace('@PYTHON_PURELIB@', python.purelib)
184 p = Path(val)
185 if self.typ == 'python_file':
186 return p
187 if self.typ == 'python_lib':
188 return p.with_suffix(python_suffix)
189 if self.typ == 'python_limited_lib':
190 return p.with_suffix(python_limited_suffix)
191 if self.typ == 'py_implib':
192 p = p.with_suffix(python_suffix)
193 if env.machines.host.is_windows() and canonical_compiler == 'msvc':
194 return p.with_suffix('.lib')
195 elif env.machines.host.is_windows() or env.machines.host.is_cygwin():
196 return p.with_suffix('.dll.a')
197 else:
198 return None
199 if self.typ == 'py_limited_implib':
200 p = p.with_suffix(python_limited_suffix)
201 if env.machines.host.is_windows() and canonical_compiler == 'msvc':
202 return p.with_suffix('.lib')
203 elif env.machines.host.is_windows() or env.machines.host.is_cygwin():
204 return p.with_suffix('.dll.a')
205 else:
206 return None
207 if self.typ == 'python_bytecode':
208 return p.parent / importlib.util.cache_from_source(p.name)
209 elif self.typ in {'file', 'dir', 'link'}:
210 return p
211 elif self.typ == 'shared_lib':
212 if env.machines.host.is_windows() or env.machines.host.is_cygwin():
213 # Windows only has foo.dll and foo-X.dll
214 if len(self.version) > 1:
215 return None
216 if self.version:
217 p = p.with_name('{}-{}'.format(p.name, self.version[0]))
218 return p.with_suffix('.dll')
219
220 p = p.with_name(f'lib{p.name}')
221 if env.machines.host.is_darwin():
222 # MacOS only has libfoo.dylib and libfoo.X.dylib
223 if len(self.version) > 1:
224 return None
225
226 # pathlib.Path.with_suffix replaces, not appends
227 suffix = '.dylib'
228 if self.version:
229 suffix = '.{}{}'.format(self.version[0], suffix)
230 else:
231 # pathlib.Path.with_suffix replaces, not appends
232 suffix = '.so'
233 if self.version:
234 suffix = '{}.{}'.format(suffix, '.'.join(self.version))
235 return p.with_suffix(suffix)
236 elif self.typ == 'exe':
237 if 'mwcc' in canonical_compiler:
238 return p.with_suffix('.nef')
239 elif env.machines.host.is_windows() or env.machines.host.is_cygwin():
240 return p.with_suffix('.exe')
241 elif self.typ == 'pdb':
242 if self.version:
243 p = p.with_name('{}-{}'.format(p.name, self.version[0]))
244 return p.with_suffix('.pdb') if has_pdb else None
245 elif self.typ in {'implib', 'implibempty'}:
246 if env.machines.host.is_windows() and canonical_compiler == 'msvc':
247 # only MSVC doesn't generate empty implibs
248 if self.typ == 'implibempty' and compiler.get_id() == 'msvc':
249 return None
250 return p.parent / (re.sub(r'^lib', '', p.name) + '.lib')
251 elif env.machines.host.is_windows() or env.machines.host.is_cygwin():
252 return p.with_suffix('.dll.a')
253 else:
254 return None
255 elif self.typ == 'expr':
256 return Path(platform_fix_name(p.as_posix(), canonical_compiler, env))
257 else:
258 raise RuntimeError(f'Invalid installed file type {self.typ}')
259
260 return p
261
262 def get_paths(self, compiler: compilers.Compiler, env: environment.Environment, installdir: Path) -> T.List[Path]:
263 p = self.get_path(compiler, env)
264 if not p:
265 return []
266 if self.typ == 'dir':
267 abs_p = installdir / p
268 if not abs_p.exists():
269 raise RuntimeError(f'{p} does not exist')
270 if not abs_p.is_dir():
271 raise RuntimeError(f'{p} is not a directory')
272 return [x.relative_to(installdir) for x in abs_p.rglob('*') if x.is_file() or x.is_symlink()]
273 elif self.typ == 'link':
274 abs_p = installdir / p
275 if not abs_p.is_symlink():
276 raise RuntimeError(f'{p} is not a symlink')
277 return [p]
278 else:
279 return [p]
280
281 @functools.total_ordering
282 class TestDef:
283 def __init__(self, path: Path, name: T.Optional[str], args: T.List[str], skip: bool, category: TestCategory):
284 self.category = category.category
285 self.path: Path = path
286 self.name = name # matrix instance name or None
287 self.args = args
288 self.skip = skip
289 self.env = os.environ.copy()
290 self.installed_files: T.List[InstalledFile] = []
291 self.do_not_set_opts: T.List[str] = []
292 self.stdout: T.List[T.Dict[str, str]] = []
293 self.skip_category = category.skip
294 self.skip_expected = False
295 self.cleanup: T.List[str] = []
296
297 # Always print a stack trace for Meson exceptions
298 self.env['MESON_FORCE_BACKTRACE'] = '1'
299
300 def __repr__(self) -> str:
301 return '<{}: {:<48} [{}: {}] -- {}>'.format(type(self).__name__, str(self.path), self.name, self.args, self.skip)
302
303 def display_name(self) -> mlog.TV_LoggableList:
304 # Remove the redundant 'test cases' part
305 section, id = self.path.parts[1:3]
306 res: mlog.TV_LoggableList = [f'{section}:', bold(id)]
307 if self.name:
308 res += [f' ({self.name})']
309 return res
310
311 def __lt__(self, other: object) -> bool:
312 if isinstance(other, TestDef):
313 # None is not sortable, so replace it with an empty string
314 s_id = int(self.path.name.split(' ')[0])
315 o_id = int(other.path.name.split(' ')[0])
316 return (s_id, self.path, self.name or '') < (o_id, other.path, other.name or '')
317 return NotImplemented
318
319 failing_testcases: T.List[str] = []
320 failing_logs: T.List[str] = []
321 print_debug = 'MESON_PRINT_TEST_OUTPUT' in os.environ
322 under_ci = 'CI' in os.environ
323 raw_ci_jobname = os.environ.get('MESON_CI_JOBNAME', None)
324 ci_jobname = raw_ci_jobname if raw_ci_jobname != 'thirdparty' else None
325 do_debug = under_ci or print_debug
326 no_meson_log_msg = 'No meson-log.txt found.'
327
328 compiler_id_map: T.Dict[str, str] = {}
329 all_compilers: mesonlib.PerMachine[T.Dict[Language, T.Optional[compilers.Compiler]]] = mesonlib.PerMachine({}, {})
330 tool_vers_map: T.Dict[str, str] = {}
331
332 compile_commands: T.List[str]
333 clean_commands: T.List[str]
334 test_commands: T.List[str]
335 install_commands: T.List[str]
336 uninstall_commands: T.List[str]
337
338 backend: 'Backend'
339 backend_flags: T.List[str]
340
341 stop: bool = False
342 is_worker_process: bool = False
343
344 # Let's have colors in our CI output
345 if under_ci:
346 def _ci_colorize_console() -> bool:
347 return not is_worker_process
348
349 mlog.colorize_console = _ci_colorize_console
350
351 class StopException(Exception):
352 def __init__(self) -> None:
353 super().__init__('Stopped by user')
354
355 def stop_handler(signal: int, frame: T.Optional['FrameType']) -> None:
356 global stop
357 stop = True
358 signal.signal(signal.SIGINT, stop_handler)
359 signal.signal(signal.SIGTERM, stop_handler)
360
361 def setup_commands(optbackend: str) -> None:
362 global backend, backend_flags
363 global compile_commands, clean_commands, test_commands, install_commands, uninstall_commands
364 backend, backend_flags = guess_backend(optbackend, shutil.which('msbuild'))
365 compile_commands, clean_commands, test_commands, install_commands, \
366 uninstall_commands = get_backend_commands(backend, do_debug)
367
368 # TODO try to eliminate or at least reduce this function
369 def platform_fix_name(fname: str, canonical_compiler: str, env: environment.Environment) -> str:
370 if '?lib' in fname:
371 if env.machines.host.is_windows() and canonical_compiler == 'msvc':
372 fname = re.sub(r'lib/\?lib(.*)$', r'bin/\1', fname)
373 fname = re.sub(r'/\?lib/', r'/bin/', fname)
374 elif env.machines.host.is_windows():
375 fname = re.sub(r'lib/\?lib(.*)$', r'bin/lib\1', fname)
376 fname = re.sub(r'\?lib(.*)\.dll$', r'lib\1.dll', fname)
377 fname = re.sub(r'/\?lib/', r'/bin/', fname)
378 elif env.machines.host.is_cygwin():
379 fname = re.sub(r'lib/\?lib(.*)\.so$', r'bin/cyg\1.dll', fname)
380 fname = re.sub(r'lib/\?lib(.*)$', r'bin/cyg\1', fname)
381 fname = re.sub(r'\?lib(.*)\.dll$', r'cyg\1.dll', fname)
382 fname = re.sub(r'/\?lib/', r'/bin/', fname)
383 else:
384 fname = re.sub(r'\?lib', 'lib', fname)
385
386 if fname.endswith('?so'):
387 if env.machines.host.is_windows() and canonical_compiler == 'msvc':
388 fname = re.sub(r'lib/([^/]*)\?so$', r'bin/\1.dll', fname)
389 fname = re.sub(r'/(?:lib|)([^/]*?)\?so$', r'/\1.dll', fname)
390 return fname
391 elif env.machines.host.is_windows():
392 fname = re.sub(r'lib/([^/]*)\?so$', r'bin/\1.dll', fname)
393 fname = re.sub(r'/([^/]*?)\?so$', r'/\1.dll', fname)
394 return fname
395 elif env.machines.host.is_cygwin():
396 fname = re.sub(r'lib/([^/]*)\?so$', r'bin/\1.dll', fname)
397 fname = re.sub(r'/lib([^/]*?)\?so$', r'/cyg\1.dll', fname)
398 fname = re.sub(r'/([^/]*?)\?so$', r'/\1.dll', fname)
399 return fname
400 elif env.machines.host.is_darwin():
401 return fname[:-3] + '.dylib'
402 else:
403 return fname[:-3] + '.so'
404
405 return fname
406
407 def validate_install(test: TestDef, installdir: Path, env: environment.Environment) -> str:
408 ret_msg = ''
409 expected_raw: T.List[Path] = []
410 c_compiler = all_compilers.host.get('c')
411
412 # We cannot do validation without a C compiler for the host
413 if c_compiler is None:
414 return None
415
416 for i in test.installed_files:
417 try:
418 expected_raw += i.get_paths(c_compiler, env, installdir)
419 except RuntimeError as err:
420 ret_msg += f'Expected path error: {err}\n'
421 expected = {x: False for x in expected_raw}
422 found = [x.relative_to(installdir) for x in installdir.rglob('*') if x.is_file() or x.is_symlink()]
423 # Mark all found files as found and detect unexpected files
424 for fname in found:
425 if fname not in expected:
426 ret_msg += f'Extra file {fname} found.\n'
427 continue
428 expected[fname] = True
429 # Check if expected files were found
430 for p, f in expected.items():
431 if not f:
432 ret_msg += f'Expected file {p} missing.\n'
433 # List dir content on error
434 if ret_msg != '':
435 ret_msg += '\nInstall dir contents:\n'
436 for p in found:
437 ret_msg += f' - {p}\n'
438 return ret_msg
439
440 def log_text_file(logfile: T.TextIO, testdir: Path, result: TestResult) -> None:
441 logfile.write('%s\nstdout\n\n---\n' % testdir.as_posix())
442 logfile.write(result.stdo)
443 logfile.write('\n\n---\n\nstderr\n\n---\n')
444 logfile.write(result.stde)
445 logfile.write('\n\n---\n\n')
446 if print_debug:
447 try:
448 print(result.stdo)
449 except UnicodeError:
450 sanitized_out = result.stdo.encode('ascii', errors='replace').decode()
451 print(sanitized_out)
452 try:
453 print(result.stde, file=sys.stderr)
454 except UnicodeError:
455 sanitized_err = result.stde.encode('ascii', errors='replace').decode()
456 print(sanitized_err, file=sys.stderr)
457
458
459 def _run_ci_include(args: T.List[str]) -> str:
460 if not args:
461 return 'At least one parameter required'
462
463 header = f'Included file {args[0]}:'
464 try:
465 return mlog.ci_fold_file(args[0], header, force=True)
466 except Exception:
467 return 'Failed to open {}\n'.format(args[0])
468
469 ci_commands = {
470 'ci_include': _run_ci_include
471 }
472
473 def run_ci_commands(raw_log: str) -> T.List[str]:
474 res = []
475 for l in raw_log.splitlines():
476 if not l.startswith('!meson_ci!/'):
477 continue
478 cmd = shlex.split(l[11:])
479 if not cmd or cmd[0] not in ci_commands:
480 continue
481 res += ['CI COMMAND {}:\n{}'.format(cmd[0], ci_commands[cmd[0]](cmd[1:]))]
482 return res
483
484 class OutputMatch:
485 def __init__(self, how: str, expected: str, count: int) -> None:
486 self.how = how
487 self.expected = expected
488 self.count = count
489
490 def match(self, actual: str) -> bool:
491 if self.how == "re":
492 return bool(re.match(self.expected, actual))
493 return self.expected == actual
494
495 def _compare_output(expected: T.List[T.Dict[str, str]], output: str, desc: str) -> str:
496 if expected:
497 matches: T.List[OutputMatch] = []
498 nomatches: T.List[OutputMatch] = []
499 for item in expected:
500 how = item.get('match', 'literal')
501 expected_line = item.get('line')
502 count = int(item.get('count', -1))
503
504 # Simple heuristic to automatically convert path separators for
505 # Windows:
506 #
507 # Any '/' appearing before 'WARNING' or 'ERROR' (i.e. a path in a
508 # filename part of a location) is replaced with '\' (in a re: '\\'
509 # which matches a literal '\')
510 #
511 # (There should probably be a way to turn this off for more complex
512 # cases which don't fit this)
513 if mesonlib.is_windows():
514 if how != "re":
515 sub = r'\\'
516 else:
517 sub = r'\\\\'
518 expected_line = re.sub(r'/(?=.*(WARNING|ERROR|DEPRECATION))', sub, expected_line)
519
520 m = OutputMatch(how, expected_line, count)
521 if count == 0:
522 nomatches.append(m)
523 else:
524 matches.append(m)
525
526
527 i = 0
528 for actual in output.splitlines():
529 # Verify this line does not match any unexpected lines (item.count == 0)
530 for match in nomatches:
531 if match.match(actual):
532 return f'unexpected "{match.expected}" found in {desc}'
533 # If we matched all expected lines, continue to verify there are
534 # no unexpected line. If nomatches is empty then we are done already.
535 if i >= len(matches):
536 if not nomatches:
537 break
538 continue
539 # Check if this line match current expected line
540 match = matches[i]
541 if match.match(actual):
542 if match.count < 0:
543 # count was not specified, continue with next expected line,
544 # it does not matter if this line will be matched again or
545 # not.
546 i += 1
547 else:
548 # count was specified (must be >0), continue expecting this
549 # same line. If count reached 0 we continue with next
550 # expected line but remember that this one must not match
551 # anymore.
552 match.count -= 1
553 if match.count == 0:
554 nomatches.append(match)
555 i += 1
556
557 if i < len(matches):
558 # reached the end of output without finding expected
559 return f'expected "{matches[i].expected}" not found in {desc}'
560
561 return ''
562
563 def validate_output(test: TestDef, stdo: str, stde: str) -> str:
564 return _compare_output(test.stdout, stdo, 'stdout')
565
566 # There are some class variables and such that cache
567 # information. Clear all of these. The better solution
568 # would be to change the code so that no state is persisted
569 # but that would be a lot of work given that Meson was originally
570 # coded to run as a batch process.
571 def clear_internal_caches() -> None:
572 import mesonbuild.interpreterbase
573 from mesonbuild.dependencies.cmake import CMakeDependency
574 from mesonbuild.dependencies.pkgconfig import PkgConfigInterface
575 from mesonbuild.mesonlib import PerMachine
576 mesonbuild.interpreterbase.FeatureNew.feature_registry = {}
577 CMakeDependency.class_cmakeinfo = PerMachine(None, None)
578 PkgConfigInterface.class_impl = PerMachine({}, {})
579 PkgConfigInterface.class_cli_impl = PerMachine({}, {})
580 PkgConfigInterface.pkg_bin_per_machine = PerMachine(None, None)
581
582
583 def run_test_inprocess(testdir: str) -> T.Tuple[int, str, str, str]:
584 old_stdout = sys.stdout
585 sys.stdout = mystdout = StringIO()
586 old_stderr = sys.stderr
587 sys.stderr = mystderr = StringIO()
588 old_cwd = os.getcwd()
589 os.chdir(testdir)
590 test_log_fname = os.path.join('meson-logs', 'testlog.txt')
591 try:
592 returncode_test = mtest.run_with_args(['--no-rebuild'])
593 if os.path.exists(test_log_fname):
594 test_log = _run_ci_include([test_log_fname])
595 else:
596 test_log = ''
597 returncode_benchmark = mtest.run_with_args(['--no-rebuild', '--benchmark', '--logbase', 'benchmarklog'])
598 finally:
599 sys.stdout = old_stdout
600 sys.stderr = old_stderr
601 os.chdir(old_cwd)
602 return max(returncode_test, returncode_benchmark), mystdout.getvalue(), mystderr.getvalue(), test_log
603
604 # Build directory name must be the same so Ccache works over
605 # consecutive invocations.
606 def create_deterministic_builddir(test: TestDef, use_tmpdir: bool) -> str:
607 import hashlib
608 src_dir = test.path.as_posix()
609 if test.name:
610 src_dir += test.name
611 rel_dirname = 'b ' + hashlib.sha256(src_dir.encode(errors='ignore')).hexdigest()[0:10]
612 abs_pathname = os.path.join(tempfile.gettempdir() if use_tmpdir else os.getcwd(), rel_dirname)
613 if os.path.exists(abs_pathname):
614 mesonlib.windows_proof_rmtree(abs_pathname)
615 os.mkdir(abs_pathname)
616 return abs_pathname
617
618 def format_parameter_file(file_basename: str, test: TestDef, test_build_dir: str) -> Path:
619 confdata = ConfigurationData()
620 confdata.values = {'MESON_TEST_ROOT': (str(test.path.absolute()), 'base directory of current test')}
621
622 template = test.path / (file_basename + '.in')
623 destination = Path(test_build_dir) / file_basename
624 mesonlib.do_conf_file(str(template), str(destination), confdata, 'meson')
625
626 return destination
627
628 def detect_parameter_files(test: TestDef, test_build_dir: str) -> T.Tuple[Path, Path]:
629 nativefile = test.path / 'nativefile.ini'
630 crossfile = test.path / 'crossfile.ini'
631
632 if os.path.exists(str(test.path / 'nativefile.ini.in')):
633 nativefile = format_parameter_file('nativefile.ini', test, test_build_dir)
634
635 if os.path.exists(str(test.path / 'crossfile.ini.in')):
636 crossfile = format_parameter_file('crossfile.ini', test, test_build_dir)
637
638 return nativefile, crossfile
639
640 # In previous python versions the global variables are lost in ProcessPoolExecutor.
641 # So, we use this tuple to restore some of them
642 class GlobalState(T.NamedTuple):
643 compile_commands: T.List[str]
644 clean_commands: T.List[str]
645 test_commands: T.List[str]
646 install_commands: T.List[str]
647 uninstall_commands: T.List[str]
648
649 backend: 'Backend'
650 backend_flags: T.List[str]
651
652 all_compilers: mesonlib.PerMachine[T.Dict[Language, T.Optional[compilers.Compiler]]] = mesonlib.PerMachine({}, {})
653
654 def run_test(test: TestDef,
655 extra_args: T.List[str],
656 should_fail: str,
657 use_tmp: bool,
658 state: T.Optional[GlobalState] = None) -> T.Optional[TestResult]:
659 # Unpack the global state
660 global compile_commands, clean_commands, test_commands, install_commands, uninstall_commands, backend, backend_flags, all_compilers
661 if state is not None:
662 compile_commands, clean_commands, test_commands, install_commands, uninstall_commands, backend, backend_flags, all_compilers = state
663 # Store that this is a worker process
664 global is_worker_process
665 is_worker_process = True
666 # Setup the test environment
667 assert not test.skip, 'Skipped test should not be run'
668 build_dir = create_deterministic_builddir(test, use_tmp)
669 try:
670 with TemporaryDirectoryWinProof(prefix='i ', dir=None if use_tmp else os.getcwd()) as install_dir:
671 try:
672 return _run_test(test, build_dir, install_dir, extra_args, should_fail)
673 except TestResult as r:
674 return r
675 finally:
676 mlog.shutdown() # Close the log file because otherwise Windows wets itself.
677 finally:
678 mesonlib.windows_proof_rmtree(build_dir)
679
680 def _run_test(test: TestDef,
681 test_build_dir: str,
682 install_dir: str,
683 extra_args: T.List[str],
684 should_fail: str) -> TestResult:
685 gen_start = time.time()
686 # Configure in-process
687 gen_args = ['setup']
688 if 'prefix' not in test.do_not_set_opts:
689 gen_args += ['--prefix', 'x:/usr'] if mesonlib.is_windows() else ['--prefix', '/usr']
690 if 'libdir' not in test.do_not_set_opts:
691 gen_args += ['--libdir', 'lib']
692 gen_args += [test.path.as_posix(), test_build_dir] + backend_flags + extra_args
693
694 nativefile, crossfile = detect_parameter_files(test, test_build_dir)
695
696 if nativefile.exists():
697 gen_args.extend(['--native-file', nativefile.as_posix()])
698 if crossfile.exists():
699 gen_args.extend(['--cross-file', crossfile.as_posix()])
700 inprocess, res = run_configure(gen_args, env=test.env, catch_exception=True)
701 returncode, stdo, stde = res
702 cmd = '(inprocess) $ ' if inprocess else '$ '
703 cmd += mesonlib.join_args(gen_args)
704 logfile = os.path.join(test_build_dir, 'meson-logs', 'meson-log.txt')
705 if os.path.exists(logfile):
706 mesonlog = '\n'.join((cmd, _run_ci_include([logfile])))
707 else:
708 mesonlog = no_meson_log_msg
709 cicmds = run_ci_commands(mesonlog)
710 testresult = TestResult(cicmds)
711 testresult.add_step(BuildStep.configure, '\n'.join((cmd, stdo)), stde, mesonlog, time.time() - gen_start)
712 output_msg = validate_output(test, stdo, stde)
713 testresult.mlog += output_msg
714 if output_msg:
715 testresult.fail('Unexpected output while configuring.')
716 return testresult
717 if should_fail == 'meson':
718 if returncode == 1:
719 return testresult
720 elif returncode != 0:
721 testresult.fail(f'Test exited with unexpected status {returncode}.')
722 return testresult
723 else:
724 testresult.fail('Test that should have failed succeeded.')
725 return testresult
726 if returncode != 0:
727 testresult.fail('Generating the build system failed.')
728 return testresult
729 builddata = build.load(test_build_dir)
730 dir_args = get_backend_args_for_dir(backend, test_build_dir)
731
732 # Build with subprocess
733 def build_step() -> None:
734 build_start = time.time()
735
736 if backend is Backend.ninja:
737 # FIXME: meson test inprocess does not handle running ninja via StringIO
738 targets = ['all', 'meson-test-prereq', 'meson-benchmark-prereq']
739 else:
740 targets = []
741
742 pc, o, _ = Popen_safe(compile_commands + dir_args + targets, cwd=test_build_dir, stderr=subprocess.STDOUT)
743 testresult.add_step(BuildStep.build, o, '', '', time.time() - build_start)
744 if should_fail == 'build':
745 if pc.returncode != 0:
746 raise testresult
747 testresult.fail('Test that should have failed to build succeeded.')
748 raise testresult
749 if pc.returncode != 0:
750 testresult.fail('Compiling source code failed.')
751 raise testresult
752
753 # Touch the meson.build file to force a regenerate
754 def force_regenerate() -> None:
755 os.utime(str(test.path / 'meson.build'))
756
757 # just test building
758 build_step()
759
760 # test that regeneration works for build step
761 force_regenerate()
762 build_step() # TBD: assert nothing gets built after the regenerate?
763
764 # test that regeneration works for test step
765 force_regenerate()
766
767 # Test in-process
768 clear_internal_caches()
769 test_start = time.time()
770 (returncode, tstdo, tstde, test_log) = run_test_inprocess(test_build_dir)
771 testresult.add_step(BuildStep.test, tstdo, tstde, test_log, time.time() - test_start)
772 if should_fail == 'test':
773 if returncode != 0:
774 return testresult
775 testresult.fail('Test that should have failed to run unit tests succeeded.')
776 return testresult
777 if returncode != 0:
778 testresult.fail('Running unit tests failed.')
779 return testresult
780
781 # Do installation, if the backend supports it
782 if install_commands:
783 env = test.env.copy()
784 env['DESTDIR'] = install_dir
785 # Install with subprocess
786 pi, o, e = Popen_safe(install_commands, cwd=test_build_dir, env=env)
787 testresult.add_step(BuildStep.install, o, e)
788 if pi.returncode != 0:
789 testresult.fail('Running install failed.')
790 return testresult
791
792 # Clean with subprocess
793 env = test.env.copy()
794 pi, o, e = Popen_safe(clean_commands + dir_args, cwd=test_build_dir, env=env)
795 testresult.add_step(BuildStep.clean, o, e)
796 if pi.returncode != 0:
797 testresult.fail('Running clean failed.')
798 return testresult
799
800 # Validate installed files
801 testresult.add_step(BuildStep.install, '', '')
802 if not install_commands:
803 return testresult
804 install_msg = validate_install(test, Path(install_dir), builddata.environment)
805 if install_msg:
806 testresult.fail('\n' + install_msg)
807 return testresult
808
809 return testresult
810
811
812 # processing of test.json 'skip_*' keys, which can appear at top level, or in
813 # matrix:
814 def _skip_keys(test_def: T.Dict) -> T.Tuple[bool, bool]:
815 skip_expected = False
816
817 # Test is expected to skip if MESON_CI_JOBNAME contains any of the list of
818 # substrings
819 if ('expect_skip_on_jobname' in test_def) and (ci_jobname is not None):
820 skip_expected = any(s in ci_jobname for s in test_def['expect_skip_on_jobname'])
821
822 # Test is expected to skip if os matches
823 if 'expect_skip_on_os' in test_def:
824 mesonenv = environment.Environment('', '', get_fake_options('/'))
825 for skip_os in test_def['expect_skip_on_os']:
826 if skip_os.startswith('!'):
827 if mesonenv.machines.host.system != skip_os[1:]:
828 skip_expected = True
829 else:
830 if mesonenv.machines.host.system == skip_os:
831 skip_expected = True
832
833 # Skip if environment variable is present
834 skip = False
835 if 'skip_on_env' in test_def:
836 for skip_env_var in test_def['skip_on_env']:
837 if skip_env_var in os.environ:
838 skip = True
839
840 return (skip, skip_expected)
841
842
843 def load_test_json(t: TestDef, c: TestCategory) -> T.List[TestDef]:
844 all_tests: T.List[TestDef] = []
845 test_def = {}
846 test_def_file = t.path / 'test.json'
847 if test_def_file.is_file():
848 test_def = json.loads(test_def_file.read_text(encoding='utf-8'))
849
850 # Handle additional environment variables
851 env: T.Dict[str, str] = {}
852 if 'env' in test_def:
853 assert isinstance(test_def['env'], dict)
854 env = test_def['env']
855 for key, val in env.items():
856 val = val.replace('@ROOT@', t.path.resolve().as_posix())
857 val = val.replace('@PATH@', t.env.get('PATH', ''))
858 env[key] = val
859
860 # Handle installed files
861 installed: T.List[InstalledFile] = []
862 if 'installed' in test_def:
863 installed = [InstalledFile(x) for x in test_def['installed']]
864
865 # Handle expected output
866 stdout = test_def.get('stdout', [])
867 if c.stdout_mandatory and not stdout:
868 raise RuntimeError(f"{test_def_file} must contain a non-empty stdout key")
869
870 # Handle the do_not_set_opts list
871 do_not_set_opts: T.List[str] = test_def.get('do_not_set_opts', [])
872
873 (t.skip, t.skip_expected) = _skip_keys(test_def)
874
875 cleanup = test_def.get('cleanup', [])
876
877 # Skip tests if the tool requirements are not met
878 if 'tools' in test_def:
879 assert isinstance(test_def['tools'], dict)
880 for tool, vers_req in test_def['tools'].items():
881 if tool not in tool_vers_map:
882 t.skip = True
883 elif not mesonlib.version_compare(tool_vers_map[tool], vers_req):
884 t.skip = True
885
886 # Skip the matrix code and just update the existing test
887 if 'matrix' not in test_def:
888 t.env.update(env)
889 t.installed_files = installed
890 t.do_not_set_opts = do_not_set_opts
891 t.stdout = stdout
892 t.cleanup = cleanup
893 return [t]
894
895 new_opt_list: T.List[T.List[T.Tuple[str, str, bool, bool]]]
896
897 # 'matrix; entry is present, so build multiple tests from matrix definition
898 opt_list: T.List[T.List[T.Tuple[str, str, bool, bool]]] = []
899 matrix = test_def['matrix']
900 assert "options" in matrix
901 for key, val in matrix["options"].items():
902 assert isinstance(val, list)
903 tmp_opts: T.List[T.Tuple[str, str, bool, bool]] = []
904 for i in val:
905 assert isinstance(i, dict)
906 assert "val" in i
907
908 (skip, skip_expected) = _skip_keys(i)
909
910 # Only run the test if all compiler ID's match
911 if 'compilers' in i:
912 for lang, id_list in i['compilers'].items():
913 if lang not in compiler_id_map or compiler_id_map[lang] not in id_list:
914 skip = True
915 break
916
917 # Add an empty matrix entry
918 if i['val'] is None:
919 tmp_opts += [(key, None, skip, skip_expected)]
920 continue
921
922 tmp_opts += [(key, i['val'], skip, skip_expected)]
923
924 if opt_list:
925 new_opt_list = []
926 for i in opt_list:
927 for j in tmp_opts:
928 new_opt_list += [[*i, j]]
929 opt_list = new_opt_list
930 else:
931 opt_list = [[x] for x in tmp_opts]
932
933 # Exclude specific configurations
934 if 'exclude' in matrix:
935 assert isinstance(matrix['exclude'], list)
936 new_opt_list = []
937 for i in opt_list:
938 exclude = False
939 opt_tuple = [(x[0], x[1]) for x in i]
940 for j in matrix['exclude']:
941 ex_list = [(k, v) for k, v in j.items()]
942 if all([x in opt_tuple for x in ex_list]):
943 exclude = True
944 break
945
946 if not exclude:
947 new_opt_list += [i]
948
949 opt_list = new_opt_list
950
951 for i in opt_list:
952 name = ' '.join([f'{x[0]}={x[1]}' for x in i if x[1] is not None])
953 opts = [f'-D{x[0]}={x[1]}' for x in i if x[1] is not None]
954 skip = any([x[2] for x in i])
955 skip_expected = any([x[3] for x in i])
956 test = TestDef(t.path, name, opts, skip or t.skip, c)
957 test.env.update(env)
958 test.installed_files = installed
959 test.do_not_set_opts = do_not_set_opts
960 test.stdout = stdout
961 test.skip_expected = skip_expected or t.skip_expected
962 test.cleanup = cleanup
963
964 all_tests.append(test)
965
966 return all_tests
967
968
969 def gather_tests(testdir: Path, category: TestCategory, only: T.List[str]) -> T.List[TestDef]:
970 all_tests: T.List[TestDef] = []
971 for t in testdir.iterdir():
972 # Filter non-tests files (dot files, etc)
973 if not t.is_dir() or t.name.startswith('.'):
974 continue
975 if t.name in {'18 includedirxyz'}:
976 continue
977 if only and not any(t.name.startswith(prefix) for prefix in only):
978 continue
979 test_def = TestDef(t, None, [], False, category)
980 all_tests.extend(load_test_json(test_def, category))
981 return sorted(all_tests)
982
983
984 def have_java() -> bool:
985 return all_compilers.host['java'] is not None and shutil.which('java') is not None
986
987 def skip_dont_care(t: TestDef) -> bool:
988 # Everything is optional when not running on CI
989 if ci_jobname is None:
990 return True
991
992 # Non-frameworks test are allowed to determine their own skipping under CI (currently)
993 if not t.category.endswith('frameworks'):
994 return True
995
996 if mesonlib.is_osx() and '6 gettext' in str(t.path):
997 return True
998
999 return False
1000
1001 def skip_csharp(backend: Backend) -> bool:
1002 if backend is not Backend.ninja:
1003 return True
1004 if not shutil.which('resgen'):
1005 return True
1006 comp = all_compilers.host['cs']
1007 if comp is None:
1008 return True
1009 if comp.id == 'mono':
1010 return False
1011 if comp.id == 'csc':
1012 # Only support VS2017 for now. Earlier versions fail
1013 # under CI in mysterious ways.
1014 try:
1015 stdo = subprocess.check_output(['csc', '/version'])
1016 except subprocess.CalledProcessError:
1017 return True
1018 # Having incrementing version numbers would be too easy.
1019 # Microsoft reset the versioning back to 1.0 (from 4.x)
1020 # when they got the Roslyn based compiler. Thus there
1021 # is NO WAY to reliably do version number comparisons.
1022 # Only support the version that ships with VS2017.
1023 return not stdo.startswith(b'2.')
1024 return True
1025
1026 def should_skip_wayland() -> bool:
1027 if mesonlib.is_windows() or mesonlib.is_osx():
1028 return True
1029 if not shutil.which('wayland-scanner'):
1030 return True
1031 return False
1032
1033 class TestCategory:
1034 def __init__(self, category: str, subdir: str, skip: bool = False, stdout_mandatory: bool = False):
1035 self.category = category # category name
1036 self.subdir = subdir # subdirectory
1037 self.skip = skip # skip condition
1038 self.stdout_mandatory = stdout_mandatory # expected stdout is mandatory for tests in this category
1039
1040 def detect_tests_to_run(only: T.Dict[str, T.List[str]], use_tmp: bool) -> T.List[T.Tuple[str, T.List[TestDef], bool]]:
1041 """
1042 Parameters
1043 ----------
1044 only: dict of categories and list of test cases, optional
1045 specify names of tests to run
1046
1047 Returns
1048 -------
1049 gathered_tests: list of tuple of str, list of TestDef, bool
1050 tests to run
1051 """
1052
1053 skip_cmake = ((os.environ.get('compiler') == 'msvc2015' and under_ci) or
1054 'cmake' not in tool_vers_map or
1055 not mesonlib.version_compare(tool_vers_map['cmake'], '>=3.14'))
1056
1057 all_tests = [
1058 TestCategory('cmake', 'cmake', skip_cmake),
1059 TestCategory('common', 'common'),
1060 TestCategory('native', 'native'),
1061 TestCategory('warning-meson', 'warning', stdout_mandatory=True),
1062 TestCategory('failing-meson', 'failing', stdout_mandatory=True),
1063 TestCategory('failing-build', 'failing build'),
1064 TestCategory('failing-test', 'failing test'),
1065 TestCategory('keyval', 'keyval'),
1066 TestCategory('platform-osx', 'osx', not mesonlib.is_osx()),
1067 TestCategory('platform-windows', 'windows', not mesonlib.is_windows() and not mesonlib.is_cygwin()),
1068 TestCategory('platform-linux', 'linuxlike', mesonlib.is_osx() or mesonlib.is_windows()),
1069 # FIXME, does not actually run in CI, change to run the test if an Android cross toolchain is detected.
1070 TestCategory('platform-android', 'android', not mesonlib.is_android()),
1071 TestCategory('java', 'java', backend is not Backend.ninja or not have_java()),
1072 TestCategory('C#', 'csharp', skip_csharp(backend)),
1073 TestCategory('vala', 'vala', backend is not Backend.ninja or all_compilers.host['vala'] is None),
1074 TestCategory('cython', 'cython', backend is not Backend.ninja or all_compilers.host['cython'] is None),
1075 TestCategory('rust', 'rust', backend is not Backend.ninja or all_compilers.host['rust'] is None),
1076 TestCategory('d', 'd', backend is not Backend.ninja or all_compilers.host['d'] is None),
1077 TestCategory('objective c', 'objc', backend not in (Backend.ninja, Backend.xcode) or all_compilers.host['objc'] is None),
1078 TestCategory('objective c++', 'objcpp', backend not in (Backend.ninja, Backend.xcode) or all_compilers.host['objcpp'] is None),
1079 TestCategory('fortran', 'fortran', backend is not Backend.ninja or all_compilers.host['fortran'] is None),
1080 TestCategory('swift', 'swift', backend not in (Backend.ninja, Backend.xcode) or all_compilers.host['swift'] is None),
1081 # CUDA tests on Windows: use Ninja backend: python run_project_tests.py --only cuda --backend ninja
1082 TestCategory('cuda', 'cuda', backend not in (Backend.ninja, Backend.xcode) or all_compilers.host['cuda'] is None),
1083 TestCategory('python3', 'python3', backend is not Backend.ninja or 'python3' not in sys.executable),
1084 TestCategory('python', 'python'),
1085 TestCategory('fpga', 'fpga', shutil.which('yosys') is None),
1086 TestCategory('frameworks', 'frameworks'),
1087 TestCategory('nasm', 'nasm'),
1088 TestCategory('wasm', 'wasm', shutil.which('emcc') is None or backend is not Backend.ninja),
1089 TestCategory('wayland', 'wayland', should_skip_wayland()),
1090 TestCategory('format', 'format'),
1091 TestCategory('snippets', 'snippets'),
1092 ]
1093
1094 categories = [t.category for t in all_tests]
1095 assert categories == ALL_TESTS, 'argparse("--only", choices=ALL_TESTS) need to be updated to match all_tests categories'
1096
1097 if only:
1098 all_tests = [t for t in all_tests if t.category in only]
1099
1100 gathered_tests = [(t.category, gather_tests(Path('test cases', t.subdir), t, only[t.category]), t.skip) for t in all_tests]
1101 return gathered_tests
1102
1103 def run_tests(all_tests: T.List[T.Tuple[str, T.List[TestDef], bool]],
1104 log_name_base: str,
1105 failfast: bool,
1106 extra_args: T.List[str],
1107 use_tmp: bool,
1108 num_workers: int) -> T.Tuple[int, int, int]:
1109 txtname = log_name_base + '.txt'
1110 with open(txtname, 'w', encoding='utf-8', errors='ignore') as lf:
1111 return _run_tests(all_tests, log_name_base, failfast, extra_args, use_tmp, num_workers, lf)
1112
1113 class TestStatus(Enum):
1114 OK = normal_green(' [SUCCESS] ')
1115 SKIP = yellow(' [SKIPPED] ')
1116 ERROR = red(' [ERROR] ')
1117 UNEXSKIP = red('[UNEXSKIP] ')
1118 UNEXRUN = red(' [UNEXRUN] ')
1119 CANCELED = cyan('[CANCELED] ')
1120 RUNNING = blue(' [RUNNING] ') # Should never be actually printed
1121 LOG = bold(' [LOG] ') # Should never be actually printed
1122
1123 def default_print(*args: mlog.TV_Loggable, sep: str = ' ') -> None:
1124 print(*args, sep=sep)
1125
1126 safe_print = default_print
1127
1128 class TestRunFuture:
1129 def __init__(self, name: str, testdef: TestDef, future: T.Optional['Future[T.Optional[TestResult]]']) -> None:
1130 super().__init__()
1131 self.name = name
1132 self.testdef = testdef
1133 self.future = future
1134 self.status = TestStatus.RUNNING if self.future is not None else TestStatus.SKIP
1135
1136 @property
1137 def result(self) -> T.Optional[TestResult]:
1138 return self.future.result() if self.future else None
1139
1140 def log(self) -> None:
1141 if verbose_output or self.status.value != TestStatus.OK.value:
1142 without_install = '' if install_commands else '(without install)'
1143 safe_print(self.status.value, without_install, *self.testdef.display_name())
1144
1145 def update_log(self, new_status: TestStatus) -> None:
1146 self.status = new_status
1147 self.log()
1148
1149 def cancel(self) -> None:
1150 if self.future is not None and self.future.cancel():
1151 self.status = TestStatus.CANCELED
1152
1153 class LogRunFuture:
1154 def __init__(self, msgs: mlog.TV_LoggableList) -> None:
1155 self.msgs = msgs
1156 self.status = TestStatus.LOG
1157
1158 def log(self) -> None:
1159 safe_print(*self.msgs, sep='')
1160
1161 def cancel(self) -> None:
1162 pass
1163
1164 RunFutureUnion = T.Union[TestRunFuture, LogRunFuture]
1165
1166 def _run_tests(all_tests: T.List[T.Tuple[str, T.List[TestDef], bool]],
1167 log_name_base: str,
1168 failfast: bool,
1169 extra_args: T.List[str],
1170 use_tmp: bool,
1171 num_workers: int,
1172 logfile: T.TextIO) -> T.Tuple[int, int, int]:
1173 xmlname = log_name_base + '.xml'
1174 junit_root = ET.Element('testsuites')
1175 conf_time: float = 0
1176 build_time: float = 0
1177 test_time: float = 0
1178 passing_tests = 0
1179 failing_tests = 0
1180 skipped_tests = 0
1181
1182 print(f'\nRunning tests with {num_workers} workers')
1183
1184 # Pack the global state
1185 state = GlobalState(compile_commands, clean_commands, test_commands, install_commands, uninstall_commands, backend, backend_flags, all_compilers)
1186 executor = ProcessPoolExecutor(max_workers=num_workers)
1187
1188 futures: T.List[RunFutureUnion] = []
1189
1190 # First, collect and start all tests and also queue log messages
1191 for name, test_cases, skipped in all_tests:
1192 ET.SubElement(junit_root, 'testsuite', {'name': name, 'tests': str(len(test_cases))})
1193
1194 if skipped:
1195 futures += [LogRunFuture(['\n', bold(f'Not running {name} tests.'), '\n'])]
1196 continue
1197 else:
1198 futures += [LogRunFuture(['\n', bold(f'Running {name} tests.'), '\n'])]
1199
1200 for t in test_cases:
1201 # Jenkins screws us over by automatically sorting test cases by name
1202 # and getting it wrong by not doing logical number sorting.
1203 (testnum, testbase) = t.path.name.split(' ', 1)
1204 testname = '%.3d %s' % (int(testnum), testbase)
1205 if t.name:
1206 testname += f' ({t.name})'
1207 should_fail = ''
1208 suite_args = []
1209 if name.startswith('failing'):
1210 should_fail = name.split('failing-')[1]
1211 if name.startswith('warning'):
1212 suite_args = ['--fatal-meson-warnings']
1213 should_fail = name.split('warning-')[1]
1214
1215 if skipped or t.skip:
1216 futures += [TestRunFuture(testname, t, None)]
1217 continue
1218 result_future = executor.submit(run_test, t, extra_args + suite_args + t.args, should_fail, use_tmp, state=state)
1219 futures += [TestRunFuture(testname, t, result_future)]
1220
1221 # Ensure we only cancel once
1222 tests_canceled = False
1223
1224 # Optionally enable the tqdm progress bar, but only if there is at least
1225 # one LogRunFuture and one TestRunFuture
1226 global safe_print
1227 futures_iter: T.Iterable[RunFutureUnion] = futures
1228 if len(futures) > 2 and sys.stdout.isatty():
1229 try:
1230 from tqdm import tqdm
1231 futures_iter = tqdm(futures, desc='Running tests', unit='test')
1232
1233 def tqdm_print(*args: mlog.TV_Loggable, sep: str = ' ') -> None:
1234 tqdm.write(sep.join([str(x) for x in args]))
1235
1236 safe_print = tqdm_print
1237 except ImportError:
1238 pass
1239
1240 # Wait and handle the test results and print the stored log output
1241 for f in futures_iter:
1242 # Just a log entry to print something to stdout
1243 sys.stdout.flush()
1244 if isinstance(f, LogRunFuture):
1245 f.log()
1246 continue
1247
1248 # Actual Test run
1249 testname = f.name
1250 t = f.testdef
1251 try:
1252 result = f.result
1253 except (CancelledError, KeyboardInterrupt):
1254 f.status = TestStatus.CANCELED
1255
1256 if stop and not tests_canceled:
1257 num_running = sum(1 if f2.status is TestStatus.RUNNING else 0 for f2 in futures)
1258 for f2 in futures:
1259 f2.cancel()
1260 executor.shutdown()
1261 num_canceled = sum(1 if f2.status is TestStatus.CANCELED else 0 for f2 in futures)
1262 safe_print(f'\nCanceled {num_canceled} out of {num_running} running tests.')
1263 safe_print(f'Finishing the remaining {num_running - num_canceled} tests.\n')
1264 tests_canceled = True
1265
1266 # Handle canceled tests
1267 if f.status is TestStatus.CANCELED:
1268 f.log()
1269 continue
1270
1271 # Handle skipped tests
1272 if result is None:
1273 # skipped due to skipped category skip or 'tools:' or 'skip_on_env:'
1274 is_skipped = True
1275 skip_reason = 'not run because preconditions were not met'
1276 skip_as_expected = True
1277 else:
1278 # skipped due to test outputting 'MESON_SKIP_TEST'
1279 is_skipped, skip_reason = handle_meson_skip_test(result.stdo)
1280 if not skip_dont_care(t):
1281 skip_as_expected = (is_skipped == t.skip_expected)
1282 else:
1283 skip_as_expected = True
1284
1285 if is_skipped:
1286 skipped_tests += 1
1287
1288 current_suite = junit_root.find(f"./testsuite[@name='{t.category}']")
1289
1290 current_test = ET.SubElement(current_suite,
1291 'testcase',
1292 {'name': testname, 'classname': t.category})
1293
1294 if result:
1295 testcase_time = result.conftime + result.buildtime + result.testtime
1296 current_test.set('time', '%.3f' % testcase_time)
1297
1298 # skip
1299 if is_skipped and skip_as_expected:
1300 f.update_log(TestStatus.SKIP)
1301 if not t.skip_category:
1302 safe_print(bold('Reason:'), skip_reason)
1303 ET.SubElement(current_test, 'skipped', {})
1304
1305 # unexrun/unexskip
1306 elif not skip_as_expected:
1307 failing_tests += 1
1308 if is_skipped:
1309 skip_msg = f'Test asked to be skipped ({skip_reason}), but was not expected to'
1310 status = TestStatus.UNEXSKIP
1311 else:
1312 skip_msg = 'Test ran, but was expected to be skipped'
1313 status = TestStatus.UNEXRUN
1314 result.msg = f"{skip_msg} for MESON_CI_JOBNAME '{ci_jobname}'"
1315
1316 f.update_log(status)
1317 safe_print(bold('Reason:'), result.msg)
1318 ET.SubElement(current_test, 'failure', {'message': result.msg})
1319
1320 # failed
1321 elif result.msg != '':
1322 f.update_log(TestStatus.ERROR)
1323 safe_print(bold('During:'), result.step.name)
1324 safe_print(bold('Reason:'), result.msg)
1325 failing_tests += 1
1326 # Append a visual separator for the different test cases
1327 cols = shutil.get_terminal_size((100, 20)).columns
1328 name_str = ' '.join([str(x) for x in f.testdef.display_name()])
1329 name_len = len(re.sub(r'\x1B[^m]+m', '', name_str)) # Do not count escape sequences
1330 left_w = (cols // 2) - (name_len // 2) - 1
1331 left_w = max(3, left_w)
1332 right_w = cols - left_w - name_len - 2
1333 right_w = max(3, right_w)
1334 failing_testcases.append(name_str)
1335 failing_logs.append(f'\n\x1b[31m{"="*left_w}\x1b[0m {name_str} \x1b[31m{"="*right_w}\x1b[0m\n')
1336 _during = bold('Failed during:')
1337 _reason = bold('Reason:')
1338 failing_logs.append(f'{_during} {result.step.name}\n{_reason} {result.msg}\n')
1339 if result.step == BuildStep.configure and result.mlog != no_meson_log_msg:
1340 # For configure failures, instead of printing stdout,
1341 # print the meson log if available since it's a superset
1342 # of stdout and often has very useful information.
1343 failing_logs.append(result.mlog)
1344 elif under_ci:
1345 # Always print the complete meson log when running in
1346 # a CI. This helps debugging issues that only occur in
1347 # a hard to reproduce environment
1348 failing_logs.append(result.mlog)
1349 failing_logs.append(result.stdo)
1350 else:
1351 failing_logs.append(result.stdo)
1352 for cmd_res in result.cicmds:
1353 failing_logs.append(cmd_res)
1354 failing_logs.append(result.stde)
1355 if failfast:
1356 safe_print("Cancelling the rest of the tests")
1357 for f2 in futures:
1358 f2.cancel()
1359
1360 ET.SubElement(current_test, 'failure', {'message': result.msg})
1361
1362 # success
1363 else:
1364 f.update_log(TestStatus.OK)
1365 passing_tests += 1
1366 for cleanup_path in t.cleanup:
1367 assert not os.path.isabs(cleanup_path)
1368 abspath = t.path / cleanup_path
1369 if abspath.is_file():
1370 mesonlib.windows_proof_rm(abspath)
1371 else:
1372 mesonlib.windows_proof_rmtree(abspath)
1373
1374 if result:
1375 # track total runtime
1376 conf_time += result.conftime
1377 build_time += result.buildtime
1378 test_time += result.testtime
1379
1380 # attach stdout and stderr child nodes to 'testcase' node
1381 ET.SubElement(current_test, 'system-out').text = mtest.replace_unencodable_xml_chars(result.stdo)
1382 ET.SubElement(current_test, 'system-err').text = mtest.replace_unencodable_xml_chars(result.stde)
1383
1384 # write stdout/stderr to log file (and terminal)
1385 log_text_file(logfile, t.path, result)
1386
1387 # Reset, just in case
1388 safe_print = default_print
1389
1390 print()
1391 print("Total configuration time: %.2fs" % conf_time)
1392 print("Total build time: %.2fs" % build_time)
1393 print("Total test time: %.2fs" % test_time)
1394 ET.ElementTree(element=junit_root).write(xmlname, xml_declaration=True, encoding='UTF-8')
1395
1396 # validate the JUnit XML output against the JUnit schema, if possible
1397 if hasattr(ET, 'XMLSchema'):
1398 junit_schema = ET.XMLSchema(file='./data/schema.xsd')
1399 junit_schema.assertValid(junit_root)
1400
1401 return passing_tests, failing_tests, skipped_tests
1402
1403 def check_meson_commands_work(use_tmpdir: bool, extra_args: T.List[str]) -> None:
1404 testdir = PurePath('test cases', 'common', '1 trivial').as_posix()
1405 meson_commands = mesonlib.python_command + [get_meson_script()]
1406 with TemporaryDirectoryWinProof(prefix='b ', dir=None if use_tmpdir else '.') as build_dir:
1407 print('Checking that configuring works...')
1408 gen_cmd = meson_commands + ['setup' , testdir, build_dir] + backend_flags + extra_args
1409 pc, o, e = Popen_safe(gen_cmd)
1410 if pc.returncode != 0:
1411 raise RuntimeError(f'Failed to configure {testdir!r}:\n{e}\n{o}')
1412 print('Checking that introspect works...')
1413 pc, o, e = Popen_safe(meson_commands + ['introspect', '--targets'], cwd=build_dir)
1414 json.loads(o)
1415 if pc.returncode != 0:
1416 raise RuntimeError(f'Failed to introspect --targets {testdir!r}:\n{e}\n{o}')
1417 print('Checking that building works...')
1418 dir_args = get_backend_args_for_dir(backend, build_dir)
1419 pc, o, e = Popen_safe(compile_commands + dir_args, cwd=build_dir)
1420 if pc.returncode != 0:
1421 raise RuntimeError(f'Failed to build {testdir!r}:\n{e}\n{o}')
1422 print('Checking that testing works...')
1423 pc, o, e = Popen_safe(test_commands, cwd=build_dir)
1424 if pc.returncode != 0:
1425 raise RuntimeError(f'Failed to test {testdir!r}:\n{e}\n{o}')
1426 if install_commands:
1427 print('Checking that installing works...')
1428 pc, o, e = Popen_safe(install_commands, cwd=build_dir)
1429 if pc.returncode != 0:
1430 raise RuntimeError(f'Failed to install {testdir!r}:\n{e}\n{o}')
1431
1432
1433 def detect_system_compiler(options: 'CompilerArgumentType') -> None:
1434 fake_opts = get_fake_options('/')
1435 if options.cross_file:
1436 fake_opts.cross_file = [options.cross_file]
1437 if options.native_file:
1438 fake_opts.native_file = [options.native_file]
1439
1440 machines = [MachineChoice.HOST]
1441 if options.cross_file:
1442 machines.append(MachineChoice.BUILD)
1443
1444 with tempfile.TemporaryDirectory(prefix='b_', dir=None if options.use_tmpdir else '.') as d:
1445 env = environment.Environment('', d, fake_opts)
1446 futures: T.Dict[T.Tuple[Language, MachineChoice], Future[T.Tuple[Language, MachineChoice, T.Optional[Compiler]]]] = {}
1447
1448 def find_compiler(lang: Language, machine: MachineChoice) -> T.Callable[[], T.Tuple[Language, MachineChoice, T.Optional[Compiler]]]:
1449 def inner() -> T.Tuple[Language, MachineChoice, T.Optional[Compiler]]:
1450 # Vala and Cython need to have a working C compiler before they can be detected
1451 if lang in {'vala', 'cython'}:
1452 if futures[('c', machine)].result()[2] is None:
1453 return lang, machine, None
1454
1455 # Cuda needs a working C++ compiler before it can be detetected
1456 if lang == 'cuda':
1457 if futures[('cpp', machine)].result()[2] is None:
1458 return lang, machine, None
1459
1460 try:
1461 comp = detect_compiler_for(env, lang, machine, False, '')
1462 except mesonlib.MesonException:
1463 comp = None
1464 return lang, machine, comp
1465 return inner
1466
1467 with ThreadPoolExecutor(max_workers=multiprocessing.cpu_count()) as pool:
1468 for machine, lang in itertools.product(machines, compilers.all_languages):
1469 futures[(lang, machine)] = pool.submit(find_compiler(lang, machine))
1470 for future in as_completed(futures.values()):
1471 lang, machine, comp = future.result()
1472 all_compilers[machine][lang] = comp
1473
1474 print_compilers(MachineChoice.HOST)
1475 if all_compilers.build:
1476 print_compilers(MachineChoice.BUILD)
1477
1478
1479 def print_compilers(machine: MachineChoice) -> None:
1480 print()
1481 print(f'{machine.get_lower_case_name()} machine compilers')
1482 print()
1483 for lang, comp in sorted(all_compilers[machine].items(), key=lambda x: x[0]):
1484 if comp is not None:
1485 details = '{:<10} {} {}'.format('[' + comp.get_id() + ']', ' '.join(comp.get_exelist()), comp.get_version_string())
1486 else:
1487 details = '[not found]'
1488 print(f'{lang:<7}: {details}')
1489
1490 class ToolInfo(T.NamedTuple):
1491 tool: str
1492 args: T.List[str]
1493 regex: T.Pattern
1494 match_group: int
1495
1496 def detect_tools(report: bool = True) -> None:
1497 tools: T.List[ToolInfo] = [
1498 ToolInfo(
1499 'ninja',
1500 ['--version'],
1501 re.compile(r'^([0-9]+(\.[0-9]+)*(-[a-z0-9]+)?)$'),
1502 1,
1503 ),
1504 ToolInfo(
1505 'cmake',
1506 ['--version'],
1507 re.compile(r'^cmake version ([0-9]+(\.[0-9]+)*(-[a-z0-9]+)?)$'),
1508 1,
1509 ),
1510 ToolInfo(
1511 'hotdoc',
1512 ['--version'],
1513 re.compile(r'^([0-9]+(\.[0-9]+)*(-[a-z0-9]+)?)$'),
1514 1,
1515 ),
1516 ]
1517
1518 def get_version(t: ToolInfo) -> str:
1519 exe = shutil.which(t.tool)
1520 if not exe:
1521 return 'not found'
1522
1523 args = [t.tool] + t.args
1524 pc, o, e = Popen_safe(args)
1525 if pc.returncode != 0:
1526 return f'{exe} (invalid {t.tool} executable)'
1527 for i in o.split('\n'):
1528 i = i.strip('\n\r\t ')
1529 m = t.regex.match(i)
1530 if m is not None:
1531 tool_vers_map[t.tool] = m.group(t.match_group)
1532 return '{} ({})'.format(exe, m.group(t.match_group))
1533
1534 return f'{exe} (unknown)'
1535
1536 if not report:
1537 for tool in tools:
1538 get_version(tool)
1539 return
1540
1541 print()
1542 print('tools')
1543 print()
1544
1545 max_width = max([len(x.tool) for x in tools] + [7])
1546 for tool in tools:
1547 print('{0:<{2}}: {1}'.format(tool.tool, get_version(tool), max_width))
1548 print()
1549
1550 symlink_test_dir1: T.Optional[Path] = None
1551 symlink_test_dir2: T.Optional[Path] = None
1552 symlink_file1: T.Optional[Path] = None
1553 symlink_file2: T.Optional[Path] = None
1554 symlink_file3: T.Optional[Path] = None
1555
1556 def scan_test_data_symlinks() -> None:
1557 global symlink_test_dir1, symlink_test_dir2, symlink_file1, symlink_file2, symlink_file3
1558 tmpdir1 = list(Path('.').glob('test cases/**/*install functions and follow symlinks'))
1559 tmpdir2 = list(Path('.').glob('test cases/frameworks/*boost symlinks'))
1560 assert len(tmpdir1) == 1
1561 assert len(tmpdir2) == 1
1562 symlink_test_dir1 = tmpdir1[0]
1563 symlink_test_dir2 = tmpdir2[0] / 'boost/include'
1564 symlink_file1 = symlink_test_dir1 / 'foo/link1'
1565 symlink_file2 = symlink_test_dir1 / 'foo/link2.h'
1566 symlink_file3 = symlink_test_dir2 / 'boost'
1567
1568 def clear_transitive_files() -> None:
1569 a = Path('test cases/common')
1570 for d in a.glob('*subproject subdir/subprojects/subsubsub*'):
1571 if d.is_dir():
1572 mesonlib.windows_proof_rmtree(str(d))
1573 else:
1574 mesonlib.windows_proof_rm(str(d))
1575 try:
1576 if symlink_file1 is not None:
1577 symlink_file1.unlink()
1578 except FileNotFoundError:
1579 pass
1580 try:
1581 if symlink_file2 is not None:
1582 symlink_file2.unlink()
1583 except FileNotFoundError:
1584 pass
1585 try:
1586 if symlink_file3 is not None:
1587 symlink_file3.unlink()
1588 symlink_test_dir2.rmdir()
1589 except FileNotFoundError:
1590 pass
1591
1592 def setup_symlinks() -> None:
1593 try:
1594 symlink_file1.symlink_to('file1')
1595 symlink_file2.symlink_to('file1')
1596 symlink_test_dir2.mkdir(parents=True, exist_ok=True)
1597 symlink_file3.symlink_to('../Cellar/boost/0.3.0/include/boost')
1598 except OSError:
1599 print('symlinks are not supported on this system')
1600
1601 def validate_only(s: str) -> str:
1602 split = s.split('/', 1)
1603 if split[0] not in ALL_TESTS:
1604 raise argparse.ArgumentTypeError(f'invalid category {split[0]!r}; must be one of {", ".join(ALL_TESTS)}')
1605 return s
1606
1607
1608 if __name__ == '__main__':
1609 if under_ci and not raw_ci_jobname:
1610 raise SystemExit('Running under CI but $MESON_CI_JOBNAME is not set (set to "thirdparty" if you are running outside of the github org)')
1611
1612 setup_vsenv()
1613 try:
1614 # This fails in some CI environments for unknown reasons.
1615 num_workers = multiprocessing.cpu_count()
1616 except Exception as e:
1617 print('Could not determine number of CPUs due to the following reason:', str(e))
1618 print('Defaulting to using only two processes')
1619 num_workers = 2
1620
1621 if num_workers > 64:
1622 # Too much parallelism seems to trigger a potential Python bug:
1623 # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1004107
1624 num_workers = 64
1625
1626 parser = argparse.ArgumentParser(description="Run the test suite of Meson.")
1627 parser.add_argument('extra_args', nargs='*',
1628 help='arguments that are passed directly to Meson (remember to have -- before these).')
1629 parser.add_argument('--backend', dest='backend', choices=backendlist)
1630 parser.add_argument('-j', dest='num_workers', type=int, default=num_workers,
1631 help=f'Maximum number of parallel tests (default {num_workers})')
1632 parser.add_argument('--failfast', action='store_true',
1633 help='Stop running if test case fails')
1634 parser.add_argument('--no-unittests', action='store_true',
1635 help='Not used, only here to simplify run_tests.py')
1636 parser.add_argument('--only', default=[], type=validate_only,
1637 help='name of test(s) to run, in format "category[/name]" where category is one of: ' + ', '.join(ALL_TESTS), nargs='+')
1638 parser.add_argument('-v', default=False, action='store_true',
1639 help='Verbose mode')
1640 parser.add_argument('--cross-file', action='store', help='File describing cross compilation environment.')
1641 parser.add_argument('--native-file', action='store', help='File describing native compilation environment.')
1642 parser.add_argument('--use-tmpdir', action='store_true', help='Use tmp directory for temporary files.')
1643 options = T.cast('ArgumentType', parser.parse_args())
1644 verbose_output = options.v
1645
1646 if options.cross_file:
1647 options.extra_args += ['--cross-file', options.cross_file]
1648 if options.native_file:
1649 options.extra_args += ['--native-file', options.native_file]
1650
1651 if not mesonlib.is_windows():
1652 scan_test_data_symlinks()
1653 clear_transitive_files()
1654 if not mesonlib.is_windows():
1655 setup_symlinks()
1656 mesonlib.set_meson_command(get_meson_script())
1657
1658 print('Meson build system', meson_version, 'Project Tests')
1659 print('Using python', sys.version.split('\n')[0], f'({sys.executable!r})')
1660 if 'VSCMD_VER' in os.environ:
1661 print('VSCMD version', os.environ['VSCMD_VER'])
1662 setup_commands(options.backend)
1663 detect_system_compiler(options)
1664 detect_tools()
1665 script_dir = os.path.split(__file__)[0]
1666 if script_dir != '':
1667 os.chdir(script_dir)
1668 check_meson_commands_work(options.use_tmpdir, options.extra_args)
1669 only = collections.defaultdict(list)
1670 for i in options.only:
1671 try:
1672 cat, case = i.split('/')
1673 only[cat].append(case)
1674 except ValueError:
1675 only[i].append('')
1676 try:
1677 all_tests = detect_tests_to_run(only, options.use_tmpdir)
1678 res = run_tests(all_tests, 'meson-test-run', options.failfast, options.extra_args, options.use_tmpdir, options.num_workers)
1679 (passing_tests, failing_tests, skipped_tests) = res
1680 except StopException:
1681 pass
1682 if failing_tests > 0:
1683 print('\nMesonlogs of failing tests\n')
1684 for l in failing_logs:
1685 try:
1686 print(l, '\n')
1687 except UnicodeError:
1688 print(l.encode('ascii', errors='replace').decode(), '\n')
1689 print()
1690 print('Total passed tests: ', green(str(passing_tests)))
1691 print('Total failed tests: ', red(str(failing_tests)))
1692 print('Total skipped tests:', yellow(str(skipped_tests)))
1693 if failing_tests > 0:
1694 print('\nAll failures:')
1695 for c in failing_testcases:
1696 print(f' -> {c}')
1697 for name, dirs, _ in all_tests:
1698 dir_names = list({x.path.name for x in dirs})
1699 for k, g in itertools.groupby(dir_names, key=lambda x: x.split()[0]):
1700 tests = list(g)
1701 if len(tests) != 1:
1702 print('WARNING: The {} suite contains duplicate "{}" tests: "{}"'.format(name, k, '", "'.join(tests)))
1703 clear_transitive_files()
1704 raise SystemExit(failing_tests)