forked from mesonbuild/meson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtest.py
2206 lines (1889 loc) · 87.1 KB
/
mtest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2016-2017 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# A tool to run tests in many different ways.
from __future__ import annotations
from pathlib import Path
from collections import deque
from contextlib import suppress
from copy import deepcopy
from fnmatch import fnmatch
import argparse
import asyncio
import datetime
import enum
import json
import multiprocessing
import os
import pickle
import platform
import random
import re
import signal
import subprocess
import shlex
import sys
import textwrap
import time
import typing as T
import unicodedata
import xml.etree.ElementTree as et
from . import build
from . import environment
from . import mlog
from .coredata import MesonVersionMismatchException, major_versions_differ
from .coredata import version as coredata_version
from .mesonlib import (MesonException, OptionKey, OrderedSet, RealPathAction,
get_wine_shortpath, join_args, split_args, setup_vsenv)
from .mintro import get_infodir, load_info_file
from .programs import ExternalProgram
from .backend.backends import TestProtocol, TestSerialisation
if T.TYPE_CHECKING:
TYPE_TAPResult = T.Union['TAPParser.Test',
'TAPParser.Error',
'TAPParser.Version',
'TAPParser.Plan',
'TAPParser.UnknownLine',
'TAPParser.Bailout']
# GNU autotools interprets a return code of 77 from tests it executes to
# mean that the test should be skipped.
GNU_SKIP_RETURNCODE = 77
# GNU autotools interprets a return code of 99 from tests it executes to
# mean that the test failed even before testing what it is supposed to test.
GNU_ERROR_RETURNCODE = 99
# Exit if 3 Ctrl-C's are received within one second
MAX_CTRLC = 3
# Define unencodable xml characters' regex for replacing them with their
# printable representation
UNENCODABLE_XML_UNICHRS: T.List[T.Tuple[int, int]] = [
(0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F), (0x7F, 0x84),
(0x86, 0x9F), (0xFDD0, 0xFDEF), (0xFFFE, 0xFFFF)]
# Not narrow build
if sys.maxunicode >= 0x10000:
UNENCODABLE_XML_UNICHRS.extend([
(0x1FFFE, 0x1FFFF), (0x2FFFE, 0x2FFFF),
(0x3FFFE, 0x3FFFF), (0x4FFFE, 0x4FFFF),
(0x5FFFE, 0x5FFFF), (0x6FFFE, 0x6FFFF),
(0x7FFFE, 0x7FFFF), (0x8FFFE, 0x8FFFF),
(0x9FFFE, 0x9FFFF), (0xAFFFE, 0xAFFFF),
(0xBFFFE, 0xBFFFF), (0xCFFFE, 0xCFFFF),
(0xDFFFE, 0xDFFFF), (0xEFFFE, 0xEFFFF),
(0xFFFFE, 0xFFFFF), (0x10FFFE, 0x10FFFF)])
UNENCODABLE_XML_CHR_RANGES = [fr'{chr(low)}-{chr(high)}' for (low, high) in UNENCODABLE_XML_UNICHRS]
UNENCODABLE_XML_CHRS_RE = re.compile('([' + ''.join(UNENCODABLE_XML_CHR_RANGES) + '])')
def is_windows() -> bool:
platname = platform.system().lower()
return platname == 'windows'
def is_cygwin() -> bool:
return sys.platform == 'cygwin'
UNIWIDTH_MAPPING = {'F': 2, 'H': 1, 'W': 2, 'Na': 1, 'N': 1, 'A': 1}
def uniwidth(s: str) -> int:
result = 0
for c in s:
w = unicodedata.east_asian_width(c)
result += UNIWIDTH_MAPPING[w]
return result
def determine_worker_count() -> int:
varname = 'MESON_TESTTHREADS'
if varname in os.environ:
try:
num_workers = int(os.environ[varname])
except ValueError:
print(f'Invalid value in {varname}, using 1 thread.')
num_workers = 1
else:
try:
# Fails in some weird environments such as Debian
# reproducible build.
num_workers = multiprocessing.cpu_count()
except Exception:
num_workers = 1
return num_workers
def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument('--maxfail', default=0, type=int,
help='Number of failing tests before aborting the '
'test run. (default: 0, to disable aborting on failure)')
parser.add_argument('--repeat', default=1, dest='repeat', type=int,
help='Number of times to run the tests.')
parser.add_argument('--no-rebuild', default=False, action='store_true',
help='Do not rebuild before running tests.')
parser.add_argument('--gdb', default=False, dest='gdb', action='store_true',
help='Run test under gdb.')
parser.add_argument('--gdb-path', default='gdb', dest='gdb_path',
help='Path to the gdb binary (default: gdb).')
parser.add_argument('--list', default=False, dest='list', action='store_true',
help='List available tests.')
parser.add_argument('--wrapper', default=None, dest='wrapper', type=split_args,
help='wrapper to run tests with (e.g. Valgrind)')
parser.add_argument('-C', dest='wd', action=RealPathAction,
# https://github.com/python/typeshed/issues/3107
# https://github.com/python/mypy/issues/7177
type=os.path.abspath, # type: ignore
help='directory to cd into before running')
parser.add_argument('--suite', default=[], dest='include_suites', action='append', metavar='SUITE',
help='Only run tests belonging to the given suite.')
parser.add_argument('--no-suite', default=[], dest='exclude_suites', action='append', metavar='SUITE',
help='Do not run tests belonging to the given suite.')
parser.add_argument('--no-stdsplit', default=True, dest='split', action='store_false',
help='Do not split stderr and stdout in test logs.')
parser.add_argument('--print-errorlogs', default=False, action='store_true',
help="Whether to print failing tests' logs.")
parser.add_argument('--benchmark', default=False, action='store_true',
help="Run benchmarks instead of tests.")
parser.add_argument('--logbase', default='testlog',
help="Base name for log file.")
parser.add_argument('-j', '--num-processes', default=determine_worker_count(), type=int,
help='How many parallel processes to use.')
parser.add_argument('-v', '--verbose', default=False, action='store_true',
help='Do not redirect stdout and stderr')
parser.add_argument('-q', '--quiet', default=False, action='store_true',
help='Produce less output to the terminal.')
parser.add_argument('-t', '--timeout-multiplier', type=float, default=None,
help='Define a multiplier for test timeout, for example '
' when running tests in particular conditions they might take'
' more time to execute. (<= 0 to disable timeout)')
parser.add_argument('--setup', default=None, dest='setup',
help='Which test setup to use.')
parser.add_argument('--test-args', default=[], type=split_args,
help='Arguments to pass to the specified test(s) or all tests')
parser.add_argument('args', nargs='*',
help='Optional list of test names to run. "testname" to run all tests with that name, '
'"subprojname:testname" to specifically run "testname" from "subprojname", '
'"subprojname:" to run all tests defined by "subprojname".')
def print_safe(s: str) -> None:
end = '' if s[-1] == '\n' else '\n'
try:
print(s, end=end)
except UnicodeEncodeError:
s = s.encode('ascii', errors='backslashreplace').decode('ascii')
print(s, end=end)
def join_lines(a: str, b: str) -> str:
if not a:
return b
if not b:
return a
return a + '\n' + b
def dashes(s: str, dash: str, cols: int) -> str:
if not s:
return dash * cols
s = ' ' + s + ' '
width = uniwidth(s)
first = (cols - width) // 2
s = dash * first + s
return s + dash * (cols - first - width)
def returncode_to_status(retcode: int) -> str:
# Note: We can't use `os.WIFSIGNALED(result.returncode)` and the related
# functions here because the status returned by subprocess is munged. It
# returns a negative value if the process was killed by a signal rather than
# the raw status returned by `wait()`. Also, If a shell sits between Meson
# the actual unit test that shell is likely to convert a termination due
# to a signal into an exit status of 128 plus the signal number.
if retcode < 0:
signum = -retcode
try:
signame = signal.Signals(signum).name
except ValueError:
signame = 'SIGinvalid'
return f'killed by signal {signum} {signame}'
if retcode <= 128:
return f'exit status {retcode}'
signum = retcode - 128
try:
signame = signal.Signals(signum).name
except ValueError:
signame = 'SIGinvalid'
return f'(exit status {retcode} or signal {signum} {signame})'
# TODO for Windows
sh_quote: T.Callable[[str], str] = lambda x: x
if not is_windows():
sh_quote = shlex.quote
def env_tuple_to_str(env: T.Iterable[T.Tuple[str, str]]) -> str:
return ''.join(["{}={} ".format(k, sh_quote(v)) for k, v in env])
class TestException(MesonException):
pass
@enum.unique
class ConsoleUser(enum.Enum):
# the logger can use the console
LOGGER = 0
# the console is used by gdb
GDB = 1
# the console is used to write stdout/stderr
STDOUT = 2
@enum.unique
class TestResult(enum.Enum):
PENDING = 'PENDING'
RUNNING = 'RUNNING'
OK = 'OK'
TIMEOUT = 'TIMEOUT'
INTERRUPT = 'INTERRUPT'
SKIP = 'SKIP'
FAIL = 'FAIL'
EXPECTEDFAIL = 'EXPECTEDFAIL'
UNEXPECTEDPASS = 'UNEXPECTEDPASS'
ERROR = 'ERROR'
@staticmethod
def maxlen() -> int:
return 14 # len(UNEXPECTEDPASS)
def is_ok(self) -> bool:
return self in {TestResult.OK, TestResult.EXPECTEDFAIL}
def is_bad(self) -> bool:
return self in {TestResult.FAIL, TestResult.TIMEOUT, TestResult.INTERRUPT,
TestResult.UNEXPECTEDPASS, TestResult.ERROR}
def is_finished(self) -> bool:
return self not in {TestResult.PENDING, TestResult.RUNNING}
def was_killed(self) -> bool:
return self in (TestResult.TIMEOUT, TestResult.INTERRUPT)
def colorize(self, s: str) -> mlog.AnsiDecorator:
if self.is_bad():
decorator = mlog.red
elif self in (TestResult.SKIP, TestResult.EXPECTEDFAIL):
decorator = mlog.yellow
elif self.is_finished():
decorator = mlog.green
else:
decorator = mlog.blue
return decorator(s)
def get_text(self, colorize: bool) -> str:
result_str = '{res:{reslen}}'.format(res=self.value, reslen=self.maxlen())
return self.colorize(result_str).get_text(colorize)
def get_command_marker(self) -> str:
return str(self.colorize('>>> '))
class TAPParser:
class Plan(T.NamedTuple):
num_tests: int
late: bool
skipped: bool
explanation: T.Optional[str]
class Bailout(T.NamedTuple):
message: str
class Test(T.NamedTuple):
number: int
name: str
result: TestResult
explanation: T.Optional[str]
def __str__(self) -> str:
return f'{self.number} {self.name}'.strip()
class Error(T.NamedTuple):
message: str
class UnknownLine(T.NamedTuple):
message: str
lineno: int
class Version(T.NamedTuple):
version: int
_MAIN = 1
_AFTER_TEST = 2
_YAML = 3
_RE_BAILOUT = re.compile(r'Bail out!\s*(.*)')
_RE_DIRECTIVE = re.compile(r'(?:\s*\#\s*([Ss][Kk][Ii][Pp]\S*|[Tt][Oo][Dd][Oo])\b\s*(.*))?')
_RE_PLAN = re.compile(r'1\.\.([0-9]+)' + _RE_DIRECTIVE.pattern)
_RE_TEST = re.compile(r'((?:not )?ok)\s*(?:([0-9]+)\s*)?([^#]*)' + _RE_DIRECTIVE.pattern)
_RE_VERSION = re.compile(r'TAP version ([0-9]+)')
_RE_YAML_START = re.compile(r'(\s+)---.*')
_RE_YAML_END = re.compile(r'\s+\.\.\.\s*')
found_late_test = False
bailed_out = False
plan: T.Optional[Plan] = None
lineno = 0
num_tests = 0
yaml_lineno: T.Optional[int] = None
yaml_indent = ''
state = _MAIN
version = 12
def parse_test(self, ok: bool, num: int, name: str, directive: T.Optional[str], explanation: T.Optional[str]) -> \
T.Generator[T.Union['TAPParser.Test', 'TAPParser.Error'], None, None]:
name = name.strip()
explanation = explanation.strip() if explanation else None
if directive is not None:
directive = directive.upper()
if directive.startswith('SKIP'):
if ok:
yield self.Test(num, name, TestResult.SKIP, explanation)
return
elif directive == 'TODO':
yield self.Test(num, name, TestResult.UNEXPECTEDPASS if ok else TestResult.EXPECTEDFAIL, explanation)
return
else:
yield self.Error(f'invalid directive "{directive}"')
yield self.Test(num, name, TestResult.OK if ok else TestResult.FAIL, explanation)
async def parse_async(self, lines: T.AsyncIterator[str]) -> T.AsyncIterator[TYPE_TAPResult]:
async for line in lines:
for event in self.parse_line(line):
yield event
for event in self.parse_line(None):
yield event
def parse(self, io: T.Iterator[str]) -> T.Iterator[TYPE_TAPResult]:
for line in io:
yield from self.parse_line(line)
yield from self.parse_line(None)
def parse_line(self, line: T.Optional[str]) -> T.Iterator[TYPE_TAPResult]:
if line is not None:
self.lineno += 1
line = line.rstrip()
# YAML blocks are only accepted after a test
if self.state == self._AFTER_TEST:
if self.version >= 13:
m = self._RE_YAML_START.match(line)
if m:
self.state = self._YAML
self.yaml_lineno = self.lineno
self.yaml_indent = m.group(1)
return
self.state = self._MAIN
elif self.state == self._YAML:
if self._RE_YAML_END.match(line):
self.state = self._MAIN
return
if line.startswith(self.yaml_indent):
return
yield self.Error(f'YAML block not terminated (started on line {self.yaml_lineno})')
self.state = self._MAIN
assert self.state == self._MAIN
if not line or line.startswith('#'):
return
m = self._RE_TEST.match(line)
if m:
if self.plan and self.plan.late and not self.found_late_test:
yield self.Error('unexpected test after late plan')
self.found_late_test = True
self.num_tests += 1
num = self.num_tests if m.group(2) is None else int(m.group(2))
if num != self.num_tests:
yield self.Error('out of order test numbers')
yield from self.parse_test(m.group(1) == 'ok', num,
m.group(3), m.group(4), m.group(5))
self.state = self._AFTER_TEST
return
m = self._RE_PLAN.match(line)
if m:
if self.plan:
yield self.Error('more than one plan found')
else:
num_tests = int(m.group(1))
skipped = num_tests == 0
if m.group(2):
if m.group(2).upper().startswith('SKIP'):
if num_tests > 0:
yield self.Error('invalid SKIP directive for plan')
skipped = True
else:
yield self.Error('invalid directive for plan')
self.plan = self.Plan(num_tests=num_tests, late=(self.num_tests > 0),
skipped=skipped, explanation=m.group(3))
yield self.plan
return
m = self._RE_BAILOUT.match(line)
if m:
yield self.Bailout(m.group(1))
self.bailed_out = True
return
m = self._RE_VERSION.match(line)
if m:
# The TAP version is only accepted as the first line
if self.lineno != 1:
yield self.Error('version number must be on the first line')
return
self.version = int(m.group(1))
if self.version < 13:
yield self.Error('version number should be at least 13')
else:
yield self.Version(version=self.version)
return
# unknown syntax
yield self.UnknownLine(line, self.lineno)
else:
# end of file
if self.state == self._YAML:
yield self.Error(f'YAML block not terminated (started on line {self.yaml_lineno})')
if not self.bailed_out and self.plan and self.num_tests != self.plan.num_tests:
if self.num_tests < self.plan.num_tests:
yield self.Error(f'Too few tests run (expected {self.plan.num_tests}, got {self.num_tests})')
else:
yield self.Error(f'Too many tests run (expected {self.plan.num_tests}, got {self.num_tests})')
class TestLogger:
def flush(self) -> None:
pass
def start(self, harness: 'TestHarness') -> None:
pass
def start_test(self, harness: 'TestHarness', test: 'TestRun') -> None:
pass
def log_subtest(self, harness: 'TestHarness', test: 'TestRun', s: str, res: TestResult) -> None:
pass
def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
pass
async def finish(self, harness: 'TestHarness') -> None:
pass
def close(self) -> None:
pass
class TestFileLogger(TestLogger):
def __init__(self, filename: str, errors: str = 'replace') -> None:
self.filename = filename
self.file = open(filename, 'w', encoding='utf-8', errors=errors)
def close(self) -> None:
if self.file:
self.file.close()
self.file = None
class ConsoleLogger(TestLogger):
ASCII_SPINNER = ['..', ':.', '.:']
SPINNER = ["\U0001f311", "\U0001f312", "\U0001f313", "\U0001f314",
"\U0001f315", "\U0001f316", "\U0001f317", "\U0001f318"]
SCISSORS = "\u2700 "
HLINE = "\u2015"
RTRI = "\u25B6 "
def __init__(self) -> None:
self.running_tests: OrderedSet['TestRun'] = OrderedSet()
self.progress_test: T.Optional['TestRun'] = None
self.progress_task: T.Optional[asyncio.Future] = None
self.max_left_width = 0
self.stop = False
# TODO: before 3.10 this cannot be created immediately, because
# it will create a new event loop
self.update: asyncio.Event
self.should_erase_line = ''
self.test_count = 0
self.started_tests = 0
self.spinner_index = 0
try:
self.cols, _ = os.get_terminal_size(1)
self.is_tty = True
except OSError:
self.cols = 80
self.is_tty = False
self.output_start = dashes(self.SCISSORS, self.HLINE, self.cols - 2)
self.output_end = dashes('', self.HLINE, self.cols - 2)
self.sub = self.RTRI
self.spinner = self.SPINNER
try:
self.output_start.encode(sys.stdout.encoding or 'ascii')
except UnicodeEncodeError:
self.output_start = dashes('8<', '-', self.cols - 2)
self.output_end = dashes('', '-', self.cols - 2)
self.sub = '| '
self.spinner = self.ASCII_SPINNER
def flush(self) -> None:
if self.should_erase_line:
print(self.should_erase_line, end='')
self.should_erase_line = ''
def print_progress(self, line: str) -> None:
print(self.should_erase_line, line, sep='', end='\r')
self.should_erase_line = '\x1b[K'
def request_update(self) -> None:
self.update.set()
def emit_progress(self, harness: 'TestHarness') -> None:
if self.progress_test is None:
self.flush()
return
if len(self.running_tests) == 1:
count = f'{self.started_tests}/{self.test_count}'
else:
count = '{}-{}/{}'.format(self.started_tests - len(self.running_tests) + 1,
self.started_tests, self.test_count)
left = '[{}] {} '.format(count, self.spinner[self.spinner_index])
self.spinner_index = (self.spinner_index + 1) % len(self.spinner)
right = '{spaces} {dur:{durlen}}'.format(
spaces=' ' * TestResult.maxlen(),
dur=int(time.time() - self.progress_test.starttime),
durlen=harness.duration_max_len)
if self.progress_test.timeout:
right += '/{timeout:{durlen}}'.format(
timeout=self.progress_test.timeout,
durlen=harness.duration_max_len)
right += 's'
details = self.progress_test.get_details()
if details:
right += ' ' + details
line = harness.format(self.progress_test, colorize=True,
max_left_width=self.max_left_width,
left=left, right=right)
self.print_progress(line)
def start(self, harness: 'TestHarness') -> None:
async def report_progress() -> None:
loop = asyncio.get_running_loop()
next_update = 0.0
self.request_update()
while not self.stop:
await self.update.wait()
self.update.clear()
# We may get here simply because the progress line has been
# overwritten, so do not always switch. Only do so every
# second, or if the printed test has finished
if loop.time() >= next_update:
self.progress_test = None
next_update = loop.time() + 1
loop.call_at(next_update, self.request_update)
if (self.progress_test and
self.progress_test.res is not TestResult.RUNNING):
self.progress_test = None
if not self.progress_test:
if not self.running_tests:
continue
# Pick a test in round robin order
self.progress_test = self.running_tests.pop(last=False)
self.running_tests.add(self.progress_test)
self.emit_progress(harness)
self.flush()
self.update = asyncio.Event()
self.test_count = harness.test_count
self.cols = max(self.cols, harness.max_left_width + 30)
if self.is_tty and not harness.need_console:
# Account for "[aa-bb/cc] OO " in the progress report
self.max_left_width = 3 * len(str(self.test_count)) + 8
self.progress_task = asyncio.ensure_future(report_progress())
def start_test(self, harness: 'TestHarness', test: 'TestRun') -> None:
if test.verbose and test.cmdline:
self.flush()
print(harness.format(test, mlog.colorize_console(),
max_left_width=self.max_left_width,
right=test.res.get_text(mlog.colorize_console())))
print(test.res.get_command_marker() + test.cmdline)
if test.direct_stdout:
print(self.output_start, flush=True)
elif not test.needs_parsing:
print(flush=True)
self.started_tests += 1
self.running_tests.add(test)
self.running_tests.move_to_end(test, last=False)
self.request_update()
def shorten_log(self, harness: 'TestHarness', result: 'TestRun') -> str:
if not result.verbose and not harness.options.print_errorlogs:
return ''
log = result.get_log(mlog.colorize_console(),
stderr_only=result.needs_parsing)
if result.verbose:
return log
lines = log.splitlines()
if len(lines) < 100:
return log
else:
return str(mlog.bold('Listing only the last 100 lines from a long log.\n')) + '\n'.join(lines[-100:])
def print_log(self, harness: 'TestHarness', result: 'TestRun') -> None:
if not result.verbose:
cmdline = result.cmdline
if not cmdline:
print(result.res.get_command_marker() + result.stdo)
return
print(result.res.get_command_marker() + cmdline)
log = self.shorten_log(harness, result)
if log:
print(self.output_start)
print_safe(log)
print(self.output_end)
def log_subtest(self, harness: 'TestHarness', test: 'TestRun', s: str, result: TestResult) -> None:
if test.verbose or (harness.options.print_errorlogs and result.is_bad()):
self.flush()
print(harness.format(test, mlog.colorize_console(), max_left_width=self.max_left_width,
prefix=self.sub,
middle=s,
right=result.get_text(mlog.colorize_console())), flush=True)
self.request_update()
def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
self.running_tests.remove(result)
if result.res is TestResult.TIMEOUT and (result.verbose or
harness.options.print_errorlogs):
self.flush()
print(f'{result.name} time out (After {result.timeout} seconds)')
if not harness.options.quiet or not result.res.is_ok():
self.flush()
if result.cmdline and result.direct_stdout:
print(self.output_end)
print(harness.format(result, mlog.colorize_console(), max_left_width=self.max_left_width))
else:
print(harness.format(result, mlog.colorize_console(), max_left_width=self.max_left_width),
flush=True)
if result.verbose or result.res.is_bad():
self.print_log(harness, result)
if result.warnings:
print(flush=True)
for w in result.warnings:
print(w, flush=True)
print(flush=True)
if result.verbose or result.res.is_bad():
print(flush=True)
self.request_update()
async def finish(self, harness: 'TestHarness') -> None:
self.stop = True
self.request_update()
if self.progress_task:
await self.progress_task
if harness.collected_failures and \
(harness.options.print_errorlogs or harness.options.verbose):
print("\nSummary of Failures:\n")
for i, result in enumerate(harness.collected_failures, 1):
print(harness.format(result, mlog.colorize_console()))
print(harness.summary())
class TextLogfileBuilder(TestFileLogger):
def start(self, harness: 'TestHarness') -> None:
self.file.write(f'Log of Meson test suite run on {datetime.datetime.now().isoformat()}\n\n')
inherit_env = env_tuple_to_str(os.environ.items())
self.file.write(f'Inherited environment: {inherit_env}\n\n')
def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
title = f'{result.num}/{harness.test_count}'
self.file.write(dashes(title, '=', 78) + '\n')
self.file.write('test: ' + result.name + '\n')
starttime_str = time.strftime("%H:%M:%S", time.gmtime(result.starttime))
self.file.write('start time: ' + starttime_str + '\n')
self.file.write('duration: ' + '%.2fs' % result.duration + '\n')
self.file.write('result: ' + result.get_exit_status() + '\n')
if result.cmdline:
self.file.write('command: ' + result.cmdline + '\n')
if result.stdo:
name = 'stdout' if harness.options.split else 'output'
self.file.write(dashes(name, '-', 78) + '\n')
self.file.write(result.stdo)
if result.stde:
self.file.write(dashes('stderr', '-', 78) + '\n')
self.file.write(result.stde)
self.file.write(dashes('', '=', 78) + '\n\n')
async def finish(self, harness: 'TestHarness') -> None:
if harness.collected_failures:
self.file.write("\nSummary of Failures:\n\n")
for i, result in enumerate(harness.collected_failures, 1):
self.file.write(harness.format(result, False) + '\n')
self.file.write(harness.summary())
print(f'Full log written to {self.filename}')
class JsonLogfileBuilder(TestFileLogger):
def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
jresult: T.Dict[str, T.Any] = {
'name': result.name,
'stdout': result.stdo,
'result': result.res.value,
'starttime': result.starttime,
'duration': result.duration,
'returncode': result.returncode,
'env': result.env,
'command': result.cmd,
}
if result.stde:
jresult['stderr'] = result.stde
self.file.write(json.dumps(jresult) + '\n')
class JunitBuilder(TestLogger):
"""Builder for Junit test results.
Junit is impossible to stream out, it requires attributes counting the
total number of tests, failures, skips, and errors in the root element
and in each test suite. As such, we use a builder class to track each
test case, and calculate all metadata before writing it out.
For tests with multiple results (like from a TAP test), we record the
test as a suite with the project_name.test_name. This allows us to track
each result separately. For tests with only one result (such as exit-code
tests) we record each one into a suite with the name project_name. The use
of the project_name allows us to sort subproject tests separately from
the root project.
"""
def __init__(self, filename: str) -> None:
self.filename = filename
self.root = et.Element(
'testsuites', tests='0', errors='0', failures='0')
self.suites: T.Dict[str, et.Element] = {}
def log(self, harness: 'TestHarness', test: 'TestRun') -> None:
"""Log a single test case."""
if test.junit is not None:
for suite in test.junit.findall('.//testsuite'):
# Assume that we don't need to merge anything here...
suite.attrib['name'] = '{}.{}.{}'.format(test.project, test.name, suite.attrib['name'])
# GTest can inject invalid attributes
for case in suite.findall('.//testcase[@result]'):
del case.attrib['result']
for case in suite.findall('.//testcase[@timestamp]'):
del case.attrib['timestamp']
for case in suite.findall('.//testcase[@file]'):
del case.attrib['file']
for case in suite.findall('.//testcase[@line]'):
del case.attrib['line']
self.root.append(suite)
return
# In this case we have a test binary with multiple results.
# We want to record this so that each result is recorded
# separately
if test.results:
suitename = f'{test.project}.{test.name}'
assert suitename not in self.suites or harness.options.repeat > 1, 'duplicate suite'
suite = self.suites[suitename] = et.Element(
'testsuite',
name=suitename,
tests=str(len(test.results)),
errors=str(sum(1 for r in test.results if r.result in
{TestResult.INTERRUPT, TestResult.ERROR})),
failures=str(sum(1 for r in test.results if r.result in
{TestResult.FAIL, TestResult.UNEXPECTEDPASS, TestResult.TIMEOUT})),
skipped=str(sum(1 for r in test.results if r.result is TestResult.SKIP)),
time=str(test.duration),
)
for subtest in test.results:
# Both name and classname are required. Use the suite name as
# the class name, so that e.g. GitLab groups testcases correctly.
testcase = et.SubElement(suite, 'testcase', name=str(subtest), classname=suitename)
if subtest.result is TestResult.SKIP:
et.SubElement(testcase, 'skipped')
elif subtest.result is TestResult.ERROR:
et.SubElement(testcase, 'error')
elif subtest.result is TestResult.FAIL:
et.SubElement(testcase, 'failure')
elif subtest.result is TestResult.UNEXPECTEDPASS:
fail = et.SubElement(testcase, 'failure')
fail.text = 'Test unexpected passed.'
elif subtest.result is TestResult.INTERRUPT:
fail = et.SubElement(testcase, 'error')
fail.text = 'Test was interrupted by user.'
elif subtest.result is TestResult.TIMEOUT:
fail = et.SubElement(testcase, 'error')
fail.text = 'Test did not finish before configured timeout.'
if subtest.explanation:
et.SubElement(testcase, 'system-out').text = subtest.explanation
if test.stdo:
out = et.SubElement(suite, 'system-out')
out.text = replace_unencodable_xml_chars(test.stdo.rstrip())
if test.stde:
err = et.SubElement(suite, 'system-err')
err.text = replace_unencodable_xml_chars(test.stde.rstrip())
else:
if test.project not in self.suites:
suite = self.suites[test.project] = et.Element(
'testsuite', name=test.project, tests='1', errors='0',
failures='0', skipped='0', time=str(test.duration))
else:
suite = self.suites[test.project]
suite.attrib['tests'] = str(int(suite.attrib['tests']) + 1)
testcase = et.SubElement(suite, 'testcase', name=test.name,
classname=test.project, time=str(test.duration))
if test.res is TestResult.SKIP:
et.SubElement(testcase, 'skipped')
suite.attrib['skipped'] = str(int(suite.attrib['skipped']) + 1)
elif test.res is TestResult.ERROR:
et.SubElement(testcase, 'error')
suite.attrib['errors'] = str(int(suite.attrib['errors']) + 1)
elif test.res is TestResult.FAIL:
et.SubElement(testcase, 'failure')
suite.attrib['failures'] = str(int(suite.attrib['failures']) + 1)
if test.stdo:
out = et.SubElement(testcase, 'system-out')
out.text = replace_unencodable_xml_chars(test.stdo.rstrip())
if test.stde:
err = et.SubElement(testcase, 'system-err')
err.text = replace_unencodable_xml_chars(test.stde.rstrip())
async def finish(self, harness: 'TestHarness') -> None:
"""Calculate total test counts and write out the xml result."""
for suite in self.suites.values():
self.root.append(suite)
# Skipped is really not allowed in the "testsuits" element
for attr in ['tests', 'errors', 'failures']:
self.root.attrib[attr] = str(int(self.root.attrib[attr]) + int(suite.attrib[attr]))
tree = et.ElementTree(self.root)
with open(self.filename, 'wb') as f:
tree.write(f, encoding='utf-8', xml_declaration=True)
class TestRun:
TEST_NUM = 0
PROTOCOL_TO_CLASS: T.Dict[TestProtocol, T.Type['TestRun']] = {}
def __new__(cls, test: TestSerialisation, *args: T.Any, **kwargs: T.Any) -> T.Any:
return super().__new__(TestRun.PROTOCOL_TO_CLASS[test.protocol])
def __init__(self, test: TestSerialisation, test_env: T.Dict[str, str],
name: str, timeout: T.Optional[int], is_parallel: bool, verbose: bool):
self.res = TestResult.PENDING
self.test = test
self._num: T.Optional[int] = None
self.name = name
self.timeout = timeout
self.results: T.List[TAPParser.Test] = []
self.returncode: T.Optional[int] = None
self.starttime: T.Optional[float] = None
self.duration: T.Optional[float] = None
self.stdo = ''
self.stde = ''
self.additional_error = ''
self.cmd: T.Optional[T.List[str]] = None
self.env = test_env
self.should_fail = test.should_fail
self.project = test.project_name
self.junit: T.Optional[et.ElementTree] = None
self.is_parallel = is_parallel
self.verbose = verbose
self.warnings: T.List[str] = []
def start(self, cmd: T.List[str]) -> None:
self.res = TestResult.RUNNING
self.starttime = time.time()
self.cmd = cmd
@property
def num(self) -> int:
if self._num is None:
TestRun.TEST_NUM += 1
self._num = TestRun.TEST_NUM
return self._num
@property
def direct_stdout(self) -> bool:
return self.verbose and not self.is_parallel and not self.needs_parsing
def get_results(self) -> str:
if self.results:
# running or succeeded
passed = sum(x.result.is_ok() for x in self.results)
ran = sum(x.result is not TestResult.SKIP for x in self.results)
if passed == ran:
return f'{passed} subtests passed'
else:
return f'{passed}/{ran} subtests passed'
return ''
def get_exit_status(self) -> str:
return returncode_to_status(self.returncode)
def get_details(self) -> str:
if self.res is TestResult.PENDING:
return ''
if self.returncode:
return self.get_exit_status()
return self.get_results()
def _complete(self) -> None:
if self.res == TestResult.RUNNING:
self.res = TestResult.OK
assert isinstance(self.res, TestResult)
if self.should_fail and self.res in (TestResult.OK, TestResult.FAIL):
self.res = TestResult.UNEXPECTEDPASS if self.res is TestResult.OK else TestResult.EXPECTEDFAIL
if self.stdo and not self.stdo.endswith('\n'):
self.stdo += '\n'
if self.stde and not self.stde.endswith('\n'):
self.stde += '\n'
self.duration = time.time() - self.starttime
@property
def cmdline(self) -> T.Optional[str]:
if not self.cmd:
return None
test_only_env = set(self.env.items()) - set(os.environ.items())
return env_tuple_to_str(test_only_env) + \