Debian Codegraph @

mesonbuild/mtest.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2016-2017 The Meson development team
3
4 # A tool to run tests in many different ways.
5 from __future__ import annotations
6
7 from pathlib import Path
8 from collections import deque
9 from contextlib import suppress
10 from copy import deepcopy
11 from fnmatch import fnmatch
12 import argparse
13 import asyncio
14 import datetime
15 import enum
16 import json
17 import os
18 import pickle
19 import platform
20 import random
21 import re
22 import signal
23 import subprocess
24 import shlex
25 import sys
26 import time
27 import typing as T
28 import unicodedata
29 import xml.etree.ElementTree as et
30
31 from . import build
32 from . import tooldetect
33 from . import mlog
34 from .coredata import MesonVersionMismatchException, major_versions_differ
35 from .coredata import version as coredata_version
36 from .mesonlib import (MesonException, OrderedSet, RealPathAction,
37 get_wine_shortpath, join_args, split_args, setup_vsenv,
38 determine_worker_count)
39 from .options import OptionKey
40 from .programs import ExternalProgram
41 from .backend.backends import TestProtocol, TestSerialisation
42
43 if T.TYPE_CHECKING:
44 TYPE_TAPResult = T.Union['TAPParser.Test',
45 'TAPParser.Error',
46 'TAPParser.Version',
47 'TAPParser.Plan',
48 'TAPParser.UnknownLine',
49 'TAPParser.Bailout']
50
51
52 # GNU autotools interprets a return code of 77 from tests it executes to
53 # mean that the test should be skipped.
54 GNU_SKIP_RETURNCODE = 77
55
56 # GNU autotools interprets a return code of 99 from tests it executes to
57 # mean that the test failed even before testing what it is supposed to test.
58 GNU_ERROR_RETURNCODE = 99
59
60 # Exit if 3 Ctrl-C's are received within one second
61 MAX_CTRLC = 3
62
63 # Define unencodable xml characters' regex for replacing them with their
64 # printable representation
65 UNENCODABLE_XML_UNICHRS: T.List[T.Tuple[int, int]] = [
66 (0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F), (0x7F, 0x84),
67 (0x86, 0x9F), (0xFDD0, 0xFDEF), (0xFFFE, 0xFFFF)]
68 # Not narrow build
69 if sys.maxunicode >= 0x10000:
70 UNENCODABLE_XML_UNICHRS.extend([
71 (0x1FFFE, 0x1FFFF), (0x2FFFE, 0x2FFFF),
72 (0x3FFFE, 0x3FFFF), (0x4FFFE, 0x4FFFF),
73 (0x5FFFE, 0x5FFFF), (0x6FFFE, 0x6FFFF),
74 (0x7FFFE, 0x7FFFF), (0x8FFFE, 0x8FFFF),
75 (0x9FFFE, 0x9FFFF), (0xAFFFE, 0xAFFFF),
76 (0xBFFFE, 0xBFFFF), (0xCFFFE, 0xCFFFF),
77 (0xDFFFE, 0xDFFFF), (0xEFFFE, 0xEFFFF),
78 (0xFFFFE, 0xFFFFF), (0x10FFFE, 0x10FFFF)])
79 UNENCODABLE_XML_CHR_RANGES = [fr'{chr(low)}-{chr(high)}' for (low, high) in UNENCODABLE_XML_UNICHRS]
80 UNENCODABLE_XML_CHRS_RE = re.compile('([' + ''.join(UNENCODABLE_XML_CHR_RANGES) + '])')
81
82 RUST_TEST_RE = re.compile(r'^test (?!result)(.*) \.\.\. (.*)$')
83 RUST_DOCTEST_RE = re.compile(r'^(.*?) - (.*? |)\(line (\d+)\)')
84
85
86 def is_windows() -> bool:
87 platname = platform.system().lower()
88 return platname == 'windows'
89
90 def is_cygwin() -> bool:
91 return sys.platform == 'cygwin'
92
93 def is_os2() -> bool:
94 return platform.system().lower() == 'os/2'
95
96 UNIWIDTH_MAPPING = {'F': 2, 'H': 1, 'W': 2, 'Na': 1, 'N': 1, 'A': 1}
97 def uniwidth(s: str) -> int:
98 result = 0
99 for c in s:
100 w = unicodedata.east_asian_width(c)
101 result += UNIWIDTH_MAPPING[w]
102 return result
103
104 def test_slice(arg: str) -> T.Tuple[int, int]:
105 values = arg.split('/')
106 if len(values) != 2:
107 raise argparse.ArgumentTypeError("value does not conform to format 'SLICE/NUM_SLICES'")
108
109 try:
110 nrslices = int(values[1])
111 except ValueError:
112 raise argparse.ArgumentTypeError('NUM_SLICES is not an integer')
113 if nrslices <= 0:
114 raise argparse.ArgumentTypeError('NUM_SLICES is not a positive integer')
115
116 try:
117 subslice = int(values[0])
118 except ValueError:
119 raise argparse.ArgumentTypeError('SLICE is not an integer')
120 if subslice <= 0:
121 raise argparse.ArgumentTypeError('SLICE is not a positive integer')
122 if subslice > nrslices:
123 raise argparse.ArgumentTypeError('SLICE exceeds NUM_SLICES')
124
125 return subslice, nrslices
126
127 # Note: when adding arguments, please also add them to the completion
128 # scripts in $MESONSRC/data/shell-completions/
129 def add_arguments(parser: argparse.ArgumentParser) -> None:
130 parser.add_argument('-k', '--maxfail', default=0, type=int,
131 help='Number of failing tests before aborting the '
132 'test run. (default: 0, to disable aborting on failure)')
133 parser.add_argument('--repeat', default=1, dest='repeat', type=int,
134 help='Number of times to run the tests.')
135 parser.add_argument('--no-rebuild', default=False, action='store_true',
136 help='Do not rebuild before running tests.')
137 parser.add_argument('--gdb', default=False, dest='gdb', action='store_true',
138 help='Run test under gdb.')
139 parser.add_argument('--gdb-path', default='gdb', dest='gdb_path',
140 help='Path to the gdb binary (default: gdb).')
141 parser.add_argument('-i', '--interactive', default=False, dest='interactive',
142 action='store_true', help='Run tests with interactive input/output.')
143 parser.add_argument('--list', default=False, dest='list', action='store_true',
144 help='List available tests.')
145 parser.add_argument('--wrapper', default=None, dest='wrapper', type=split_args,
146 help='wrapper to run tests with (e.g. Valgrind)')
147 parser.add_argument('-C', dest='wd', action=RealPathAction,
148 help='directory to cd into before running')
149 parser.add_argument('--suite', default=[], dest='include_suites', action='append', metavar='SUITE',
150 help='Only run tests belonging to the given suite.')
151 parser.add_argument('--no-suite', default=[], dest='exclude_suites', action='append', metavar='SUITE',
152 help='Do not run tests belonging to the given suite.')
153 parser.add_argument('--exclude', default=[], dest='exclude', action='append',
154 help='Exclude tests with the given name.')
155 parser.add_argument('--no-stdsplit', default=True, dest='split', action='store_false',
156 help='Do not split stderr and stdout in test logs.')
157 parser.add_argument('--print-errorlogs', default=False, action='store_true',
158 help="Whether to print failing tests' logs.")
159 parser.add_argument('--benchmark', default=False, action='store_true',
160 help="Run benchmarks instead of tests.")
161 parser.add_argument('--logbase', default='testlog',
162 help="Base name for log file.")
163 parser.add_argument('-j', '--num-processes', default=determine_worker_count(['MESON_TESTTHREADS']), type=int,
164 help='How many parallel processes to use.')
165 parser.add_argument('-v', '--verbose', default=False, action='store_true',
166 help='Do not redirect stdout and stderr')
167 parser.add_argument('-q', '--quiet', default=False, action='store_true',
168 help='Produce less output to the terminal.')
169 parser.add_argument('-t', '--timeout-multiplier', type=float, default=None,
170 help='Define a multiplier for test timeout, for example '
171 ' when running tests in particular conditions they might take'
172 ' more time to execute. (<= 0 to disable timeout)')
173 parser.add_argument('--setup', default=None, dest='setup',
174 help='Which test setup to use.')
175 parser.add_argument('--test-args', default=[], type=split_args,
176 help='Arguments to pass to the specified test(s) or all tests')
177 parser.add_argument('--max-lines', default=100, dest='max_lines', type=int,
178 help='Maximum number of lines to show from a long test log. Since 1.5.0.')
179 parser.add_argument('--slice', default=None, type=test_slice, metavar='SLICE/NUM_SLICES',
180 help='Split tests into NUM_SLICES slices and execute slice SLICE. Since 1.8.0.')
181 parser.add_argument('args', nargs='*',
182 help='Optional list of test names to run. "testname" to run all tests with that name, '
183 '"subprojname:testname" to specifically run "testname" from "subprojname", '
184 '"subprojname:" to run all tests defined by "subprojname".')
185
186 def print_safe(s: str) -> None:
187 end = '' if s[-1] == '\n' else '\n'
188 try:
189 print(s, end=end)
190 except UnicodeEncodeError:
191 s = s.encode('ascii', errors='backslashreplace').decode('ascii')
192 print(s, end=end)
193
194 def join_lines(a: str, b: str) -> str:
195 if not a:
196 return b
197 if not b:
198 return a
199 return a + '\n' + b
200
201 def dashes(s: str, dash: str, cols: int) -> str:
202 if not s:
203 return dash * cols
204 s = ' ' + s + ' '
205 width = uniwidth(s)
206 first = (cols - width) // 2
207 s = dash * first + s
208 return s + dash * (cols - first - width)
209
210 def returncode_to_status(retcode: int) -> str:
211 # Note: We can't use `os.WIFSIGNALED(result.returncode)` and the related
212 # functions here because the status returned by subprocess is munged. It
213 # returns a negative value if the process was killed by a signal rather than
214 # the raw status returned by `wait()`. Also, If a shell sits between Meson
215 # the actual unit test that shell is likely to convert a termination due
216 # to a signal into an exit status of 128 plus the signal number.
217 if retcode < 0:
218 signum = -retcode
219 try:
220 signame = signal.Signals(signum).name
221 except ValueError:
222 signame = 'SIGinvalid'
223 return f'killed by signal {signum} {signame}'
224
225 if retcode <= 128:
226 return f'exit status {retcode}'
227
228 signum = retcode - 128
229 if signum < 32:
230 try:
231 signame = signal.Signals(signum).name
232 except ValueError:
233 signame = 'SIGinvalid'
234 return f'(exit status {retcode} or signal {signum} {signame})'
235
236 return f'(exit status {retcode} or {hex(retcode)})'
237
238 # TODO for Windows
239 sh_quote: T.Callable[[str], str] = lambda x: x
240 if not is_windows():
241 sh_quote = shlex.quote
242
243 def env_tuple_to_str(env: T.Iterable[T.Tuple[str, str]]) -> str:
244 return ''.join(["{}={} ".format(k, sh_quote(v)) for k, v in env])
245
246
247 class TestException(MesonException):
248 pass
249
250
251 @enum.unique
252 class ConsoleUser(enum.Enum):
253
254 # the logger can use the console
255 LOGGER = 0
256
257 # the console is used by gdb or the user
258 INTERACTIVE = 1
259
260 # the console is used to write stdout/stderr
261 STDOUT = 2
262
263
264 @enum.unique
265 class TestResult(enum.Enum):
266
267 PENDING = 'PENDING'
268 RUNNING = 'RUNNING'
269 OK = 'OK'
270 TIMEOUT = 'TIMEOUT'
271 INTERRUPT = 'INTERRUPT'
272 SKIP = 'SKIP'
273 FAIL = 'FAIL'
274 EXPECTEDFAIL = 'EXPECTEDFAIL'
275 UNEXPECTEDPASS = 'UNEXPECTEDPASS'
276 ERROR = 'ERROR'
277 IGNORED = 'IGNORED'
278
279 @staticmethod
280 def maxlen() -> int:
281 return 14 # len(UNEXPECTEDPASS)
282
283 def is_ok(self) -> bool:
284 return self in {TestResult.OK, TestResult.EXPECTEDFAIL}
285
286 def is_bad(self) -> bool:
287 return self in {TestResult.FAIL, TestResult.TIMEOUT, TestResult.INTERRUPT,
288 TestResult.UNEXPECTEDPASS, TestResult.ERROR}
289
290 def is_finished(self) -> bool:
291 return self not in {TestResult.PENDING, TestResult.RUNNING}
292
293 def was_killed(self) -> bool:
294 return self in (TestResult.TIMEOUT, TestResult.INTERRUPT)
295
296 def colorize(self, s: str) -> mlog.AnsiDecorator:
297 if self.is_bad():
298 decorator = mlog.red
299 elif self in (TestResult.SKIP, TestResult.IGNORED, TestResult.EXPECTEDFAIL):
300 decorator = mlog.yellow
301 elif self.is_finished():
302 decorator = mlog.green
303 else:
304 decorator = mlog.blue
305 return decorator(s)
306
307 def get_text(self, colorize: bool) -> str:
308 result_str = '{res:{reslen}}'.format(res=self.value, reslen=self.maxlen())
309 return self.colorize(result_str).get_text(colorize)
310
311 def get_command_marker(self) -> str:
312 return str(self.colorize('>>> '))
313
314
315 class TAPParser:
316 class Plan(T.NamedTuple):
317 num_tests: int
318 late: bool
319 skipped: bool
320 explanation: T.Optional[str]
321
322 class Bailout(T.NamedTuple):
323 message: str
324
325 class Test(T.NamedTuple):
326 number: int
327 name: str
328 result: TestResult
329 explanation: T.Optional[str]
330
331 def __str__(self) -> str:
332 return f'{self.number} {self.name}'.strip()
333
334 class Error(T.NamedTuple):
335 message: str
336
337 class UnknownLine(T.NamedTuple):
338 message: str
339 lineno: int
340
341 class Version(T.NamedTuple):
342 version: int
343
344 _MAIN = 1
345 _AFTER_TEST = 2
346 _YAML = 3
347
348 _RE_BAILOUT = re.compile(r'Bail out!\s*(.*)')
349 _RE_DIRECTIVE = re.compile(r'(?:\s*\#\s*([Ss][Kk][Ii][Pp]\S*|[Tt][Oo][Dd][Oo])\b\s*(.*))?')
350 _RE_PLAN = re.compile(r'1\.\.([0-9]+)' + _RE_DIRECTIVE.pattern)
351 _RE_TEST = re.compile(r'((?:not )?ok)\s*(?:([0-9]+)\s*)?([^#]*)' + _RE_DIRECTIVE.pattern)
352 _RE_VERSION = re.compile(r'TAP version ([0-9]+)')
353 _RE_YAML_START = re.compile(r'(\s+)---.*')
354 _RE_YAML_END = re.compile(r'\s+\.\.\.\s*')
355
356 found_late_test = False
357 bailed_out = False
358 plan: T.Optional[Plan] = None
359 lineno = 0
360 num_tests = 0
361 last_test = 0
362 highest_test = 0
363 yaml_lineno: T.Optional[int] = None
364 yaml_indent = ''
365 state = _MAIN
366 version = 12
367
368 def parse_test(self, ok: bool, num: int, name: str, directive: T.Optional[str], explanation: T.Optional[str]) -> \
369 T.Generator[T.Union['TAPParser.Test', 'TAPParser.Error'], None, None]:
370 name = name.strip()
371 explanation = explanation.strip() if explanation else None
372 if directive is not None:
373 directive = directive.upper()
374 if directive.startswith('SKIP'):
375 if ok:
376 yield self.Test(num, name, TestResult.SKIP, explanation)
377 return
378 elif directive == 'TODO':
379 yield self.Test(num, name, TestResult.UNEXPECTEDPASS if ok else TestResult.EXPECTEDFAIL, explanation)
380 return
381 else:
382 yield self.Error(f'invalid directive "{directive}"')
383
384 yield self.Test(num, name, TestResult.OK if ok else TestResult.FAIL, explanation)
385
386 async def parse_async(self, lines: T.AsyncIterator[str]) -> T.AsyncIterator[TYPE_TAPResult]:
387 async for line in lines:
388 for event in self.parse_line(line):
389 yield event
390 for event in self.parse_line(None):
391 yield event
392
393 def parse(self, io: T.Iterator[str]) -> T.Iterator[TYPE_TAPResult]:
394 for line in io:
395 yield from self.parse_line(line)
396 yield from self.parse_line(None)
397
398 def parse_line(self, line: T.Optional[str]) -> T.Iterator[TYPE_TAPResult]:
399 if line is not None:
400 self.lineno += 1
401
402 # YAML blocks are only accepted after a test
403 if self.state == self._AFTER_TEST:
404 if self.version >= 13:
405 m = self._RE_YAML_START.match(line)
406 if m:
407 self.state = self._YAML
408 self.yaml_lineno = self.lineno
409 self.yaml_indent = m.group(1)
410 return
411 self.state = self._MAIN
412
413 elif self.state == self._YAML:
414 if self._RE_YAML_END.match(line):
415 self.state = self._MAIN
416 return
417 if line.startswith(self.yaml_indent):
418 return
419 yield self.Error(f'YAML block not terminated (started on line {self.yaml_lineno})')
420 self.state = self._MAIN
421
422 line = line.rstrip()
423
424 assert self.state == self._MAIN
425 if not line or line.startswith('#'):
426 return
427
428 m = self._RE_TEST.match(line)
429 if m:
430 if self.plan and self.plan.late and not self.found_late_test:
431 yield self.Error('unexpected test after late plan')
432 self.found_late_test = True
433 self.num_tests += 1
434 self.last_test = self.last_test + 1 if m.group(2) is None else int(m.group(2))
435 self.highest_test = max(self.highest_test, self.last_test)
436 if self.plan and self.last_test > self.plan.num_tests:
437 yield self.Error('test number exceeds maximum specified in test plan')
438 yield from self.parse_test(m.group(1) == 'ok', self.last_test,
439 m.group(3), m.group(4), m.group(5))
440 self.state = self._AFTER_TEST
441 return
442
443 m = self._RE_PLAN.match(line)
444 if m:
445 if self.plan:
446 yield self.Error('more than one plan found')
447 else:
448 num_tests = int(m.group(1))
449 skipped = num_tests == 0
450 if m.group(2):
451 if m.group(2).upper().startswith('SKIP'):
452 if num_tests > 0:
453 yield self.Error('invalid SKIP directive for plan')
454 skipped = True
455 else:
456 yield self.Error('invalid directive for plan')
457 self.plan = self.Plan(num_tests=num_tests, late=(self.num_tests > 0),
458 skipped=skipped, explanation=m.group(3))
459 yield self.plan
460 return
461
462 m = self._RE_BAILOUT.match(line)
463 if m:
464 yield self.Bailout(m.group(1))
465 self.bailed_out = True
466 return
467
468 m = self._RE_VERSION.match(line)
469 if m:
470 # The TAP version is only accepted as the first line
471 if self.lineno != 1:
472 yield self.Error('version number must be on the first line')
473 return
474 self.version = int(m.group(1))
475 if self.version < 13:
476 yield self.Error('version number should be at least 13')
477 else:
478 yield self.Version(version=self.version)
479 return
480
481 # unknown syntax
482 yield self.UnknownLine(line, self.lineno)
483 else:
484 # end of file
485 if self.state == self._YAML:
486 yield self.Error(f'YAML block not terminated (started on line {self.yaml_lineno})')
487
488 if self.bailed_out:
489 return
490
491 if self.plan and self.num_tests != self.plan.num_tests:
492 if self.num_tests < self.plan.num_tests:
493 yield self.Error(f'Too few tests run (expected {self.plan.num_tests}, got {self.num_tests})')
494 else:
495 yield self.Error(f'Too many tests run (expected {self.plan.num_tests}, got {self.num_tests})')
496 return
497
498 if self.highest_test != self.num_tests:
499 if self.highest_test < self.num_tests:
500 yield self.Error(f'Duplicate test numbers (expected {self.num_tests}, got test numbered {self.highest_test}')
501 else:
502 yield self.Error(f'Missing test numbers (expected {self.num_tests}, got test numbered {self.highest_test}')
503
504 class TestLogger:
505 def flush(self) -> None:
506 pass
507
508 def start(self, harness: 'TestHarness') -> None:
509 pass
510
511 def start_test(self, harness: 'TestHarness', test: 'TestRun') -> None:
512 pass
513
514 def log_subtest(self, harness: 'TestHarness', test: 'TestRun', s: str, res: TestResult,
515 explanation: T.Optional[str]) -> None:
516 pass
517
518 def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
519 pass
520
521 async def finish(self, harness: 'TestHarness') -> None:
522 pass
523
524 def close(self) -> None:
525 pass
526
527
528 class TestFileLogger(TestLogger):
529 def __init__(self, filename: str, errors: str = 'replace') -> None:
530 self.filename = filename
531 self.file = open(filename, 'w', encoding='utf-8', errors=errors)
532
533 def close(self) -> None:
534 if self.file:
535 self.file.close()
536 self.file = None
537
538
539 class ConsoleLogger(TestLogger):
540 ASCII_SPINNER = ['..', ':.', '.:']
541 SPINNER = ["\U0001f311", "\U0001f312", "\U0001f313", "\U0001f314",
542 "\U0001f315", "\U0001f316", "\U0001f317", "\U0001f318"]
543
544 SCISSORS = "\u2700 "
545 HLINE = "\u2015"
546 RTRI = "\u25B6 "
547
548 def __init__(self, max_lines: int) -> None:
549 self.max_lines = max_lines
550 self.running_tests: OrderedSet['TestRun'] = OrderedSet()
551 self.progress_test: T.Optional['TestRun'] = None
552 self.progress_task: T.Optional[asyncio.Future] = None
553 self.max_left_width = 0
554 self.stop = False
555 # TODO: before 3.10 this cannot be created immediately, because
556 # it will create a new event loop
557 self.update: asyncio.Event
558 self.should_erase_line = ''
559 self.test_count = 0
560 self.started_tests = 0
561 self.spinner_index = 0
562 self.is_tty = sys.stdout.isatty()
563 self.cols = 80
564 if self.is_tty:
565 try:
566 self.cols, _ = os.get_terminal_size(1)
567 except (OSError, AttributeError):
568 self.is_tty = False
569
570 self.output_start = dashes(self.SCISSORS, self.HLINE, self.cols - 2)
571 self.output_end = dashes('', self.HLINE, self.cols - 2)
572 self.sub = self.RTRI
573 self.spinner = self.SPINNER
574 try:
575 self.output_start.encode(sys.stdout.encoding or 'ascii')
576 except UnicodeEncodeError:
577 self.output_start = dashes('8<', '-', self.cols - 2)
578 self.output_end = dashes('', '-', self.cols - 2)
579 self.sub = '| '
580 self.spinner = self.ASCII_SPINNER
581
582 def flush(self) -> None:
583 if self.should_erase_line:
584 print(self.should_erase_line, end='')
585 self.should_erase_line = ''
586
587 def print_progress(self, line: str) -> None:
588 print(self.should_erase_line, line, sep='', end='\r')
589 if self.is_tty:
590 self.should_erase_line = '\x1b[K'
591 else:
592 self.should_erase_line = '\n'
593
594 def request_update(self) -> None:
595 self.update.set()
596
597 def emit_progress(self, harness: 'TestHarness') -> None:
598 if self.progress_test is None:
599 self.flush()
600 return
601
602 if len(self.running_tests) == 1:
603 count = f'{self.started_tests}/{self.test_count}'
604 else:
605 count = '{}-{}/{}'.format(self.started_tests - len(self.running_tests) + 1,
606 self.started_tests, self.test_count)
607
608 left = '[{}] {} '.format(count, self.spinner[self.spinner_index])
609 self.spinner_index = (self.spinner_index + 1) % len(self.spinner)
610
611 right = '{spaces} {dur:{durlen}}'.format(
612 spaces=' ' * TestResult.maxlen(),
613 dur=int(time.time() - self.progress_test.starttime),
614 durlen=harness.duration_max_len)
615 if self.progress_test.timeout:
616 right += '/{timeout:{durlen}}'.format(
617 timeout=self.progress_test.timeout,
618 durlen=harness.duration_max_len)
619 right += 's'
620 details = self.progress_test.get_details()
621 if details:
622 right += ' ' + details
623
624 line = harness.format(self.progress_test, colorize=True,
625 max_left_width=self.max_left_width,
626 left=left, right=right)
627 self.print_progress(line)
628
629 def start(self, harness: 'TestHarness') -> None:
630 async def report_progress() -> None:
631 loop = asyncio.get_running_loop()
632 next_update = 0.0
633 self.request_update()
634 while not self.stop:
635 await self.update.wait()
636 self.update.clear()
637 # We may get here simply because the progress line has been
638 # overwritten, so do not always switch. Only do so every
639 # second, or if the printed test has finished
640 if loop.time() >= next_update:
641 self.progress_test = None
642 next_update = loop.time() + 1
643 loop.call_at(next_update, self.request_update)
644
645 if (self.progress_test and
646 self.progress_test.res is not TestResult.RUNNING):
647 self.progress_test = None
648
649 if not self.progress_test:
650 if not self.running_tests:
651 continue
652 # Pick a test in round robin order
653 self.progress_test = self.running_tests.pop(last=False)
654 self.running_tests.add(self.progress_test)
655
656 self.emit_progress(harness)
657 self.flush()
658
659 self.update = asyncio.Event()
660 self.test_count = harness.test_count
661 self.cols = max(self.cols, harness.max_left_width + 30)
662
663 if self.is_tty and not harness.need_console:
664 # Account for "[aa-bb/cc] OO " in the progress report
665 self.max_left_width = 3 * len(str(self.test_count)) + 8
666 self.progress_task = asyncio.ensure_future(report_progress())
667
668 def start_test(self, harness: 'TestHarness', test: 'TestRun') -> None:
669 if test.verbose and test.cmdline:
670 self.flush()
671 print(harness.format(test, mlog.colorize_console(),
672 max_left_width=self.max_left_width,
673 right=test.res.get_text(mlog.colorize_console())))
674 print(test.res.get_command_marker() + test.cmdline)
675 if test.direct_stdout:
676 print(self.output_start, flush=True)
677 elif not test.needs_parsing:
678 print(flush=True)
679
680 self.started_tests += 1
681 self.running_tests.add(test)
682 self.running_tests.move_to_end(test, last=False)
683 self.request_update()
684
685 def shorten_log(self, harness: 'TestHarness', result: 'TestRun') -> str:
686 if not result.verbose and not harness.options.print_errorlogs:
687 return ''
688
689 log = result.get_log(mlog.colorize_console(),
690 stderr_only=result.needs_parsing)
691 if result.verbose:
692 return log
693
694 lines = log.splitlines()
695 if len(lines) < self.max_lines:
696 return log
697 else:
698 return str(mlog.bold(f'Listing only the last {self.max_lines} lines from a long log.\n')) + '\n'.join(lines[-self.max_lines:])
699
700 def print_log(self, harness: 'TestHarness', result: 'TestRun') -> None:
701 if not result.verbose:
702 cmdline = result.cmdline
703 if not cmdline:
704 print(result.res.get_command_marker() + result.stdo)
705 return
706 print(result.res.get_command_marker() + cmdline)
707
708 log = self.shorten_log(harness, result)
709 if log:
710 print(self.output_start)
711 print_safe(log)
712 print(self.output_end)
713
714 def log_subtest(self, harness: 'TestHarness', test: 'TestRun', s: str, result: TestResult, explanation: T.Optional[str]) -> None:
715 if test.verbose or (harness.options.print_errorlogs and result.is_bad()):
716 self.flush()
717 print(harness.format(test, mlog.colorize_console(), max_left_width=self.max_left_width,
718 prefix=self.sub,
719 middle=s,
720 right=result.get_text(mlog.colorize_console())), flush=True)
721
722 if explanation is not None:
723 print(result.colorize(f"{' ' * len(self.sub)}Reason: {explanation}").get_text(mlog.colorize_console()))
724
725 self.request_update()
726
727 def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
728 self.running_tests.remove(result)
729 if result.res is TestResult.TIMEOUT and (result.verbose or
730 harness.options.print_errorlogs):
731 self.flush()
732 print(f'{result.name} time out (After {result.timeout} seconds)')
733
734 if not harness.options.quiet or not result.res.is_ok():
735 self.flush()
736 if result.cmdline and result.direct_stdout:
737 print(self.output_end)
738 print(harness.format(result, mlog.colorize_console(), max_left_width=self.max_left_width))
739 else:
740 print(harness.format(result, mlog.colorize_console(), max_left_width=self.max_left_width),
741 flush=True)
742 if result.verbose or harness.is_bad_result(result):
743 self.print_log(harness, result)
744 if result.warnings:
745 print(flush=True)
746 for w in result.warnings:
747 print(w, flush=True)
748 print(flush=True)
749 if result.verbose or result.res.is_bad():
750 print(flush=True)
751
752 self.request_update()
753
754 async def finish(self, harness: 'TestHarness') -> None:
755 self.stop = True
756 self.request_update()
757 if self.progress_task:
758 await self.progress_task
759
760 if harness.collected_failures and \
761 (harness.options.print_errorlogs or harness.options.verbose):
762 print("\nSummary of Failures:\n")
763 for i, result in enumerate(harness.collected_failures, 1):
764 print(harness.format(result, mlog.colorize_console()))
765
766 print(harness.summary())
767
768
769 class TextLogfileBuilder(TestFileLogger):
770 def start(self, harness: 'TestHarness') -> None:
771 self.file.write(f'Log of Meson test suite run on {datetime.datetime.now().isoformat()}\n\n')
772 inherit_env = env_tuple_to_str(os.environ.items())
773 self.file.write(f'Inherited environment: {inherit_env}\n\n')
774
775 def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
776 title = f'{result.num}/{harness.test_count}'
777 self.file.write(dashes(title, '=', 78) + '\n')
778 self.file.write('test: ' + result.name + '\n')
779 starttime_str = time.strftime("%H:%M:%S", time.gmtime(result.starttime))
780 self.file.write('start time: ' + starttime_str + '\n')
781 self.file.write('duration: ' + '%.2fs' % result.duration + '\n')
782 self.file.write('result: ' + result.get_exit_status() + '\n')
783 if result.cmdline:
784 self.file.write('command: ' + result.cmdline + '\n')
785 if result.stdo:
786 name = 'stdout' if harness.options.split else 'output'
787 self.file.write(dashes(name, '-', 78) + '\n')
788 self.file.write(result.stdo)
789 if result.stde:
790 self.file.write(dashes('stderr', '-', 78) + '\n')
791 self.file.write(result.stde)
792 self.file.write(dashes('', '=', 78) + '\n\n')
793
794 async def finish(self, harness: 'TestHarness') -> None:
795 if harness.collected_failures:
796 self.file.write("\nSummary of Failures:\n\n")
797 for i, result in enumerate(harness.collected_failures, 1):
798 self.file.write(harness.format(result, False) + '\n')
799 self.file.write(harness.summary())
800
801 print(f'Full log written to {self.filename}')
802
803
804 class JsonLogfileBuilder(TestFileLogger):
805 def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
806 jresult: T.Dict[str, T.Any] = {
807 'name': result.name,
808 'stdout': result.stdo,
809 'result': result.res.value,
810 'is_fail': result.res.is_bad(),
811 'starttime': result.starttime,
812 'duration': result.duration,
813 'returncode': result.returncode,
814 'env': result.env,
815 'command': result.cmd,
816 }
817 if result.stde:
818 jresult['stderr'] = result.stde
819 self.file.write(json.dumps(jresult) + '\n')
820
821
822 class JunitBuilder(TestLogger):
823
824 """Builder for Junit test results.
825
826 Junit is impossible to stream out, it requires attributes counting the
827 total number of tests, failures, skips, and errors in the root element
828 and in each test suite. As such, we use a builder class to track each
829 test case, and calculate all metadata before writing it out.
830
831 For tests with multiple results (like from a TAP test), we record the
832 test as a suite with the project_name.test_name. This allows us to track
833 each result separately. For tests with only one result (such as exit-code
834 tests) we record each one into a suite with the name project_name. The use
835 of the project_name allows us to sort subproject tests separately from
836 the root project.
837 """
838
839 def __init__(self, filename: str) -> None:
840 self.filename = filename
841 self.root = et.Element(
842 'testsuites', tests='0', errors='0', failures='0')
843 self.suites: T.Dict[str, et.Element] = {}
844
845 def log(self, harness: 'TestHarness', test: 'TestRun') -> None:
846 """Log a single test case."""
847 if test.junit is not None:
848 for suite in test.junit.findall('.//testsuite'):
849 # Assume that we don't need to merge anything here...
850 suite.attrib['name'] = '{}.{}.{}'.format(test.project, test.name, suite.attrib['name'])
851
852 # GTest can inject invalid attributes
853 for case in suite.findall('.//testcase[@result]'):
854 del case.attrib['result']
855 for case in suite.findall('.//testcase[@timestamp]'):
856 del case.attrib['timestamp']
857 for case in suite.findall('.//testcase[@file]'):
858 del case.attrib['file']
859 for case in suite.findall('.//testcase[@line]'):
860 del case.attrib['line']
861 self.root.append(suite)
862 return
863
864 # In this case we have a test binary with multiple results.
865 # We want to record this so that each result is recorded
866 # separately
867 if test.results:
868 suitename = f'{test.project}.{test.name}'
869 assert suitename not in self.suites or harness.options.repeat > 1, 'duplicate suite'
870
871 suite = self.suites[suitename] = et.Element(
872 'testsuite',
873 name=suitename,
874 tests=str(len(test.results)),
875 errors=str(sum(1 for r in test.results if r.result in
876 {TestResult.INTERRUPT, TestResult.ERROR})),
877 failures=str(sum(1 for r in test.results if r.result in
878 {TestResult.FAIL, TestResult.UNEXPECTEDPASS, TestResult.TIMEOUT})),
879 skipped=str(sum(1 for r in test.results if r.result in
880 {TestResult.SKIP, TestResult.IGNORED})),
881 time=str(test.duration),
882 )
883
884 for subtest in test.results:
885 # Both name and classname are required. Use the suite name as
886 # the class name, so that e.g. GitLab groups testcases correctly.
887 testcase = et.SubElement(suite, 'testcase', name=str(subtest), classname=suitename)
888 if subtest.result is TestResult.SKIP:
889 et.SubElement(testcase, 'skipped')
890 elif subtest.result is TestResult.IGNORED:
891 skip = et.SubElement(testcase, 'skipped')
892 skip.text = 'Test output was not parsed.'
893 elif subtest.result is TestResult.ERROR:
894 et.SubElement(testcase, 'error')
895 elif subtest.result is TestResult.FAIL:
896 et.SubElement(testcase, 'failure')
897 elif subtest.result is TestResult.UNEXPECTEDPASS:
898 fail = et.SubElement(testcase, 'failure')
899 fail.text = 'Test unexpectedly passed.'
900 elif subtest.result is TestResult.INTERRUPT:
901 fail = et.SubElement(testcase, 'error')
902 fail.text = 'Test was interrupted by user.'
903 elif subtest.result is TestResult.TIMEOUT:
904 fail = et.SubElement(testcase, 'error')
905 fail.text = 'Test did not finish before configured timeout.'
906 if subtest.explanation:
907 et.SubElement(testcase, 'system-out').text = subtest.explanation
908 if test.stdo:
909 out = et.SubElement(suite, 'system-out')
910 out.text = replace_unencodable_xml_chars(test.stdo.rstrip())
911 if test.stde:
912 err = et.SubElement(suite, 'system-err')
913 err.text = replace_unencodable_xml_chars(test.stde.rstrip())
914 else:
915 if test.project not in self.suites:
916 suite = self.suites[test.project] = et.Element(
917 'testsuite', name=test.project, tests='1', errors='0',
918 failures='0', skipped='0', time=str(test.duration))
919 else:
920 suite = self.suites[test.project]
921 suite.attrib['tests'] = str(int(suite.attrib['tests']) + 1)
922
923 testcase = et.SubElement(suite, 'testcase', name=test.name,
924 classname=test.project, time=str(test.duration))
925 if test.res is TestResult.SKIP:
926 et.SubElement(testcase, 'skipped')
927 suite.attrib['skipped'] = str(int(suite.attrib['skipped']) + 1)
928 elif test.res is TestResult.IGNORED:
929 skip = et.SubElement(testcase, 'skipped')
930 skip.text = 'Test output was not parsed.'
931 suite.attrib['skipped'] = str(int(suite.attrib['skipped']) + 1)
932 elif test.res is TestResult.ERROR:
933 et.SubElement(testcase, 'error')
934 suite.attrib['errors'] = str(int(suite.attrib['errors']) + 1)
935 elif test.res is TestResult.FAIL:
936 et.SubElement(testcase, 'failure')
937 suite.attrib['failures'] = str(int(suite.attrib['failures']) + 1)
938 elif test.res is TestResult.UNEXPECTEDPASS:
939 fail = et.SubElement(testcase, 'failure')
940 fail.text = 'Test unexpectedly passed.'
941 suite.attrib['failures'] = str(int(suite.attrib['failures']) + 1)
942 elif test.res is TestResult.INTERRUPT:
943 fail = et.SubElement(testcase, 'error')
944 fail.text = 'Test was interrupted by user.'
945 suite.attrib['errors'] = str(int(suite.attrib['errors']) + 1)
946 elif test.res is TestResult.TIMEOUT:
947 fail = et.SubElement(testcase, 'error')
948 fail.text = 'Test did not finish before configured timeout.'
949 suite.attrib['errors'] = str(int(suite.attrib['errors']) + 1)
950 if test.stdo:
951 out = et.SubElement(testcase, 'system-out')
952 out.text = replace_unencodable_xml_chars(test.stdo.rstrip())
953 if test.stde:
954 err = et.SubElement(testcase, 'system-err')
955 err.text = replace_unencodable_xml_chars(test.stde.rstrip())
956
957 async def finish(self, harness: 'TestHarness') -> None:
958 """Calculate total test counts and write out the xml result."""
959 for suite in self.suites.values():
960 self.root.append(suite)
961 # Skipped is really not allowed in the "testsuits" element
962 for attr in ['tests', 'errors', 'failures']:
963 self.root.attrib[attr] = str(int(self.root.attrib[attr]) + int(suite.attrib[attr]))
964
965 tree = et.ElementTree(self.root)
966 with open(self.filename, 'wb') as f:
967 tree.write(f, encoding='utf-8', xml_declaration=True)
968
969
970 class TestRun:
971 TEST_NUM = 0
972 PROTOCOL_TO_CLASS: T.Dict[TestProtocol, T.Type['TestRun']] = {}
973
974 def __new__(cls, test: TestSerialisation, *args: T.Any, **kwargs: T.Any) -> T.Any:
975 return super().__new__(TestRun.PROTOCOL_TO_CLASS[test.protocol])
976
977 def __init__(self, test: TestSerialisation, test_env: T.Dict[str, str],
978 name: str, timeout: T.Optional[int], is_parallel: bool, verbose: bool,
979 interactive: bool):
980 self.res = TestResult.PENDING
981 self.test = test
982 self._num: T.Optional[int] = None
983 self.name = name
984 self.timeout = timeout
985 self.results: T.List[TAPParser.Test] = []
986 self.returncode: T.Optional[int] = None
987 self.starttime: T.Optional[float] = None
988 self.duration: T.Optional[float] = None
989 self.stdo = ''
990 self.stde = ''
991 self.additional_error = ''
992 self.cmd: T.Optional[T.List[str]] = None
993 self.env = test_env
994 self.expected_fail = test.expected_fail
995 self.expected_exitcode = test.expected_exitcode
996 self.project = test.project_name
997 self.junit: T.Optional[et.ElementTree] = None
998 self.is_parallel = is_parallel
999 self.verbose = verbose
1000 self.interactive = interactive
1001 self.warnings: T.List[str] = []
1002
1003 def start(self, cmd: T.List[str]) -> None:
1004 self.res = TestResult.RUNNING
1005 self.starttime = time.time()
1006 self.cmd = cmd
1007
1008 @property
1009 def num(self) -> int:
1010 if self._num is None:
1011 TestRun.TEST_NUM += 1
1012 self._num = TestRun.TEST_NUM
1013 return self._num
1014
1015 @property
1016 def console_mode(self) -> ConsoleUser:
1017 if self.interactive:
1018 return ConsoleUser.INTERACTIVE
1019 elif self.direct_stdout:
1020 return ConsoleUser.STDOUT
1021 else:
1022 return ConsoleUser.LOGGER
1023
1024 @property
1025 def direct_stdout(self) -> bool:
1026 return self.verbose and not self.is_parallel and not self.needs_parsing
1027
1028 def get_results(self) -> str:
1029 if self.results:
1030 # running or succeeded
1031 passed = sum(x.result.is_ok() for x in self.results)
1032 ran = sum(x.result not in {TestResult.SKIP, TestResult.IGNORED} for x in self.results)
1033 if passed == ran:
1034 return f'{passed} subtests passed'
1035 else:
1036 return f'{passed}/{ran} subtests passed'
1037 return ''
1038
1039 def get_exit_status(self) -> str:
1040 return returncode_to_status(self.returncode)
1041
1042 def get_details(self) -> str:
1043 if self.res is TestResult.PENDING:
1044 return ''
1045 if self.returncode:
1046 return self.get_exit_status()
1047 return self.get_results()
1048
1049 def _complete(self) -> None:
1050 if self.res == TestResult.RUNNING:
1051 self.res = TestResult.OK
1052 if self.needs_parsing and self.console_mode is ConsoleUser.INTERACTIVE:
1053 self.res = TestResult.IGNORED
1054 assert isinstance(self.res, TestResult)
1055 if self.expected_fail and self.res in (TestResult.OK, TestResult.FAIL):
1056 self.res = TestResult.UNEXPECTEDPASS if self.res is TestResult.OK else TestResult.EXPECTEDFAIL
1057 if self.stdo and not self.stdo.endswith('\n'):
1058 self.stdo += '\n'
1059 if self.stde and not self.stde.endswith('\n'):
1060 self.stde += '\n'
1061 self.duration = time.time() - self.starttime
1062
1063 @property
1064 def cmdline(self) -> T.Optional[str]:
1065 if not self.cmd:
1066 return None
1067 test_only_env = set(self.env.items()) - set(os.environ.items())
1068 return env_tuple_to_str(test_only_env) + \
1069 ' '.join(sh_quote(x) for x in self.cmd)
1070
1071 def complete_skip(self) -> None:
1072 self.starttime = time.time()
1073 self.returncode = GNU_SKIP_RETURNCODE
1074 self.res = TestResult.SKIP
1075 self._complete()
1076
1077 def complete(self) -> None:
1078 self._complete()
1079
1080 def get_log(self, colorize: bool = False, stderr_only: bool = False) -> str:
1081 stdo = '' if stderr_only else self.stdo
1082 if self.stde or self.additional_error:
1083 res = ''
1084 if stdo:
1085 res += mlog.cyan('stdout:').get_text(colorize) + '\n'
1086 res += stdo
1087 if res[-1:] != '\n':
1088 res += '\n'
1089 res += mlog.cyan('stderr:').get_text(colorize) + '\n'
1090 res += join_lines(self.stde, self.additional_error)
1091 else:
1092 res = stdo
1093 if res and res[-1:] != '\n':
1094 res += '\n'
1095 return res
1096
1097 @property
1098 def needs_parsing(self) -> bool:
1099 return False
1100
1101 async def parse(self, harness: 'TestHarness', lines: T.AsyncIterator[str]) -> None:
1102 async for l in lines:
1103 pass
1104
1105
1106 class TestRunExitCode(TestRun):
1107
1108 def complete(self) -> None:
1109 if self.res != TestResult.RUNNING:
1110 pass
1111 elif self.returncode == (self.expected_exitcode or 0):
1112 self.res = TestResult.OK
1113 elif self.returncode == GNU_SKIP_RETURNCODE:
1114 self.res = TestResult.SKIP
1115 elif self.returncode == GNU_ERROR_RETURNCODE:
1116 self.res = TestResult.ERROR
1117 else:
1118 self.res = TestResult.FAIL
1119 super().complete()
1120
1121 TestRun.PROTOCOL_TO_CLASS[TestProtocol.EXITCODE] = TestRunExitCode
1122
1123
1124 class TestRunGTest(TestRunExitCode):
1125 def complete(self) -> None:
1126 filename = f'{self.test.name}.xml'
1127 if self.test.workdir:
1128 filename = os.path.join(self.test.workdir, filename)
1129
1130 try:
1131 with open(filename, 'r', encoding='utf8', errors='replace') as f:
1132 self.junit = et.parse(f)
1133 except FileNotFoundError:
1134 # This can happen if the test fails to run or complete for some
1135 # reason, like the rpath for libgtest isn't properly set. ExitCode
1136 # will handle the failure, don't generate a stacktrace.
1137 pass
1138 except et.ParseError as e:
1139 # ExitCode will handle the failure, don't generate a stacktrace.
1140 mlog.error(f'Unable to parse {filename}: {e!s}')
1141
1142 super().complete()
1143
1144 TestRun.PROTOCOL_TO_CLASS[TestProtocol.GTEST] = TestRunGTest
1145
1146
1147 class TestRunTAP(TestRun):
1148 @property
1149 def needs_parsing(self) -> bool:
1150 return True
1151
1152 def complete(self) -> None:
1153 if self.returncode != 0 and not self.res.is_bad():
1154 self.res = TestResult.ERROR
1155 self.stde = self.stde or ''
1156 self.stde += f'\n(test program exited with status code {self.returncode})'
1157 super().complete()
1158
1159 async def parse(self, harness: 'TestHarness', lines: T.AsyncIterator[str]) -> None:
1160 res = None
1161 warnings: T.List[TAPParser.UnknownLine] = []
1162 version = 12
1163
1164 async for i in TAPParser().parse_async(lines):
1165 if isinstance(i, TAPParser.Version):
1166 version = i.version
1167 elif isinstance(i, TAPParser.Bailout):
1168 res = TestResult.ERROR
1169 harness.log_subtest(self, i.message, res, None)
1170 elif isinstance(i, TAPParser.Test):
1171 self.results.append(i)
1172 if i.result.is_bad():
1173 res = TestResult.FAIL
1174 harness.log_subtest(self, i.name or f'subtest {i.number}', i.result, i.explanation)
1175 elif isinstance(i, TAPParser.UnknownLine):
1176 warnings.append(i)
1177 elif isinstance(i, TAPParser.Error):
1178 self.additional_error += 'TAP parsing error: ' + i.message
1179 res = TestResult.ERROR
1180
1181 if warnings:
1182 unknown = str(mlog.yellow('UNKNOWN'))
1183 width = len(str(max(i.lineno for i in warnings)))
1184 for w in warnings:
1185 self.warnings.append(f'stdout: {w.lineno:{width}}: {unknown}: {w.message}')
1186 if version > 13:
1187 self.warnings.append('Unknown TAP output lines have been ignored. Please open a feature request to\n'
1188 'implement them, or prefix them with a # if they are not TAP syntax.')
1189 else:
1190 self.warnings.append(str(mlog.red('ERROR')) + ': Unknown TAP output lines for a supported TAP version.\n'
1191 'This is probably a bug in the test; if they are not TAP syntax, prefix them with a #')
1192 if all(t.result is TestResult.SKIP for t in self.results):
1193 # This includes the case where self.results is empty
1194 if res != TestResult.ERROR:
1195 res = TestResult.SKIP
1196
1197 if res and self.res == TestResult.RUNNING:
1198 self.res = res
1199
1200 TestRun.PROTOCOL_TO_CLASS[TestProtocol.TAP] = TestRunTAP
1201
1202
1203 class TestRunRust(TestRun):
1204 @property
1205 def needs_parsing(self) -> bool:
1206 return True
1207
1208 async def parse(self, harness: 'TestHarness', lines: T.AsyncIterator[str]) -> None:
1209 def parse_res(n: int, name: str, result: str) -> TAPParser.Test:
1210 if result == 'ok':
1211 return TAPParser.Test(n, name, TestResult.OK, None)
1212 elif result.startswith('ignored'):
1213 return TAPParser.Test(n, name, TestResult.SKIP, None)
1214 elif result == 'FAILED':
1215 return TAPParser.Test(n, name, TestResult.FAIL, None)
1216 return TAPParser.Test(n, name, TestResult.ERROR,
1217 f'Unsupported output from rust test: {result}')
1218
1219 n = 1
1220 async for line in lines:
1221 match = RUST_TEST_RE.match(line)
1222 if match:
1223 name, result = match.groups()
1224 doctest = RUST_DOCTEST_RE.match(name)
1225 if doctest:
1226 name = ':'.join((x.rstrip() for x in doctest.groups() if x))
1227 else:
1228 name = name.rstrip()
1229 name = name.replace('::', '.')
1230 t = parse_res(n, name, result)
1231 self.results.append(t)
1232 harness.log_subtest(self, name, t.result, None)
1233 n += 1
1234
1235 res = None
1236
1237 if all(t.result is TestResult.SKIP for t in self.results):
1238 # This includes the case where self.results is empty
1239 res = TestResult.SKIP
1240 elif any(t.result is TestResult.ERROR for t in self.results):
1241 res = TestResult.ERROR
1242 elif any(t.result is TestResult.FAIL for t in self.results):
1243 res = TestResult.FAIL
1244
1245 if res and self.res == TestResult.RUNNING:
1246 self.res = res
1247
1248 TestRun.PROTOCOL_TO_CLASS[TestProtocol.RUST] = TestRunRust
1249
1250 # Check unencodable characters in xml output and replace them with
1251 # their printable representation
1252 def replace_unencodable_xml_chars(original_str: str) -> str:
1253 # [1:-1] is needed for removing `'` characters from both start and end
1254 # of the string
1255 replacement_lambda = lambda illegal_chr: repr(illegal_chr.group())[1:-1]
1256 return UNENCODABLE_XML_CHRS_RE.sub(replacement_lambda, original_str)
1257
1258 def decode(stream: T.Union[None, bytes]) -> str:
1259 if stream is None:
1260 return ''
1261 try:
1262 return stream.decode('utf-8')
1263 except UnicodeDecodeError:
1264 return stream.decode('iso-8859-1', errors='ignore')
1265
1266 async def read_decode(reader: asyncio.StreamReader,
1267 queue: T.Optional['asyncio.Queue[T.Optional[str]]'],
1268 console_mode: ConsoleUser) -> str:
1269 stdo_lines = []
1270 try:
1271 while not reader.at_eof():
1272 # Prefer splitting by line, as that produces nicer output
1273 try:
1274 line_bytes = await reader.readuntil(b'\n')
1275 except asyncio.IncompleteReadError as e:
1276 line_bytes = e.partial
1277 except asyncio.LimitOverrunError as e:
1278 line_bytes = await reader.readexactly(e.consumed)
1279 if line_bytes:
1280 line = decode(line_bytes).replace('\r\n', '\n')
1281 stdo_lines.append(line)
1282 if console_mode is ConsoleUser.STDOUT:
1283 print(line, end='', flush=True)
1284 if queue:
1285 await queue.put(line)
1286 return ''.join(stdo_lines)
1287 except asyncio.CancelledError:
1288 return ''.join(stdo_lines)
1289 finally:
1290 if queue:
1291 await queue.put(None)
1292
1293 def run_with_mono(fname: str) -> bool:
1294 return fname.endswith('.exe') and not (is_windows() or is_cygwin() or is_os2())
1295
1296 def check_testdata(objs: T.List[TestSerialisation]) -> T.List[TestSerialisation]:
1297 if not isinstance(objs, list):
1298 raise MesonVersionMismatchException('<unknown>', coredata_version)
1299 for obj in objs:
1300 if not isinstance(obj, TestSerialisation):
1301 raise MesonVersionMismatchException('<unknown>', coredata_version)
1302 if not hasattr(obj, 'version'):
1303 raise MesonVersionMismatchException('<unknown>', coredata_version)
1304 if major_versions_differ(obj.version, coredata_version):
1305 raise MesonVersionMismatchException(obj.version, coredata_version)
1306 return objs
1307
1308 # Custom waiting primitives for asyncio
1309
1310 async def queue_iter(q: 'asyncio.Queue[T.Optional[str]]') -> T.AsyncIterator[str]:
1311 while True:
1312 item = await q.get()
1313 q.task_done()
1314 if item is None:
1315 break
1316 yield item
1317
1318 async def complete(future: asyncio.Future) -> None:
1319 """Wait for completion of the given future, ignoring cancellation."""
1320 try:
1321 await future
1322 except asyncio.CancelledError:
1323 pass
1324
1325 async def complete_all(futures: T.Iterable[asyncio.Future],
1326 timeout: T.Optional[T.Union[int, float]] = None) -> None:
1327 """Wait for completion of all the given futures, ignoring cancellation.
1328 If timeout is not None, raise an asyncio.TimeoutError after the given
1329 time has passed. asyncio.TimeoutError is only raised if some futures
1330 have not completed and none have raised exceptions, even if timeout
1331 is zero."""
1332
1333 def check_futures(futures: T.Iterable[asyncio.Future]) -> None:
1334 # Raise exceptions if needed
1335 left = False
1336 for f in futures:
1337 if not f.done():
1338 left = True
1339 elif not f.cancelled():
1340 f.result()
1341 if left:
1342 raise asyncio.TimeoutError
1343
1344 # Python is silly and does not have a variant of asyncio.wait with an
1345 # absolute time as deadline.
1346 loop = asyncio.get_running_loop()
1347 deadline = None if timeout is None else loop.time() + timeout
1348 while futures and (timeout is None or timeout > 0):
1349 done, futures = await asyncio.wait(futures, timeout=timeout,
1350 return_when=asyncio.FIRST_EXCEPTION)
1351 check_futures(done)
1352 if deadline:
1353 timeout = deadline - loop.time()
1354
1355 check_futures(futures)
1356
1357
1358 class TestSubprocess:
1359 def __init__(self, p: asyncio.subprocess.Process,
1360 stdout: T.Optional[int], stderr: T.Optional[int],
1361 postwait_fn: T.Callable[[], None] = None):
1362 self._process = p
1363 self.stdout = stdout
1364 self.stderr = stderr
1365 self.stdo_task: T.Optional[asyncio.Task[None]] = None
1366 self.stde_task: T.Optional[asyncio.Task[None]] = None
1367 self.postwait_fn = postwait_fn
1368 self.all_futures: T.List[asyncio.Future] = []
1369 self.queue: T.Optional[asyncio.Queue[T.Optional[str]]] = None
1370
1371 def stdout_lines(self) -> T.AsyncIterator[str]:
1372 self.queue = asyncio.Queue()
1373 return queue_iter(self.queue)
1374
1375 def communicate(self,
1376 test: 'TestRun',
1377 console_mode: ConsoleUser) -> T.Tuple[T.Optional[T.Awaitable[str]],
1378 T.Optional[T.Awaitable[str]]]:
1379 async def collect_stdo(test: 'TestRun',
1380 reader: asyncio.StreamReader,
1381 console_mode: ConsoleUser) -> None:
1382 test.stdo = await read_decode(reader, self.queue, console_mode)
1383
1384 async def collect_stde(test: 'TestRun',
1385 reader: asyncio.StreamReader,
1386 console_mode: ConsoleUser) -> None:
1387 test.stde = await read_decode(reader, None, console_mode)
1388
1389 # asyncio.ensure_future ensures that printing can
1390 # run in the background, even before it is awaited
1391 if self.stdo_task is None and self.stdout is not None:
1392 decode_coro = collect_stdo(test, self._process.stdout, console_mode)
1393 self.stdo_task = asyncio.ensure_future(decode_coro)
1394 self.all_futures.append(self.stdo_task)
1395 if self.stderr is not None and self.stderr != asyncio.subprocess.STDOUT:
1396 decode_coro = collect_stde(test, self._process.stderr, console_mode)
1397 self.stde_task = asyncio.ensure_future(decode_coro)
1398 self.all_futures.append(self.stde_task)
1399
1400 return self.stdo_task, self.stde_task
1401
1402 async def _kill(self) -> T.Optional[str]:
1403 # Python does not provide multiplatform support for
1404 # killing a process and all its children so we need
1405 # to roll our own.
1406 p = self._process
1407 try:
1408 if is_windows():
1409 subprocess.run(['taskkill', '/F', '/T', '/PID', str(p.pid)])
1410 else:
1411 # Send a termination signal to the process group that setsid()
1412 # created - giving it a chance to perform any cleanup.
1413 os.killpg(p.pid, signal.SIGTERM)
1414
1415 # Make sure the termination signal actually kills the process
1416 # group, otherwise retry with a SIGKILL.
1417 with suppress(asyncio.TimeoutError):
1418 await asyncio.wait_for(p.wait(), timeout=0.5)
1419 if p.returncode is not None:
1420 return None
1421
1422 os.killpg(p.pid, signal.SIGKILL)
1423
1424 with suppress(asyncio.TimeoutError):
1425 await asyncio.wait_for(p.wait(), timeout=1)
1426 if p.returncode is not None:
1427 return None
1428
1429 # An earlier kill attempt has not worked for whatever reason.
1430 # Try to kill it one last time with a direct call.
1431 # If the process has spawned children, they will remain around.
1432 p.kill()
1433 with suppress(asyncio.TimeoutError):
1434 await asyncio.wait_for(p.wait(), timeout=1)
1435 if p.returncode is not None:
1436 return None
1437 return 'Test process could not be killed.'
1438 except ProcessLookupError:
1439 # Sometimes (e.g. with Wine) this happens. There's nothing
1440 # we can do, probably the process already died so just wait
1441 # for the event loop to pick that up.
1442 await p.wait()
1443 return None
1444 finally:
1445 if self.stdo_task:
1446 self.stdo_task.cancel()
1447 if self.stde_task:
1448 self.stde_task.cancel()
1449
1450 async def wait(self, test: 'TestRun') -> None:
1451 p = self._process
1452
1453 self.all_futures.append(asyncio.ensure_future(p.wait()))
1454 try:
1455 await complete_all(self.all_futures, timeout=test.timeout)
1456 except asyncio.TimeoutError:
1457 test.additional_error += await self._kill() or ''
1458 test.res = TestResult.TIMEOUT
1459 except asyncio.CancelledError:
1460 # The main loop must have seen Ctrl-C.
1461 test.additional_error += await self._kill() or ''
1462 test.res = TestResult.INTERRUPT
1463 finally:
1464 if self.postwait_fn:
1465 self.postwait_fn()
1466
1467 test.returncode = p.returncode or 0
1468
1469 class SingleTestRunner:
1470
1471 def __init__(self, test: TestSerialisation, env: T.Dict[str, str], name: str,
1472 options: argparse.Namespace):
1473 self.test = test
1474 self.options = options
1475 self.cmd = self._get_cmd()
1476
1477 if self.cmd and self.test.extra_paths:
1478 env['PATH'] = os.pathsep.join(self.test.extra_paths + ['']) + env['PATH']
1479 winecmd = []
1480 for c in self.cmd:
1481 winecmd.append(c)
1482 if os.path.basename(c).startswith('wine'):
1483 env['WINEPATH'] = get_wine_shortpath(
1484 winecmd,
1485 ['Z:' + p for p in self.test.extra_paths] + env.get('WINEPATH', '').split(';'),
1486 self.test.workdir
1487 )
1488 break
1489
1490 # If MALLOC_PERTURB_ is not set, or if it is set to an empty value,
1491 # (i.e., the test or the environment don't explicitly set it), set
1492 # it ourselves. We do this unconditionally for regular tests
1493 # because it is extremely useful to have.
1494 # Setting MALLOC_PERTURB_="0" will completely disable this feature.
1495 if ('MALLOC_PERTURB_' not in env or not env['MALLOC_PERTURB_']) and not options.benchmark:
1496 env['MALLOC_PERTURB_'] = str(random.randint(1, 255))
1497
1498 # Sanitizers do not default to aborting on error. This is counter to
1499 # expectations when using -Db_sanitize and has led to confusion in the wild
1500 # in CI. Set our own values of {ASAN,UBSAN}_OPTIONS to rectify this, but
1501 # only if the user has not defined them.
1502 if ('ASAN_OPTIONS' not in env or not env['ASAN_OPTIONS']):
1503 env['ASAN_OPTIONS'] = 'halt_on_error=1:abort_on_error=1:print_summary=1'
1504 if ('UBSAN_OPTIONS' not in env or not env['UBSAN_OPTIONS']):
1505 env['UBSAN_OPTIONS'] = 'halt_on_error=1:abort_on_error=1:print_summary=1:print_stacktrace=1'
1506 if ('MSAN_OPTIONS' not in env or not env['MSAN_OPTIONS']):
1507 env['MSAN_OPTIONS'] = 'halt_on_error=1:abort_on_error=1:print_summary=1:print_stacktrace=1'
1508
1509 # Valgrind also doesn't reflect errors in its exit code by default.
1510 if 'VALGRIND_OPTS' not in env or not env['VALGRIND_OPTS']:
1511 try:
1512 wrapper_name = TestHarness.get_wrapper(self.options)[0]
1513 if 'valgrind' in wrapper_name:
1514 env['VALGRIND_OPTS'] = '--error-exitcode=1'
1515 except IndexError:
1516 pass
1517
1518 if self.options.interactive or self.test.timeout is None or self.test.timeout <= 0:
1519 timeout = None
1520 elif self.options.timeout_multiplier is None:
1521 timeout = self.test.timeout
1522 elif self.options.timeout_multiplier <= 0:
1523 timeout = None
1524 else:
1525 timeout = self.test.timeout * self.options.timeout_multiplier
1526
1527 is_parallel = test.is_parallel and self.options.num_processes > 1 and not self.options.interactive
1528 verbose = (test.verbose or self.options.verbose) and not self.options.quiet
1529 self.runobj = TestRun(test, env, name, timeout, is_parallel, verbose, self.options.interactive)
1530
1531 @property
1532 def console_mode(self) -> ConsoleUser:
1533 return self.runobj.console_mode
1534
1535 def _get_test_cmd(self) -> T.Optional[T.List[str]]:
1536 testentry = self.test.fname[0]
1537 if self.options.no_rebuild and self.test.cmd_is_built and not os.path.isfile(testentry):
1538 raise TestException(f'The test program {testentry!r} does not exist. Cannot run tests before building them.')
1539 if testentry.endswith('.jar'):
1540 return ['java', '-jar'] + self.test.fname
1541 elif not self.test.is_cross_built and run_with_mono(testentry):
1542 return ['mono'] + self.test.fname
1543 elif self.test.cmd_is_exe and self.test.is_cross_built and self.test.needs_exe_wrapper:
1544 if self.test.exe_wrapper is None:
1545 # Can not run test on cross compiled executable
1546 # because there is no execute wrapper.
1547 return None
1548 elif self.test.cmd_is_exe:
1549 # If the command is not built (ie, its a python script),
1550 # then we don't check for the exe-wrapper
1551 if not self.test.exe_wrapper.found():
1552 msg = ('The exe_wrapper defined in the cross file {!r} was not '
1553 'found. Please check the command and/or add it to PATH.')
1554 raise TestException(msg.format(self.test.exe_wrapper.name))
1555 return self.test.exe_wrapper.get_command() + self.test.fname
1556 elif self.test.cmd_is_built and not self.test.cmd_is_exe and is_windows():
1557 test_cmd = ExternalProgram._shebang_to_cmd(self.test.fname[0])
1558 if test_cmd is not None:
1559 test_cmd += self.test.fname[1:]
1560 return test_cmd
1561 return self.test.fname
1562
1563 def _get_cmd(self) -> T.Optional[T.List[str]]:
1564 test_cmd = self._get_test_cmd()
1565 if not test_cmd:
1566 return None
1567 return TestHarness.get_wrapper(self.options) + test_cmd
1568
1569 @property
1570 def is_parallel(self) -> bool:
1571 return self.runobj.is_parallel
1572
1573 @property
1574 def visible_name(self) -> str:
1575 return self.runobj.name
1576
1577 @property
1578 def timeout(self) -> T.Optional[int]:
1579 return self.runobj.timeout
1580
1581 async def run(self, harness: 'TestHarness') -> TestRun:
1582 if self.cmd is None:
1583 self.stdo = 'Not run because cannot execute cross compiled binaries.'
1584 harness.log_start_test(self.runobj)
1585 self.runobj.complete_skip()
1586 else:
1587 cmd = self.cmd + self.test.cmd_args + self.options.test_args
1588 self.runobj.start(cmd)
1589 harness.log_start_test(self.runobj)
1590 await self._run_cmd(harness, cmd)
1591 return self.runobj
1592
1593 async def _run_subprocess(self, args: T.List[str], *, stdin: T.Optional[int],
1594 stdout: T.Optional[int], stderr: T.Optional[int],
1595 env: T.Dict[str, str], cwd: T.Optional[str]) -> TestSubprocess:
1596 # Let gdb handle ^C instead of us
1597 if self.options.interactive:
1598 previous_sigint_handler = signal.getsignal(signal.SIGINT)
1599 # Make the meson executable ignore SIGINT while gdb is running.
1600 signal.signal(signal.SIGINT, signal.SIG_IGN)
1601
1602 def preexec_fn() -> None:
1603 if self.options.interactive:
1604 # Restore the SIGINT handler for the child process to
1605 # ensure it can handle it.
1606 signal.signal(signal.SIGINT, signal.SIG_DFL)
1607 else:
1608 # We don't want setsid() in gdb because gdb needs the
1609 # terminal in order to handle ^C and not show tcsetpgrp()
1610 # errors avoid not being able to use the terminal.
1611 os.setsid()
1612
1613 def postwait_fn() -> None:
1614 if self.options.interactive:
1615 # Let us accept ^C again
1616 signal.signal(signal.SIGINT, previous_sigint_handler)
1617
1618 p = await asyncio.create_subprocess_exec(*args,
1619 stdin=stdin,
1620 stdout=stdout,
1621 stderr=stderr,
1622 env=env,
1623 cwd=cwd,
1624 preexec_fn=preexec_fn if not (is_windows() or is_os2()) else None)
1625 return TestSubprocess(p, stdout=stdout, stderr=stderr,
1626 postwait_fn=postwait_fn if not is_windows() else None)
1627
1628 async def _run_cmd(self, harness: 'TestHarness', cmd: T.List[str]) -> None:
1629 if self.console_mode is ConsoleUser.INTERACTIVE:
1630 stdin = None
1631 stdout = None
1632 stderr = None
1633 else:
1634 stdin = asyncio.subprocess.DEVNULL
1635 stdout = asyncio.subprocess.PIPE
1636 stderr = asyncio.subprocess.STDOUT \
1637 if not self.options.split and not self.runobj.needs_parsing \
1638 else asyncio.subprocess.PIPE
1639
1640 extra_cmd: T.List[str] = []
1641 if self.test.protocol is TestProtocol.GTEST:
1642 gtestname = self.test.name
1643 if self.test.workdir:
1644 gtestname = os.path.join(self.test.workdir, self.test.name)
1645 extra_cmd.append(f'--gtest_output=xml:{gtestname}.xml')
1646
1647 p = await self._run_subprocess(cmd + extra_cmd,
1648 stdin=stdin,
1649 stdout=stdout,
1650 stderr=stderr,
1651 env=self.runobj.env,
1652 cwd=self.test.workdir)
1653
1654 if self.runobj.needs_parsing and self.console_mode is not ConsoleUser.INTERACTIVE:
1655 parse_coro = self.runobj.parse(harness, p.stdout_lines())
1656 parse_task = asyncio.ensure_future(parse_coro)
1657 else:
1658 parse_task = None
1659
1660 stdo_task, stde_task = p.communicate(self.runobj, self.console_mode)
1661 await p.wait(self.runobj)
1662
1663 if parse_task:
1664 await parse_task
1665 if stdo_task:
1666 await stdo_task
1667 if stde_task:
1668 await stde_task
1669
1670 self.runobj.complete()
1671
1672
1673 class TestHarness:
1674 def __init__(self, options: argparse.Namespace):
1675 self.options = options
1676 self.collected_failures: T.List[TestRun] = []
1677 self.maxfail_reached = False
1678 self.fail_count = 0
1679 self.expectedfail_count = 0
1680 self.unexpectedpass_count = 0
1681 self.success_count = 0
1682 self.skip_count = 0
1683 self.ignored_count = 0
1684 self.timeout_count = 0
1685 self.test_count = 0
1686 self.name_max_len = 0
1687 self.is_run = False
1688 self.loggers: T.List[TestLogger] = []
1689 self.console_logger = ConsoleLogger(options.max_lines)
1690 self.loggers.append(self.console_logger)
1691 self.need_console = False
1692 self.ninja: T.List[str] = None
1693
1694 self.logfile_base: T.Optional[str] = None
1695 if self.options.logbase and not self.options.interactive:
1696 namebase = None
1697 self.logfile_base = os.path.join(self.options.wd, 'meson-logs', self.options.logbase)
1698
1699 if self.options.wrapper:
1700 namebase = os.path.basename(self.get_wrapper(self.options)[0])
1701 elif self.options.setup:
1702 namebase = self.options.setup.replace(":", "_")
1703
1704 if namebase:
1705 self.logfile_base += '-' + namebase.replace(' ', '_')
1706
1707 self.prepare_build()
1708 self.load_metadata()
1709
1710 ss = set()
1711 for t in self.tests:
1712 for s in t.suite:
1713 ss.add(s)
1714 self.suites = list(ss)
1715
1716 def get_console_logger(self) -> 'ConsoleLogger':
1717 assert self.console_logger
1718 return self.console_logger
1719
1720 def prepare_build(self) -> None:
1721 if self.options.no_rebuild:
1722 return
1723
1724 self.ninja = tooldetect.detect_ninja()
1725 if not self.ninja:
1726 print("Can't find ninja, can't rebuild test.")
1727 # If ninja can't be found return exit code 127, indicating command
1728 # not found for shell, which seems appropriate here. This works
1729 # nicely for `git bisect run`, telling it to abort - no point in
1730 # continuing if there's no ninja.
1731 sys.exit(127)
1732
1733 def load_metadata(self) -> None:
1734 startdir = os.getcwd()
1735 try:
1736 os.chdir(self.options.wd)
1737
1738 # Before loading build / test data, make sure that the build
1739 # configuration does not need to be regenerated. This needs to
1740 # happen before rebuild_deps(), because we need the correct list of
1741 # tests and their dependencies to compute
1742 if not self.options.no_rebuild:
1743 teststdo = subprocess.run(self.ninja + ['-n', 'build.ninja'], capture_output=True).stdout
1744 if b'ninja: no work to do.' not in teststdo and b'samu: nothing to do' not in teststdo:
1745 stdo = sys.stderr if self.options.list else sys.stdout
1746 ret = subprocess.run(self.ninja + ['build.ninja'], stdout=stdo.fileno())
1747 if ret.returncode != 0:
1748 raise TestException(f'Could not configure {self.options.wd!r}')
1749
1750 self.build_data = build.load(os.getcwd())
1751 if not self.options.setup:
1752 self.options.setup = self.build_data.test_setup_default_name
1753 if self.options.benchmark:
1754 self.tests = self.load_tests('meson_benchmark_setup.dat')
1755 else:
1756 self.tests = self.load_tests('meson_test_setup.dat')
1757 finally:
1758 os.chdir(startdir)
1759
1760 def load_tests(self, file_name: str) -> T.List[TestSerialisation]:
1761 datafile = Path('meson-private') / file_name
1762 if not datafile.is_file():
1763 raise TestException(f'Directory {self.options.wd!r} does not seem to be a Meson build directory.')
1764 with datafile.open('rb') as f:
1765 objs = check_testdata(pickle.load(f))
1766 return objs
1767
1768 def __enter__(self) -> 'TestHarness':
1769 return self
1770
1771 def __exit__(self, exc_type: T.Any, exc_value: T.Any, traceback: T.Any) -> None:
1772 self.close_logfiles()
1773
1774 def close_logfiles(self) -> None:
1775 for l in self.loggers:
1776 l.close()
1777 self.console_logger = None
1778
1779 def get_test_setup(self, test: T.Optional[TestSerialisation]) -> build.TestSetup:
1780 if ':' in self.options.setup:
1781 if self.options.setup not in self.build_data.test_setups:
1782 sys.exit(f"Unknown test setup '{self.options.setup}'.")
1783 return self.build_data.test_setups[self.options.setup]
1784 else:
1785 full_name = test.project_name + ":" + self.options.setup
1786 if full_name not in self.build_data.test_setups:
1787 sys.exit(f"Test setup '{self.options.setup}' not found from project '{test.project_name}'.")
1788 return self.build_data.test_setups[full_name]
1789
1790 def merge_setup_options(self, options: argparse.Namespace, test: TestSerialisation) -> T.Dict[str, str]:
1791 current = self.get_test_setup(test)
1792 if not options.gdb:
1793 options.gdb = current.gdb
1794 if options.gdb:
1795 options.interactive = True
1796 options.verbose = True
1797 if options.timeout_multiplier is None:
1798 options.timeout_multiplier = current.timeout_multiplier
1799 # if options.env is None:
1800 # options.env = current.env # FIXME, should probably merge options here.
1801 if options.wrapper is None:
1802 options.wrapper = current.exe_wrapper
1803 elif current.exe_wrapper:
1804 sys.exit('Conflict: both test setup and command line specify an exe wrapper.')
1805 return current.env.get_env(os.environ.copy())
1806
1807 def get_test_runner(self, test: TestSerialisation, iteration: int) -> SingleTestRunner:
1808 name = self.get_pretty_suite(test)
1809 options = deepcopy(self.options)
1810 if self.options.setup:
1811 env = self.merge_setup_options(options, test)
1812 else:
1813 env = os.environ.copy()
1814 test_env = test.env.get_env(env)
1815 env.update(test_env)
1816 if (test.is_cross_built and test.needs_exe_wrapper and
1817 test.exe_wrapper and test.exe_wrapper.found()):
1818 env['MESON_EXE_WRAPPER'] = join_args(test.exe_wrapper.get_command())
1819 env['MESON_TEST_ITERATION'] = str(iteration + 1)
1820 return SingleTestRunner(test, env, name, options)
1821
1822 def process_test_result(self, result: TestRun) -> None:
1823 if result.res is TestResult.TIMEOUT:
1824 self.timeout_count += 1
1825 elif result.res is TestResult.SKIP:
1826 self.skip_count += 1
1827 elif result.res is TestResult.IGNORED:
1828 self.ignored_count += 1
1829 elif result.res is TestResult.OK:
1830 self.success_count += 1
1831 elif result.res in {TestResult.FAIL, TestResult.ERROR, TestResult.INTERRUPT}:
1832 self.fail_count += 1
1833 elif result.res is TestResult.EXPECTEDFAIL:
1834 self.expectedfail_count += 1
1835 elif result.res is TestResult.UNEXPECTEDPASS:
1836 self.unexpectedpass_count += 1
1837 else:
1838 sys.exit(f'Unknown test result encountered: {result.res}')
1839
1840 if self.is_bad_result(result):
1841 self.collected_failures.append(result)
1842 for l in self.loggers:
1843 l.log(self, result)
1844
1845 def is_bad_result(self, result: TestRun) -> bool:
1846 return result.res.is_bad() and not (result.res is TestResult.INTERRUPT and self.maxfail_reached)
1847
1848 @property
1849 def numlen(self) -> int:
1850 return len(str(self.test_count))
1851
1852 @property
1853 def max_left_width(self) -> int:
1854 return 2 * self.numlen + 2
1855
1856 def get_test_num_prefix(self, num: int) -> str:
1857 return '{num:{numlen}}/{testcount} '.format(numlen=self.numlen,
1858 num=num,
1859 testcount=self.test_count)
1860
1861 def format(self, result: TestRun, colorize: bool,
1862 max_left_width: int = 0,
1863 prefix: str = '',
1864 left: T.Optional[str] = None,
1865 middle: T.Optional[str] = None,
1866 right: T.Optional[str] = None) -> str:
1867 if left is None:
1868 left = self.get_test_num_prefix(result.num)
1869
1870 # A non-default max_left_width lets the logger print more stuff before the
1871 # name, while ensuring that the rightmost columns remain aligned.
1872 max_left_width = max(max_left_width, self.max_left_width)
1873
1874 if middle is None:
1875 middle = result.name
1876 extra_mid_width = max_left_width + self.name_max_len + 1 - uniwidth(middle) - uniwidth(left) - uniwidth(prefix)
1877 middle += ' ' * max(1, extra_mid_width)
1878
1879 if right is None:
1880 right = '{res} {dur:{durlen}.2f}s'.format(
1881 res=result.res.get_text(colorize),
1882 dur=result.duration,
1883 durlen=self.duration_max_len + 3)
1884 details = result.get_details()
1885 if details:
1886 right += ' ' + details
1887 return prefix + left + middle + right
1888
1889 def summary(self) -> str:
1890 results = {
1891 'Ok: ': self.success_count,
1892 'Expected Fail: ': self.expectedfail_count,
1893 'Fail: ': self.fail_count,
1894 'Unexpected Pass: ': self.unexpectedpass_count,
1895 'Skipped: ': self.skip_count,
1896 'Ignored: ': self.ignored_count,
1897 'Timeout: ': self.timeout_count,
1898 }
1899
1900 summary = []
1901 for result, count in results.items():
1902 if count > 0 or result.startswith('Ok:') or result.startswith('Fail:'):
1903 summary.append(result + '{:<4}'.format(count))
1904
1905 return '\n{}\n'.format('\n'.join(summary))
1906
1907 def total_failure_count(self) -> int:
1908 return self.fail_count + self.unexpectedpass_count + self.timeout_count
1909
1910 def doit(self) -> int:
1911 if self.is_run:
1912 raise RuntimeError('Test harness object can only be used once.')
1913 self.is_run = True
1914 tests = self.get_tests()
1915 # NOTE: If all tests are selected anyway, we pass
1916 # an empty list to `rebuild_deps`, which then will execute
1917 # the "meson-test-prereq" ninja target as a fallback.
1918 # This prevents situations, where ARG_MAX may overflow
1919 # if there are many targets.
1920 rebuild_only_tests = tests if tests != self.tests else []
1921 if not tests:
1922 return 0
1923 if not self.options.no_rebuild and not rebuild_deps(self.ninja, self.options.wd, rebuild_only_tests, self.options.benchmark):
1924 # We return 125 here in case the build failed.
1925 # The reason is that exit code 125 tells `git bisect run` that the current
1926 # commit should be skipped. Thus users can directly use `meson test` to
1927 # bisect without needing to handle the does-not-build case separately in a
1928 # wrapper script.
1929 sys.exit(125)
1930
1931 self.name_max_len = max(uniwidth(self.get_pretty_suite(test)) for test in tests)
1932 self.options.num_processes = min(self.options.num_processes,
1933 len(tests) * self.options.repeat)
1934 startdir = os.getcwd()
1935 try:
1936 os.chdir(self.options.wd)
1937 runners: T.List[SingleTestRunner] = []
1938 for i in range(self.options.repeat):
1939 runners.extend(self.get_test_runner(test, i) for test in tests)
1940 if i == 0:
1941 self.duration_max_len = max(len(str(int(runner.timeout or 99)))
1942 for runner in runners)
1943 # Disable the progress report if it gets in the way
1944 self.need_console = any(runner.console_mode is not ConsoleUser.LOGGER
1945 for runner in runners)
1946
1947 self.test_count = len(runners)
1948 self.run_tests(runners)
1949 finally:
1950 os.chdir(startdir)
1951 return 1 if self.total_failure_count() > 0 else 0
1952
1953 @staticmethod
1954 def split_suite_string(suite: str) -> T.Tuple[str, str]:
1955 if ':' in suite:
1956 split = suite.split(':', 1)
1957 assert len(split) == 2
1958 return split[0], split[1]
1959 else:
1960 return suite, ""
1961
1962 @staticmethod
1963 def test_in_suites(test: TestSerialisation, suites: T.List[str]) -> bool:
1964 for suite in suites:
1965 (prj_match, st_match) = TestHarness.split_suite_string(suite)
1966 for prjst in test.suite:
1967 (prj, st) = TestHarness.split_suite_string(prjst)
1968
1969 # The SUITE can be passed as
1970 # - `name` - We select tests belonging to (sub)project OR suite
1971 # with the given name.
1972 # - `:suite_name` - We select tests belonging to any (sub)projects
1973 # and in suite_name.
1974 # - `project_name:suite_name` - We select tests belonging
1975 # to project_name and in suite_name.
1976 if not st_match:
1977 if prj_match in {prj, st}:
1978 return True
1979 elif not prj_match:
1980 if st == st_match:
1981 return True
1982 else:
1983 if prj == prj_match and st == st_match:
1984 return True
1985 return False
1986
1987 def test_suitable(self, test: TestSerialisation, excluded_tests: set[str]) -> bool:
1988 if TestHarness.test_in_suites(test, self.options.exclude_suites):
1989 return False
1990
1991 # Accept both --exclude name and --exclude subproject:name.
1992 # For the main project, we also accept 'name' without qualification
1993 # for convenience.
1994 if self.build_data.project_name == test.project_name and test.name in excluded_tests:
1995 return False
1996 if f'{test.project_name}:{test.name}' in excluded_tests:
1997 return False
1998
1999 if self.options.include_suites:
2000 # Both force inclusion (overriding add_test_setup) and exclude
2001 # everything else
2002 return TestHarness.test_in_suites(test, self.options.include_suites)
2003
2004 if self.options.setup:
2005 setup = self.get_test_setup(test)
2006 if TestHarness.test_in_suites(test, setup.exclude_suites):
2007 return False
2008
2009 return True
2010
2011 def tests_from_args(self, tests: T.List[TestSerialisation]) -> T.Generator[TestSerialisation, None, None]:
2012 '''
2013 Allow specifying test names like "meson test foo1 foo2", where test('foo1', ...)
2014
2015 Also support specifying the subproject to run tests from like
2016 "meson test subproj:" (all tests inside subproj) or "meson test subproj:foo1"
2017 to run foo1 inside subproj. Coincidentally also "meson test :foo1" to
2018 run all tests with that name across all subprojects, which is
2019 identical to "meson test foo1"
2020 '''
2021 patterns: T.Dict[T.Tuple[str, str], bool] = {}
2022 for arg in self.options.args:
2023 # Replace empty components by wildcards:
2024 # '' -> '*:*'
2025 # 'name' -> '*:name'
2026 # ':name' -> '*:name'
2027 # 'proj:' -> 'proj:*'
2028 if ':' in arg:
2029 subproj, name = arg.split(':', maxsplit=1)
2030 if name == '':
2031 name = '*'
2032 if subproj == '': # in case arg was ':'
2033 subproj = '*'
2034 else:
2035 subproj, name = '*', arg
2036 patterns[(subproj, name)] = False
2037
2038 for t in tests:
2039 # For each test, find the first matching pattern
2040 # and mark it as used. yield the matching tests.
2041 for subproj, name in list(patterns):
2042 if fnmatch(t.project_name, subproj) and fnmatch(t.name, name):
2043 patterns[(subproj, name)] = True
2044 yield t
2045 break
2046
2047 for (subproj, name), was_used in patterns.items():
2048 if not was_used:
2049 # For each unused pattern...
2050 arg = f'{subproj}:{name}'
2051 for t in tests:
2052 # ... if it matches a test, then it wasn't used because another
2053 # pattern matched the same test before.
2054 # Report it as a warning.
2055 if fnmatch(t.project_name, subproj) and fnmatch(t.name, name):
2056 mlog.warning(f'{arg} test name is redundant and was not used')
2057 break
2058 else:
2059 # If the pattern doesn't match any test,
2060 # report it as an error. We don't want the `test` command to
2061 # succeed on an invalid pattern.
2062 raise MesonException(f'{arg} test name does not match any test')
2063
2064 def get_tests(self, errorfile: T.Optional[T.IO] = None) -> T.List[TestSerialisation]:
2065 if not self.tests:
2066 print('No tests defined.', file=errorfile)
2067 return []
2068
2069 excluded_tests = set(self.options.exclude)
2070 tests = [t for t in self.tests if self.test_suitable(t, excluded_tests)]
2071
2072 if self.options.args:
2073 tests = list(self.tests_from_args(tests))
2074 if self.options.slice:
2075 our_slice, nslices = self.options.slice
2076 if nslices > len(tests):
2077 raise MesonException(f'number of slices ({nslices}) exceeds number of tests ({len(tests)})')
2078 tests = tests[our_slice - 1::nslices]
2079
2080 if not tests:
2081 print('No suitable tests defined.', file=errorfile)
2082 return []
2083
2084 return tests
2085
2086 def flush_logfiles(self) -> None:
2087 for l in self.loggers:
2088 l.flush()
2089
2090 def open_logfiles(self) -> None:
2091 if not self.logfile_base:
2092 return
2093
2094 self.loggers.append(JunitBuilder(self.logfile_base + '.junit.xml'))
2095 self.loggers.append(JsonLogfileBuilder(self.logfile_base + '.json'))
2096 self.loggers.append(TextLogfileBuilder(self.logfile_base + '.txt', errors='surrogateescape'))
2097
2098 @staticmethod
2099 def get_wrapper(options: argparse.Namespace) -> T.List[str]:
2100 if options.gdb:
2101 wrap = [options.gdb_path, '--quiet']
2102 if options.repeat > 1:
2103 wrap += ['-ex', 'run', '-ex', 'quit']
2104 # Signal the end of arguments to gdb
2105 wrap += ['--args']
2106 elif options.wrapper:
2107 wrap = options.wrapper
2108 else:
2109 wrap = []
2110 return wrap
2111
2112 def get_pretty_suite(self, test: TestSerialisation) -> str:
2113 assert test.suite, 'Interpreter should ensure there is always at least one suite'
2114 prj = TestHarness.split_suite_string(test.suite[0])[0]
2115 suites: T.List[str] = []
2116 for i in test.suite:
2117 s = TestHarness.split_suite_string(i)[1]
2118 if s:
2119 suites.append(s)
2120 name = f'{prj}:{test.name}'
2121 if suites:
2122 s = '+'.join(suites)
2123 name = f'{s} - {name}'
2124 return name
2125
2126 def run_tests(self, runners: T.List[SingleTestRunner]) -> None:
2127 try:
2128 self.open_logfiles()
2129
2130 # TODO: this is the default for python 3.8
2131 if sys.platform == 'win32' and sys.version_info < (3, 8):
2132 asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
2133
2134 asyncio.run(self._run_tests(runners))
2135 finally:
2136 self.close_logfiles()
2137
2138 def log_subtest(self, test: TestRun, s: str, res: TestResult, explanation: T.Optional[str]) -> None:
2139 for l in self.loggers:
2140 l.log_subtest(self, test, s, res, explanation)
2141
2142 def log_start_test(self, test: TestRun) -> None:
2143 for l in self.loggers:
2144 l.start_test(self, test)
2145
2146 async def _run_tests(self, runners: T.List[SingleTestRunner]) -> None:
2147 semaphore = asyncio.Semaphore(self.options.num_processes)
2148 futures: T.Deque[asyncio.Future] = deque()
2149 running_tests: T.Dict[asyncio.Future, str] = {}
2150 interrupted = False
2151 ctrlc_times: T.Deque[float] = deque(maxlen=MAX_CTRLC)
2152 loop = asyncio.get_running_loop()
2153
2154 async def run_test(test: SingleTestRunner) -> None:
2155 async with semaphore:
2156 if interrupted or (self.options.repeat > 1 and self.fail_count):
2157 return
2158 res = await test.run(self)
2159 self.process_test_result(res)
2160 maxfail = self.options.maxfail
2161 if maxfail and self.fail_count >= maxfail and res.res.is_bad():
2162 self.maxfail_reached = True
2163 cancel_all_tests()
2164
2165 def test_done(f: asyncio.Future) -> None:
2166 if not f.cancelled():
2167 f.result()
2168 futures.remove(f)
2169 try:
2170 del running_tests[f]
2171 except KeyError:
2172 pass
2173
2174 def cancel_one_test(warn: bool) -> None:
2175 future = futures.popleft()
2176 futures.append(future)
2177 if warn:
2178 self.flush_logfiles()
2179 mlog.warning('CTRL-C detected, interrupting {}'.format(running_tests[future]))
2180 del running_tests[future]
2181 future.cancel()
2182
2183 def cancel_all_tests() -> None:
2184 nonlocal interrupted
2185 interrupted = True
2186 while running_tests:
2187 cancel_one_test(False)
2188
2189 def sigterm_handler() -> None:
2190 if interrupted:
2191 return
2192 self.flush_logfiles()
2193 mlog.warning('Received SIGTERM, exiting')
2194 cancel_all_tests()
2195
2196 def sigint_handler() -> None:
2197 # We always pick the longest-running future that has not been cancelled
2198 # If all the tests have been CTRL-C'ed, just stop
2199 nonlocal interrupted
2200 if interrupted:
2201 return
2202 ctrlc_times.append(loop.time())
2203 if len(ctrlc_times) == MAX_CTRLC and ctrlc_times[-1] - ctrlc_times[0] < 1:
2204 self.flush_logfiles()
2205 mlog.warning('CTRL-C detected, exiting')
2206 cancel_all_tests()
2207 elif running_tests:
2208 cancel_one_test(True)
2209 else:
2210 self.flush_logfiles()
2211 mlog.warning('CTRL-C detected, exiting')
2212 interrupted = True
2213
2214 for l in self.loggers:
2215 l.start(self)
2216
2217 if sys.platform != 'win32':
2218 if os.getpgid(0) == os.getpid():
2219 loop.add_signal_handler(signal.SIGINT, sigint_handler)
2220 else:
2221 loop.add_signal_handler(signal.SIGINT, sigterm_handler)
2222 loop.add_signal_handler(signal.SIGTERM, sigterm_handler)
2223 try:
2224 for runner in runners:
2225 if not runner.is_parallel:
2226 await complete_all(futures)
2227 future = asyncio.ensure_future(run_test(runner))
2228 futures.append(future)
2229 running_tests[future] = runner.visible_name
2230 future.add_done_callback(test_done)
2231 if not runner.is_parallel:
2232 await complete(future)
2233 if self.options.repeat > 1 and self.fail_count:
2234 break
2235
2236 await complete_all(futures)
2237 finally:
2238 if sys.platform != 'win32':
2239 loop.remove_signal_handler(signal.SIGINT)
2240 loop.remove_signal_handler(signal.SIGTERM)
2241 for l in self.loggers:
2242 await l.finish(self)
2243
2244 def list_tests(th: TestHarness) -> bool:
2245 tests = th.get_tests(errorfile=sys.stderr)
2246 for t in tests:
2247 print(th.get_pretty_suite(t))
2248 return not tests
2249
2250 def rebuild_deps(ninja: T.List[str], wd: str, tests: T.List[TestSerialisation], benchmark: bool) -> bool:
2251 def convert_path_to_target(path: str) -> str:
2252 path = os.path.relpath(path, wd)
2253 if os.sep != '/':
2254 path = path.replace(os.sep, '/')
2255 return path
2256
2257 assert len(ninja) > 0
2258
2259 targets: T.Set[str] = set()
2260 if tests:
2261 targets_file = os.path.join(wd, 'meson-info/intro-targets.json')
2262 with open(targets_file, encoding='utf-8') as fp:
2263 targets_info = json.load(fp)
2264
2265 depends: T.Set[str] = set()
2266 intro_targets: T.Dict[str, T.List[str]] = {}
2267 for target in targets_info:
2268 intro_targets[target['id']] = [
2269 convert_path_to_target(f)
2270 for f in target['filename']]
2271 for t in tests:
2272 for d in t.depends:
2273 if d in depends:
2274 continue
2275 depends.update(d)
2276 targets.update(intro_targets[d])
2277 else:
2278 if benchmark:
2279 targets.add('meson-benchmark-prereq')
2280 else:
2281 targets.add('meson-test-prereq')
2282
2283 if not targets:
2284 # We want to build minimal deps, but if the subset of targets have no
2285 # deps then ninja falls back to 'all'.
2286 return True
2287
2288 ret = subprocess.run(ninja + ['-C', wd] + sorted(targets)).returncode
2289 if ret != 0:
2290 print(f'Could not rebuild {wd}')
2291 return False
2292
2293 return True
2294
2295 def run(options: argparse.Namespace) -> int:
2296 if options.benchmark or options.interactive:
2297 options.num_processes = 1
2298
2299 if options.verbose and options.quiet:
2300 print('Can not be both quiet and verbose at the same time.')
2301 return 1
2302
2303 check_bin = None
2304 if options.gdb:
2305 options.interactive = True
2306 if options.wrapper:
2307 print('Must not specify both a wrapper and gdb at the same time.')
2308 return 1
2309 check_bin = 'gdb'
2310
2311 if options.interactive:
2312 options.verbose = True
2313
2314 if options.wrapper:
2315 check_bin = options.wrapper[0]
2316
2317 if check_bin is not None:
2318 exe = ExternalProgram(check_bin, silent=True)
2319 if not exe.found():
2320 print(f'Could not find requested program: {check_bin!r}')
2321 return 1
2322
2323 b = build.load(options.wd)
2324 need_vsenv = T.cast('bool', b.environment.coredata.optstore.get_value_for(OptionKey('vsenv')))
2325 setup_vsenv(need_vsenv)
2326
2327 if not options.no_rebuild:
2328 backend = b.environment.coredata.optstore.get_value_for(OptionKey('backend'))
2329 if backend == 'none':
2330 # nothing to build...
2331 options.no_rebuild = True
2332 elif backend != 'ninja':
2333 print('Only ninja backend is supported to rebuild tests before running them.')
2334 # Disable, no point in trying to build anything later
2335 options.no_rebuild = True
2336
2337 with TestHarness(options) as th:
2338 try:
2339 if options.list:
2340 return list_tests(th)
2341 return th.doit()
2342 except TestException as e:
2343 print('Meson test encountered an error:\n')
2344 if os.environ.get('MESON_FORCE_BACKTRACE'):
2345 raise e
2346 else:
2347 print(e)
2348 return 1
2349
2350 def run_with_args(args: T.List[str]) -> int:
2351 parser = argparse.ArgumentParser(prog='meson test')
2352 add_arguments(parser)
2353 options = parser.parse_args(args)
2354 return run(options)