-
Notifications
You must be signed in to change notification settings - Fork 20
/
btest
executable file
·3369 lines (2643 loc) · 103 KB
/
btest
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
#! /usr/bin/env python3
#
# Main test driver.
#
# pylint: disable=line-too-long,too-many-lines,invalid-name,missing-function-docstring,
# pylint: disable=missing-class-docstring
import atexit
import binascii
import configparser
import copy
import fnmatch
import glob
import json
import optparse
import os
import os.path
import pathlib
import platform as pform
import re
import shlex
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
import uuid
import xml.dom.minidom
from datetime import datetime
# We require the external multiprocess library on Windows due to pickling issues
# with the standard one.
if sys.platform == "win32":
try:
import multiprocess as mp
import multiprocess.managers as mp_managers
import multiprocess.sharedctypes as mp_sharedctypes
except ImportError as error:
print(
"error: btest failed to import the 'multiprocess' library\n"
"\n"
"This library is required for btest to function on Windows. "
"It can be installed from pip like:\n"
"\n"
" pip install multiprocess\n"
"\n"
"Also check the following exception output for possible alternate explanations:\n\n"
"{}: {}".format(type(error).__name__, error),
file=sys.stderr,
)
else:
import multiprocessing as mp
import multiprocessing.managers as mp_managers
import multiprocessing.sharedctypes as mp_sharedctypes
VERSION = "1.1-8" # Automatically filled in.
Name = "btest"
Config = None
try:
ConfigDefault = os.environ["BTEST_CFG"]
except KeyError:
ConfigDefault = "btest.cfg"
def normalize_path(path):
"""Ensures that paths on Windows convert backslashes to forward slashes, to
make path handling easier in lots of other places. On non-Windows platforms
this is a no-op beyond converting things to absolute paths."""
os_path = os.path.abspath(path)
windows_path = pathlib.PureWindowsPath(os_path)
return windows_path.as_posix()
def normalize_path_join(*args):
return normalize_path(os.path.join(*args))
def reopen_std_file(stdfile):
"""Reopens one of the stderr or stdout files, but resets the newline
used in the output to "\n" in order to force that line ending on Windows.
Without this, Windows will use "\r\n" which breaks a lot of tests."""
return open(
stdfile.fileno(),
mode=stdfile.mode,
buffering=1,
encoding=stdfile.encoding,
errors=stdfile.errors,
newline="\n",
closefd=False,
)
def output(msg, nl=True, file=None):
if not file:
file = reopen_std_file(sys.__stderr__)
if nl:
print(msg, file=file)
else:
print(msg, end=" ", file=file)
def warning(msg):
print(f"warning: {msg}", file=sys.stderr)
def error(msg):
print(msg, file=sys.stderr)
sys.exit(1)
def mkdir(folder):
if not os.path.exists(folder):
try:
os.makedirs(folder)
except OSError as exc:
error(f"cannot create directory {folder}: {exc}")
else:
if not os.path.isdir(folder):
error(f"path {folder} exists but is not a directory")
def which(cmd):
# Adapted from http://stackoverflow.com/a/377028
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
(fpath, _) = os.path.split(cmd)
if fpath:
if is_exe(cmd):
return cmd
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, cmd)
if is_exe(exe_file):
return exe_file
return None
def platform():
return pform.system()
def validate_version_requirement(required: str, present: str):
"""Validates that `present` version semantically satisfies `required` version."""
def extract_version(v: str):
"""Helper function to extract version components from a string."""
try:
xyz = [int(x) for x in re.split(r"[.-]", v)]
except ValueError:
error(
"invalid version %s: versions must contain only numeric identifiers" % v
)
return xyz
v_present = extract_version(present)
v_required = extract_version(required)
if v_present < v_required:
error(
"%s requires at least BTest %s, this is %s. Please upgrade."
% (Options.config, min_version, VERSION)
)
# Get the value of the specified option in the specified section (or
# section "btest" if not specified), or return the specified default value
# if the option or section is not found. The returned value has macros and
# backticks from the config file expanded, but if the default value is returned
# it will not be modified in any way.
def getOption(key, default, section="btest"):
try:
value = Config.get(section, key)
except (configparser.NoSectionError, configparser.NoOptionError):
return default
return ExpandBackticks(value)
reBackticks = re.compile(r"`(([^`]|`)*)`")
def readTestsFile(file):
try:
# Read state file.
tests = []
for line in open(file, encoding="utf-8"):
line = line.strip()
if not line or line.startswith("#"):
continue
tests += [line]
tests = findTests(tests)
except OSError:
return (False, [])
return (True, tests)
def _build_win_subprocess_cmd_script(cmd, tmpdir=None):
"""
Builds a bash file for running subprocess commands under Windows.
:param cmd The command line to be run under bash.
:param tmpdir An optional directory path where the script file will be written.
If None, it will be written to the system's temp directory.
:return A tuple containing a file object pointing at the script file and a bash
command for running the script.
"""
tf = tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", suffix=".sh", dir=tmpdir, delete=True
)
fcontents = f"#!/usr/bin/env bash\n{cmd}\n"
tf.write(fcontents)
tf.flush()
bash_cmd = ["bash.exe", "-c", normalize_path(tf.name)]
return tf, bash_cmd
# Expand backticks in a config option value and return the result.
def ExpandBackticks(origvalue):
def _exec(m):
cmd = m.group(1)
if not cmd:
return ""
tf = None
if sys.platform == "win32":
try:
tf, bash_cmd = _build_win_subprocess_cmd_script(cmd, None)
pp = subprocess.Popen(bash_cmd, stdout=subprocess.PIPE)
except OSError as e:
error(f"cannot execute '{cmd}': {e}")
else:
try:
pp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
except OSError as e:
error(f"cannot execute '{cmd}': {e}")
out = pp.communicate()[0]
out = out.decode()
if tf:
tf.close()
return out.strip()
value = reBackticks.sub(_exec, origvalue)
return value
# We monkey-patch the config parser to provide an alternative method that
# expands backticks in option values and does not include defaults in
# returned section items.
def cpItemsNoDefaults(self, section):
# Get the keys from the specified section without anything from the
# default section (the values are raw, so we need to fetch the actual
# value below).
try:
items = self._sections[section].items()
except KeyError:
raise configparser.NoSectionError(section)
# Override any of the defaults with ones that we read from the command-line
# options before expanding macros below.
cfg_defaults = self.defaults()
if Options.defaults:
for d in Options.defaults:
k, v = d.split("=", 1)
cfg_defaults[k] = v.strip("'\"")
result = {}
for key, rawvalue in items:
# Python 2 includes a key of "__name__" that we don't want (Python 3
# doesn't include this)
if not key.startswith("__"):
# Expand macros such as %(testbase)s.
value = self.get(section, key)
# Expand backticks (if any) in the value.
result[key] = ExpandBackticks(value)
return result.items()
def getcfgparser(defaults):
configparser.ConfigParser.itemsNoDefaults = cpItemsNoDefaults
cfg = configparser.ConfigParser()
# We make all key lookups case-sensitive to avoid aliasing of
# case-sensitive environment variables.
cfg.optionxform = lambda optionstr: optionstr
default_section = cfg.defaults()
for key, value in defaults.items():
default_section[key] = value
return cfg
# Replace environment variables in string.
def replaceEnvs(s):
def replace_with_env(m):
try:
return os.environ[m.group(1)]
except KeyError:
return ""
return RE_ENV.sub(replace_with_env, s)
# Execute one of test's command line *cmdline*. *measure_time* indicates if
# timing measurement is desired. *kw_args* are further keyword arguments
# interpreted the same way as with subprocess.check_call().
# Returns a 3-tuple (success, rc, time) where the former two likewise
# have the same meaning as with runSubprocess(), and 'time' is an integer
# value corresponding to the commands execution time measured in some
# appropiate integer measure. If 'time' is negative, that's an indicator
# that time measurement wasn't possible and the value is to be ignored.
def runTestCommandLine(cmdline, measure_time, **kwargs):
if measure_time and Timer:
return Timer.timeSubprocess(cmdline, **kwargs)
(success, rc) = runSubprocess(cmdline, **kwargs)
return (success, rc, -1)
# Runs a subprocess. Takes same arguments as subprocess.check_call()
# and returns a 2-tuple (success, rc) where *success* is a boolean
# indicating if the command executed, and *rc* is its exit code if it did.
def runSubprocess(*args, **kwargs):
def child(q):
try:
if sys.platform == "win32":
tmpdir = normalize_path(kwargs.get("cwd", ""))
if len(args) > 1:
cmd = shlex.join(args)
else:
cmd = args[0]
tf, bash_cmd = _build_win_subprocess_cmd_script(cmd, tmpdir)
with tf:
subprocess.check_call(bash_cmd, **kwargs)
else:
subprocess.check_call(*args, **kwargs)
success = True
rc = 0
except subprocess.CalledProcessError as e:
success = False
rc = e.returncode
except KeyboardInterrupt:
success = False
rc = 0
q.put([success, rc])
try:
q = mp.Queue()
p = mp.Process(target=child, args=(q,))
p.start()
result = q.get()
p.join()
except KeyboardInterrupt:
# Bail out here directly as otherwise we'd get a bunch of errors.
# from all the childs.
sys.exit(1)
return result
# Description of an alternative configuration.
class Alternative:
DEFAULT = "default"
def __init__(self, name):
self.name = name
self.filters = {}
self.substitutions = {}
self.envs = {}
def is_default(self):
return self.name == Alternative.DEFAULT
def is_empty(self):
return not (self.filters or self.substitutions or self.envs)
# Exception class thrown to signal manager to abort processing.
# The message passed to the constructor will be printed to the console.
class Abort(Exception):
pass
# Main class distributing the work across threads.
class TestManager(mp_managers.SyncManager):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._output_handler = None
self._lock = None
self._succeeded = None
self._failed = None
self._failed_expected = None
self._unstable = None
self._skipped = None
self._tests = None
self._failed_tests = None
self._num_tests = None
self._timing = None
self._ports = None
def run(self, tests, output_handler):
self.start()
mgr_data = self.dict()
mgr_data["Alternatives"] = Alternatives
mgr_data["BaselineDirs"] = BaselineDirs
mgr_data["Initializer"] = Initializer
mgr_data["Finalizer"] = Finalizer
mgr_data["Teardown"] = Teardown
mgr_data["Options"] = Options
mgr_data["TestBase"] = TestBase
mgr_data["TmpDir"] = TmpDir
mgr_data["RE_INPUT"] = RE_INPUT
mgr_data["RE_DIR"] = RE_DIR
mgr_data["RE_ENV"] = RE_ENV
output_handler.prepare(self)
self._output_handler = output_handler
self._lock = self.RLock()
self._succeeded = mp_sharedctypes.RawValue("i", 0)
self._failed = mp_sharedctypes.RawValue("i", 0)
self._failed_expected = mp_sharedctypes.RawValue("i", 0)
self._unstable = mp_sharedctypes.RawValue("i", 0)
self._skipped = mp_sharedctypes.RawValue("i", 0)
self._tests = self.list(tests)
self._failed_tests = self.list([])
self._num_tests = len(self._tests)
self._timing = self.loadTiming()
port_range = getOption("PortRange", "1024-65535")
port_range_lo = int(port_range.split("-")[0])
port_range_hi = int(port_range.split("-")[1])
if port_range_lo > port_range_hi:
error(f"invalid PortRange value: {port_range}")
max_test_ports = 0
test_with_most_ports = None
for t in self._tests:
if len(t.ports) > max_test_ports:
max_test_ports = len(t.ports)
test_with_most_ports = t
if max_test_ports > port_range_hi - port_range_lo + 1:
error(
"PortRange {} cannot satisfy requirement of {} ports in test {}".format(
port_range, max_test_ports, test_with_most_ports.name
)
)
self._ports = self.list([p for p in range(port_range_lo, port_range_hi + 1)])
threads = []
# With interactive input possibly required, we run tests
# directly. This avoids noisy output appearing from detached
# processes post-btest-exit when using CTRL-C during the input
# stage.
if Options.mode == "UPDATE_INTERACTIVE":
self.threadRun(0, mgr_data)
else:
try:
# Create a set of processes for running each of the tests. This isn't the actual
# zeek processes, but runner processes executing individual test commands.
for i in range(Options.threads):
t = mp.Process(
name="#%d" % (i + 1), target=lambda: self.threadRun(i, mgr_data)
)
t.start()
threads += [t]
for t in threads:
t.join()
except KeyboardInterrupt:
for t in threads:
t.terminate()
t.join()
if (
Options.abort_on_failure
and self._failed.value > 0
and self._failed.value > self._failed_expected.value
):
# Signal abort. The child processes will already have
# finished because the join() above still ran.
raise Abort("Aborted after first failure.")
# Record failed tests if not updating.
if Options.mode != "UPDATE" and Options.mode != "UPDATE_INTERACTIVE":
try:
state = open(StateFile, "w", encoding="utf-8")
except OSError:
error("cannot open state file %s" % StateFile)
for t in sorted(self._failed_tests):
print(t, file=state)
state.close()
return (
self._succeeded.value,
self._failed.value,
self._skipped.value,
self._unstable.value,
self._failed_expected.value,
)
def percentage(self):
if not self._num_tests:
return 0
count = self._succeeded.value + self._failed.value + self._skipped.value
return 100.0 * count / self._num_tests
# Worker method for each of the "threads" specified by the "-j" argument passed
# at run time. This basically segments the list of tests into chunks and runs
# until we're out of chunks.
def threadRun(self, thread_num, mgr_data):
# This should prevent the child processes from receiving SIGINT signals and
# let the KeyboardInterrupt handler in the manager's run() method handle
# those.
signal.signal(signal.SIGINT, signal.SIG_IGN)
all_tests = []
# Globals get lost moving from the parent to the child on Windows, so we need to use
# the data proxied from the manager to rebuild the dict of globals before continuing.
if sys.platform == "win32":
for global_key, global_value in mgr_data.items():
globals()[global_key] = global_value
while True:
# Pull the next test from the list that was built at startup. This may
# be more than one test if there were alternatives requested in the
# arguments passed to btest.
thread_tests = self.nextTests(thread_num)
if thread_tests is None:
# No more work for us.
return
all_tests += thread_tests
for t in thread_tests:
t.run(self)
self.testReplayOutput(t)
if Options.update_times:
self.saveTiming(all_tests)
def rerun(self, test):
test.reruns += 1
self._tests += [test.clone(increment=False)]
def nextTests(self, thread_num):
with self._lock:
if (
Options.abort_on_failure
and self._failed.value > 0
and self._failed.value > self._failed_expected.value
):
# Don't hand out any more tests if we are to abort after
# first failure. Doing so will let all the processes terminate.
return None
for i in range(len(self._tests)):
t = self._tests[i]
if not t:
continue
if t.serialize and t.serialize_hash() % Options.threads != thread_num:
# Not ours.
continue
# We'll execute it, delete from queue.
del self._tests[i]
if Options.alternatives:
tests = []
for alternative in Options.alternatives:
if alternative in t.ignore_alternatives:
continue
if (
t.include_alternatives
and alternative not in t.include_alternatives
):
continue
alternative_test = copy.deepcopy(t)
if alternative == Alternative.DEFAULT:
alternative = ""
alternative_test.setAlternative(alternative)
tests += [alternative_test]
else:
if (
t.include_alternatives
and Alternative.DEFAULT not in t.include_alternatives
):
tests = []
elif Alternative.DEFAULT in t.ignore_alternatives:
tests = []
else:
tests = [t]
return tests
# No more tests for us.
return None
def returnPorts(self, ports):
with self._lock:
for p in ports:
self._ports.append(p)
def getAvailablePorts(self, count):
with self._lock:
if count > len(self._ports):
return []
first_port = -1
rval = []
for _ in range(count):
while True:
if len(self._ports) == 0:
for s in rval:
s.close()
self._ports.append(s.getsockname()[1])
return []
next_port = self._ports[0]
if next_port == first_port:
# Looped over port pool once, bail out.
for s in rval:
s.close()
self._ports.append(s.getsockname()[1])
return []
if first_port == -1:
first_port = next_port
del self._ports[0]
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Setting REUSEADDR would allow ports to be recycled
# more quickly, but on macOS, seems to also have the
# effect of allowing multiple sockets to bind to the
# same port, even if REUSEPORT is off, so just try to
# ensure both are off.
if hasattr(socket, "SO_REUSEADDR"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 0)
if hasattr(socket, "SO_REUSEPORT"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 0)
try:
sock.bind(("", next_port))
except Exception:
self._ports.append(next_port)
continue
else:
break
rval.append(sock)
return rval
def lock(self):
return self._lock
def testStart(self, test):
with self._lock:
self._output_handler.testStart(test)
def testCommand(self, test, cmdline):
with self._lock:
self._output_handler.testCommand(test, cmdline)
def testProgress(self, test, msg):
with self._lock:
self._output_handler.testProgress(test, msg)
def testSucceeded(self, test):
test.parseProgress()
msg = "ok"
if test.known_failure:
msg += " (but expected to fail)"
msg += test.timePostfix()
with self._lock:
if test.reruns == 0:
self._succeeded.value += 1
self._output_handler.testSucceeded(test, msg)
else:
self._failed.value -= 1
if test.known_failure:
self._failed_expected.value -= 1
self._unstable.value += 1
msg += f" on retry #{test.reruns}, unstable"
self._output_handler.testUnstable(test, msg)
self._output_handler.testFinished(test, msg)
def testFailed(self, test):
test.parseProgress()
msg = "failed"
if test.reruns > 0:
msg += f" on retry #{test.reruns}"
if test.known_failure:
msg += " (expected)"
msg += test.timePostfix()
with self._lock:
self._output_handler.testFailed(test, msg)
self._output_handler.testFinished(test, msg)
if test.reruns == 0:
self._failed.value += 1
if test.known_failure:
self._failed_expected.value += 1
else:
self._failed_tests += [test.name]
if test.reruns < Options.retries and not test.known_failure:
self.rerun(test)
def testSkipped(self, test):
msg = "not available, skipped"
with self._lock:
self._output_handler.testSkipped(test, msg)
self._skipped.value += 1
def testReplayOutput(self, test):
with self._lock:
self._output_handler.replayOutput(test)
def testTimingBaseline(self, test):
return self._timing.get(test.name, -1)
# Returns the name of the file to store the timing baseline in for this host.
def timingPath(self):
id = uuid.uuid3(uuid.NAMESPACE_DNS, str(uuid.getnode()))
return os.path.abspath(os.path.join(BaselineTimingDir, id.hex))
# Loads baseline timing information for this host if available. Returns
# empty directory if not.
def loadTiming(self):
timing = {}
with self._lock:
path = self.timingPath()
if not os.path.exists(path):
return {}
for line in open(path):
(k, v) = line.split()
timing[k] = float(v)
return timing
# Updates the timing baseline for the given tests on this host.
def saveTiming(self, tests):
with self._lock:
changed = False
timing = self.loadTiming()
for t in tests:
if t and t.measure_time and t.utime >= 0:
changed = True
timing[t.name] = t.utime
if not changed:
return
path = self.timingPath()
(dir, base) = os.path.split(path)
mkdir(dir)
out = open(path, "w")
for k, v in timing.items():
print("%s %u" % (k, v), file=out)
out.close()
class CmdLine:
"""A single command to invoke.
These commands can be provided by @TEST-{EXEC,REQUIRES} instructions, an
Initializer, Finalizer, or Teardown, or their part-specific equivalents.
"""
def __init__(self, cmdline, expect_success, part, file):
self.cmdline = cmdline
self.expect_success = expect_success
self.part = part
self.file = file
class CmdSeq:
"""A sequence of commands, with potential subsequent teardown.
Tracking the teardown separately allows us to skip to it when commands
fail. Commands can be invidual CmdLines or CmdSeq instances. Test.run()
processes the latter recursively.
"""
def __init__(self):
self.cmds = [] # CmdLine or CmdSeq instances
self.teardown = None
# One test.
class Test:
def __init__(self, file=None, directory=None): # Allow dir to be directly defined
if file is not None:
self.dir = normalize_path(os.path.dirname(file))
else:
self.dir = normalize_path(directory)
self.alternative = None
self.baselines = []
self.basename = None
self.bound_ports = []
self.cloned = False
self.cmdseqs = []
self.contents = []
self.copy_files = []
self.diag = None
self.diagmsgs = []
self.doc = []
self.files = []
self.groups = set()
self.ignore_alternatives = []
self.include_alternatives = []
self.known_failure = False
self.log = None
self.measure_time = False
self.mgr = None
self.monitor = None
self.monitor_quit = None
self.name = None
self.number = 1
self.part = -1
self.ports = set()
self.progress_lock = None
self.requires = []
self.reruns = 0
self.serialize = []
self.start = None
self.stdout = None
self.stderr = None
self.tmpdir = None
self.utime = -1
self.utime_base = -1
self.utime_exceeded = False
self.utime_perc = 0.0
self.verbose = None
def __lt__(self, value):
return self.name and value.name and self.name < value.name
def serialize_hash(self):
if not self.serialize:
return 0
return int(binascii.crc32(self.serialize.encode("utf-8")))
def displayName(self):
name = self.name
if self.alternative:
name = f"{name} [{self.alternative}]"
return name
def setAlternative(self, alternative):
self.alternative = alternative
# Parse the test's content.
def parse(self, content, file):
cmds = {}
for line in content:
m = RE_IGNORE.search(line)
if m:
# Ignore this file.
return False
for tag, regexp, multiple, optional, group1, group2 in Commands:
m = regexp.search(line)
if m:
value = None
if group1 >= 0:
value = m.group(group1)
if group2 >= 0:
value = (value, m.group(group2))
if not multiple:
if tag in cmds:
error(f"{file}: {tag} defined multiple times.")
cmds[tag] = value
else:
try:
cmds[tag] += [value]
except KeyError:
cmds[tag] = [value]
# Make sure all non-optional commands are there.
for tag, regexp, multiple, optional, group1, group2 in Commands:
if not optional and tag not in cmds:
if tag == "exec":
error(
f"{file}: mandatory keyword '@TEST-EXEC' or '@TEST-EXEC-FAIL' is missing."
)
else:
error(f"{file}: mandatory {tag} command not found.")
basename = file
part = 1
m = RE_PART.match(file)
if m:
basename = m.group(1)
part = int(m.group(2))
name = os.path.relpath(basename, TestBase)
(name, ext) = os.path.splitext(name)
name = name.replace(os.sep, ".")
while name.startswith("."):
name = name[1:]
self.name = name
self.part = part
self.basename = name
self.contents += [(file, content)]
seq = CmdSeq()