Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / tools / tesh / tesh.py
1 #! @PYTHON_EXECUTABLE@
2 # -*- coding: utf-8 -*-
3 """
4
5 tesh -- testing shell
6 ========================
7
8 Copyright (c) 2012-2023. The SimGrid Team. All rights reserved.
9
10 This program is free software; you can redistribute it and/or modify it
11 under the terms of the license (GNU LGPL) which comes with this package.
12
13 #TODO: child of child of child that printfs. Does it work?
14 #TODO: a child dies after its parent. What happen?
15
16 #TODO: regular expression in output
17 #ex: >> Time taken: [0-9]+s
18 #TODO: linked regular expression in output
19 #ex:
20 # >> Bytes sent: ([0-9]+)
21 # >> Bytes recv: \1
22 # then, even better:
23 # ! expect (\1 > 500)
24
25 """
26
27 import sys
28 import errno
29 import os
30 import shlex
31 import re
32 import difflib
33 import signal
34 import argparse
35 import time
36
37 if sys.version_info[0] == 3:
38     import subprocess
39     import _thread
40 else:
41     raise RuntimeError("This program is expected to run with Python3 only")
42
43 ##############
44 #
45 # Utilities
46 #
47 #
48
49 # Singleton metaclass that works in Python 2 & 3
50 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
51
52 class _Singleton(type):
53     """ A metaclass that creates a Singleton base class when called. """
54     _instances = {}
55
56     def __call__(cls, *args, **kwargs):
57         if cls not in cls._instances:
58             cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
59         return cls._instances[cls]
60
61 class Singleton(_Singleton('SingletonMeta', (object,), {})):
62     """ The Singleton base class """
63     # pass
64
65 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n)
66                              for n in dir(signal) if n.startswith('SIG') and '_' not in n)
67
68 def tesh_exit(errcode):
69     """ Exit correctly """
70     # If you do not flush some prints are skipped
71     sys.stdout.flush()
72     # os._exit exit even when executed within a thread
73     # pylint: disable=protected-access
74     os._exit(errcode)
75
76
77 def fatal_error(msg):
78     """ Exit with error """
79     print("[Tesh/CRITICAL] " + str(msg))
80     tesh_exit(1)
81
82 # retrocompatibility: support ${aaa:=.} variable format
83 def replace_perl_variables(arg):
84     vname = arg.group(1)
85     vdefault = arg.group(2)
86     if vname in os.environ:
87         return "$" + vname
88     return vdefault
89
90 def setenv(arg):
91     """
92     Set an environment variable.
93     arg must be a string with the format "variable=value"
94     """
95     if '$' in arg:
96         arg = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, arg)
97         arg = expandvars2(arg)
98     (var, val) = arg.split("=", 1)
99     print("[Tesh/INFO] setenv " + var + "=" + val)
100     os.environ[var] = val
101     # os.putenv(var, val) does not work
102     # see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env
103
104
105 def expandvars2(path):
106     """ http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does """
107     return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path))
108
109 ##############
110 #
111 # Cleanup on signal
112 #
113 #
114
115 def process_is_dead(pid):
116     """ Tests whether the process is dead already """
117     try:
118         os.kill(pid, 0)
119     except ProcessLookupError:
120         return True
121     except OSError as err:
122         if err.errno == errno.ESRCH: # ESRCH == No such process. The process is now dead
123             return True
124     return False
125
126 def kill_process_group(pid):
127     """ This function send TERM signal + KILL signal after 0.2s to the group of the specified process """
128     if pid is None:
129         # Nobody to kill. We don't have anyone to kill on signal handler
130         return
131
132     try:
133         pgid = os.getpgid(pid)
134     except OSError:
135         # os.getpgid failed. Ok, don't cleanup.
136         return
137
138     try:
139         os.killpg(pgid, signal.SIGTERM)
140         if process_is_dead(pid):
141             return
142         time.sleep(0.2)
143         os.killpg(pgid, signal.SIGKILL)
144     except OSError:
145         # os.killpg failed. OK. Some subprocesses may still be running.
146         pass
147
148 def signal_handler(signo, _frame):
149     """ Signal handler """
150     print("Caught signal {}".format(SIGNALS_TO_NAMES_DICT[signo]))
151     running_pids = TeshState().running_pids # Just in case of interthread conflicts.
152     for pid in running_pids:
153         kill_process_group(pid)
154     TeshState().running_pids.clear()
155     tesh_exit(5)
156
157
158 ##############
159 #
160 # Classes
161 #
162 #
163
164
165 class FileReader(Singleton):
166     """ Read file line per line (and concat line that ends with "\") """
167     def __init__(self, filename=None):
168         if filename is None:
169             self.filename = "(stdin)"
170             self.fileno = sys.stdin
171         else:
172             self.filename_raw = filename
173             self.filename = os.path.basename(filename)
174             self.abspath = os.path.abspath(filename)
175             self.fileno = open(self.filename_raw)
176
177         self.linenumber = 0
178
179     def __repr__(self):
180         return self.filename + ":" + str(self.linenumber)
181
182     def readfullline(self):
183         """ Read a full line """
184         try:
185             line = next(self.fileno)
186             self.linenumber += 1
187         except StopIteration:
188             return None
189         if line[-1] == "\n":
190             txt = line[0:-1]
191         else:
192             txt = line
193         while len(line) > 1 and line[-2] == "\\":
194             txt = txt[0:-1]
195             line = next(self.fileno)
196             self.linenumber += 1
197             txt += line[0:-1]
198         return txt
199
200
201 class TeshState(Singleton):
202     """ Keep the state of tesh (mostly configuration values) """
203     def __init__(self):
204         self.running_pids = list() # stores which process group should be killed (or None otherwise)
205         self.threads = []
206         self.args_suffix = ""
207         self.ignore_regexps_common = []
208         self.jenkins = False  # not a Jenkins run by default
209         self.auto_valgrind = True
210         self.timeout = 10  # default value: 10 sec
211         self.wrapper = None
212         self.keep = False
213         self.return_code = 0
214
215     def add_thread(self, thread):
216         """ Add another thread to wait for """
217         self.threads.append(thread)
218
219     def join_all_threads(self):
220         """ Wait for all threads """
221         for thread in self.threads:
222             thread.acquire()
223             thread.release()
224
225     def set_return_code(self, value):
226         """ Set exit status """
227         if value > self.return_code:
228             self.return_code = value
229
230
231 class Cmd:
232     """ Command line object """
233     def __init__(self):
234         self.input_pipe = []
235         self.output_pipe_stdout = []
236         self.output_pipe_stderr = []
237         self.timeout = TeshState().timeout
238         self.args = None
239         self.linenumber = -1
240
241         self.background = False
242         # Python threads loose the cwd
243         self.cwd = os.getcwd()
244
245         self.ignore_output = False
246         self.expect_return = [0]
247
248         self.output_display = False
249
250         self.sort = -1
251         self.rerun_with_valgrind = False
252
253         self.ignore_regexps = TeshState().ignore_regexps_common
254
255     def add_input_pipe(self, line):
256         """ Add a line to stdin input """
257         self.input_pipe.append(line)
258
259     def add_output_pipe_stdout(self, line):
260         """ Add a line to stdout output """
261         self.output_pipe_stdout.append(line)
262
263     def add_output_pipe_stderr(self, line):
264         """ Add a line to stderr output """
265         self.output_pipe_stderr.append(line)
266
267     def set_cmd(self, args, linenumber):
268         """ Set command line """
269         self.args = args
270         self.linenumber = linenumber
271
272     def add_ignore(self, txt):
273         """ Add regexp to ignore lines """
274         self.ignore_regexps.append(re.compile(txt))
275
276     def remove_ignored_lines(self, lines):
277         """ Remove ignored lines """
278         for ign in self.ignore_regexps:
279             lines = [l for l in lines if not ign.match(l)]
280         return lines
281
282     def _cmd_mkfile(self, argline):
283         filename = argline[len("mkfile "):]
284         file = open(filename, "w")
285         if file is None:
286             fatal_error("Unable to create file " + filename)
287         file.write("\n".join(self.input_pipe))
288         file.write("\n")
289         file.close()
290
291     def _cmd_cd(self, argline): # pylint: disable=no-self-use
292         args = shlex.split(argline)
293         if len(args) != 2:
294             fatal_error("Too many arguments to cd")
295         try:
296             os.chdir(args[1])
297             print("[Tesh/INFO] change directory to " + args[1])
298         except FileNotFoundError:
299             print("Chdir to " + args[1] + " failed: No such file or directory")
300             print("Test suite `" + FileReader().filename + "': NOK (system error)")
301             tesh_exit(4)
302
303     def run_if_possible(self):
304         """
305         Run the Cmd if possible.
306         Return False if nothing has been ran.
307         """
308         if not self.can_run():
309             return False
310         if self.background:
311             lock = _thread.allocate_lock()
312             lock.acquire()
313             TeshState().add_thread(lock)
314             _thread.start_new_thread(Cmd._run, (self, lock))
315         else:
316             self._run()
317             if self.rerun_with_valgrind and TeshState().auto_valgrind:
318                 print('\n\n\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
319                 print(      'XXXXXXXXX Rerunning this test with valgrind to help debugging it XXXXXXXXX')
320                 print(      'XXXXXXXX (this will fail if valgrind is not installed, of course) XXXXXXXX')
321                 print(      'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\n\n')
322
323                 self.args = "valgrind " + self.args
324                 self._run()
325         return True
326
327
328     def _run(self, lock=None):
329         # Python threads loose the cwd
330         os.chdir(self.cwd)
331
332         self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
333
334         # replace bash environment variables ($THINGS) to their values
335         self.args = expandvars2(self.args)
336
337         if re.match("^mkfile ", self.args) is not None:
338             self._cmd_mkfile(self.args)
339             if lock is not None:
340                 lock.release()
341             return
342
343         if re.match("^cd ", self.args) is not None:
344             self._cmd_cd(self.args)
345             if lock is not None:
346                 lock.release()
347             return
348
349         if TeshState().wrapper is not None:
350             self.timeout *= 20
351             self.args = TeshState().wrapper + self.args
352         elif re.match(".*smpirun.*", self.args) is not None:
353             self.args = "sh " + self.args
354         if TeshState().jenkins and self.timeout is not None:
355             self.timeout *= 10
356
357         self.args += TeshState().args_suffix
358
359         logs = list()
360         msg = "[{file}:{number}] {args}".format(file=FileReader().filename, number=self.linenumber, args=self.args)
361         if self.background:
362             logs.append(msg)
363         else:
364             print(msg, flush=True)
365
366         args = shlex.split(self.args)
367
368         local_pid = None
369
370         try:
371             preexec_function = lambda: os.setpgid(0, 0)
372             proc = subprocess.Popen( # pylint: disable=subprocess-popen-preexec-fn
373                 args,
374                 bufsize=1,
375                 stdin=subprocess.PIPE,
376                 stdout=subprocess.PIPE,
377                 stderr=subprocess.STDOUT,
378                 universal_newlines=True,
379                 preexec_fn=preexec_function)
380             local_pid = proc.pid
381             TeshState().running_pids.append(local_pid)
382         except PermissionError:
383             logs.append("[{file}:{number}] Cannot start '{cmd}': The binary is not executable.".format(
384                 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
385             logs.append("[{file}:{number}] Current dir: {dir}".format(file=FileReader().filename,
386                                                                       number=self.linenumber, dir=os.getcwd()))
387             TeshState().set_return_code(3)
388             print('\n'.join(logs))
389             return
390         except NotADirectoryError:
391             logs.append("[{file}:{number}] Cannot start '{cmd}': The path to binary does not exist.".format(
392                 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
393             logs.append("[{file}:{number}] Current dir: {dir}".format(file=FileReader().filename,
394                                                                       number=self.linenumber, dir=os.getcwd()))
395             TeshState().set_return_code(3)
396             print('\n'.join(logs))
397             return
398         except FileNotFoundError:
399             logs.append("[{file}:{number}] Cannot start '{cmd}': File not found.".format(
400                 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
401             TeshState().set_return_code(3)
402             print('\n'.join(logs))
403             return
404         except OSError as err:
405             if err.errno == 8:
406                 err.strerror += \
407                     "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/usr/bin/env sh)"
408             raise err
409
410         cmd_name = FileReader().filename + ":" + str(self.linenumber)
411         try:
412             (stdout_data, _stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
413             timeout_reached = False
414         except subprocess.TimeoutExpired:
415             timeout_reached = True
416             logs.append("Test suite `{file}': NOK (<{cmd}> timeout after {timeout} sec)".format(
417                 file=FileReader().filename, cmd=cmd_name, timeout=self.timeout))
418             TeshState().running_pids.remove(local_pid)
419             kill_process_group(local_pid)
420             # Try to get the output of the timeout process, to help in debugging.
421             try:
422                 (stdout_data, _stderr_data) = proc.communicate(timeout=1)
423             except subprocess.TimeoutExpired:
424                 logs.append("[{file}:{number}] Could not retrieve output. Killing the process group failed?".format(
425                     file=FileReader().filename, number=self.linenumber))
426                 TeshState().set_return_code(3)
427                 print('\n'.join(logs))
428                 return
429
430         # remove text colors
431         ansi_escape = re.compile(r'\x1b[^m]*m')
432         stdout_data = ansi_escape.sub('', stdout_data)
433
434         if self.output_display:
435             logs.append(str(stdout_data))
436
437         if self.rerun_with_valgrind:
438             print(str(stdout_data), file=sys.stderr)
439             return
440
441         if self.ignore_output:
442             logs.append("(ignoring the output of <{cmd}> as requested)".format(cmd=cmd_name))
443         else:
444             stdouta = stdout_data.split("\n")
445             stdouta = self.remove_ignored_lines(stdouta)
446             while stdouta and stdouta[-1] == "":
447                 del stdouta[-1]
448             stdcpy = stdouta[:]
449
450             # Mimic the "sort" bash command, which is case unsensitive.
451             if self.sort == 0:
452                 stdouta.sort(key=lambda x: x.lower())
453                 self.output_pipe_stdout.sort(key=lambda x: x.lower())
454             elif self.sort > 0:
455                 stdouta.sort(key=lambda x: x[:self.sort].lower())
456                 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
457
458             diff = list(
459                 difflib.unified_diff(
460                     self.output_pipe_stdout,
461                     stdouta,
462                     lineterm="",
463                     fromfile='expected',
464                     tofile='obtained'))
465             if diff:
466                 logs.append("Output of <{cmd}> mismatch:".format(cmd=cmd_name))
467                 if self.sort >= 0:  # If sorted, truncate the diff output and show the unsorted version
468                     difflen = 0
469                     for line in diff:
470                         if difflen < 50:
471                             print(line)
472                         difflen += 1
473                     if difflen > 50:
474                         logs.append("(diff truncated after 50 lines)")
475                     logs.append("Unsorted observed output:\n")
476                     for line in stdcpy:
477                         logs.append(line)
478                 else:  # If not sorted, just display the diff
479                     for line in diff:
480                         logs.append(line)
481
482                 logs.append("Test suite `{file}': NOK (<{cmd}> output mismatch)".format(
483                     file=FileReader().filename, cmd=cmd_name))
484
485                 # Also report any failed return code and/or signal we got in case of output mismatch
486                 if not proc.returncode in self.expect_return:
487                     if proc.returncode >= 0:
488                         logs.append("In addition, <{cmd}> returned code {code}.".format(
489                             cmd=cmd_name, code=proc.returncode))
490                     else:
491                         logs.append("In addition, <{cmd}> got signal {sig}.".format(cmd=cmd_name,
492                             sig=SIGNALS_TO_NAMES_DICT[-proc.returncode]))
493                     if proc.returncode == -signal.SIGSEGV:
494                         self.rerun_with_valgrind = True
495
496                 if lock is not None:
497                     lock.release()
498                 if TeshState().keep:
499                     file = open('obtained', 'w')
500                     obtained = stdout_data.split("\n")
501                     while obtained and obtained[-1] == "":
502                         del obtained[-1]
503                     obtained = self.remove_ignored_lines(obtained)
504                     for line in obtained:
505                         file.write("> " + line + "\n")
506                     file.close()
507                     logs.append("Obtained output kept as requested: {path}".format(path=os.path.abspath("obtained")))
508                 TeshState().set_return_code(2)
509                 print('\n'.join(logs))
510                 return
511
512         if timeout_reached:
513             TeshState().set_return_code(3)
514             print('\n'.join(logs))
515             return
516
517         if not proc.returncode in self.expect_return:
518             if proc.returncode >= 0:
519                 logs.append("Test suite `{file}': NOK (<{cmd}> returned code {code})".format(
520                     file=FileReader().filename, cmd=cmd_name, code=proc.returncode))
521                 if lock is not None:
522                     lock.release()
523                 TeshState().set_return_code(2)
524                 print('\n'.join(logs))
525                 return
526
527             logs.append("Test suite `{file}': NOK (<{cmd}> got signal {sig})".format(
528                 file=FileReader().filename, cmd=cmd_name,
529                 sig=SIGNALS_TO_NAMES_DICT[-proc.returncode]))
530
531             if proc.returncode == -signal.SIGSEGV:
532                 self.rerun_with_valgrind = True
533
534             if lock is not None:
535                 lock.release()
536             TeshState().set_return_code(max(-proc.returncode, 1))
537             print('\n'.join(logs))
538             return
539
540         if lock is not None:
541             lock.release()
542
543         print('\n'.join(logs))
544
545     def can_run(self):
546         """ Check if ready to run """
547         return self.args is not None
548
549 ##############
550 #
551 # Main
552 #
553 #
554
555 def main():
556     """ main function """
557     signal.signal(signal.SIGINT, signal_handler)
558     signal.signal(signal.SIGTERM, signal_handler)
559
560     parser = argparse.ArgumentParser(description='tesh -- testing shell')
561     group1 = parser.add_argument_group('Options')
562     group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
563     group1.add_argument(
564         '--cd',
565         metavar='some/directory',
566         help='ask tesh to switch the working directory before launching the tests')
567     group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
568     group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line')
569     group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line')
570     group1.add_argument(
571         '--ignore-jenkins',
572         action='store_true',
573         help='ignore all cruft generated on SimGrid continuous integration servers')
574     group1.add_argument(
575         '--no-auto-valgrind',
576         action='store_true',
577         help='do not automaticall launch segfaulting commands in valgrind')
578     group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
579     group1.add_argument(
580         '--keep',
581         action='store_true',
582         help='Keep the obtained output when it does not match the expected one')
583
584     options = parser.parse_args()
585
586     if options.cd is not None:
587         print("[Tesh/INFO] change directory to " + options.cd)
588         os.chdir(options.cd)
589
590     if options.ignore_jenkins:
591         print("Ignore all cruft seen on SimGrid's continuous integration servers")
592         # Note: regexps should match at the beginning of lines
593         TeshState().ignore_regexps_common = [
594             re.compile(r"profiling:"),
595             re.compile(r"Unable to clean temporary file C:"),
596             re.compile(r".*Configuration change: Set 'contexts/"),
597             re.compile(r"==[0-9]+== ?WARNING: ASan doesn't fully support"),
598             re.compile(r"==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack "),
599             re.compile(r"False positive error reports may follow"),
600             re.compile(r"For details see http://code\.google\.com/p/address-sanitizer/issues/detail\?id=189"),
601             re.compile(r"For details see https://github\.com/google/sanitizers/issues/189"),
602             re.compile(r"Python runtime initialized with LC_CTYPE=C .*"),
603             re.compile(r"sthread is intercepting the execution of \.*"),
604             # Seen on CircleCI
605             re.compile(r"cmake: /usr/local/lib/libcurl\.so\.4: no version information available \(required by cmake\)"),
606             re.compile(
607                 r".*mmap broken on FreeBSD, but dlopen\+thread broken too\. Switching to dlopen\+raw contexts\."),
608             re.compile(r".*dlopen\+thread broken on Apple and BSD\. Switching to raw contexts\."),
609         ]
610         TeshState().jenkins = True  # This is a Jenkins build
611
612     if options.no_auto_valgrind:
613         TeshState().auto_valgrind = False
614
615     if options.teshfile is None:
616         file = FileReader(None)
617         print("Test suite from stdin")
618     else:
619         if not os.path.isfile(options.teshfile):
620             print("Cannot open teshfile '" + options.teshfile + "': File not found")
621             tesh_exit(3)
622         file = FileReader(options.teshfile)
623         print("Test suite '" + file.abspath + "'")
624
625     if options.setenv is not None:
626         for env in options.setenv:
627             setenv(env)
628
629     if options.cfg is not None:
630         for cfg in options.cfg:
631             TeshState().args_suffix += " --cfg=" + cfg
632     if options.log is not None:
633         for log in options.log:
634             TeshState().args_suffix += " --log=" + log
635
636     if options.wrapper is not None:
637         TeshState().wrapper = options.wrapper
638
639     if options.keep:
640         TeshState().keep = True
641
642     # cmd holds the current command line
643     # tech commands will add some parameters to it
644     # when ready, we execute it.
645     cmd = Cmd()
646
647     line = file.readfullline()
648     while line is not None:
649         # print(">>============="+line+"==<<")
650         if not line:
651             #print ("END CMD block")
652             if cmd.run_if_possible():
653                 cmd = Cmd()
654
655         elif line[0] == "#":
656             pass
657
658         elif line[0:2] == "p ":
659             print("[" + str(FileReader()) + "] " + line[2:])
660
661         elif line[0:2] == "< ":
662             cmd.add_input_pipe(line[2:])
663         elif line[0:1] == "<":
664             cmd.add_input_pipe(line[1:])
665
666         elif line[0:2] == "> ":
667             cmd.add_output_pipe_stdout(line[2:])
668         elif line[0:1] == ">":
669             cmd.add_output_pipe_stdout(line[1:])
670
671         elif line[0:2] == "$ ":
672             if cmd.run_if_possible():
673                 cmd = Cmd()
674             cmd.set_cmd(line[2:], file.linenumber)
675
676         elif line[0:2] == "& ":
677             if cmd.run_if_possible():
678                 cmd = Cmd()
679             cmd.set_cmd(line[2:], file.linenumber)
680             cmd.background = True
681
682         elif line[0:15] == "! output ignore":
683             cmd.ignore_output = True
684             #print("cmd.ignore_output = True")
685         elif line[0:16] == "! output display":
686             cmd.output_display = True
687             cmd.ignore_output = True
688         elif line[0:15] == "! expect return":
689             try:
690                 cmd.expect_return = [int(line[16:])]
691             except ValueError as err:
692                 fatal_error("Invalid expect return value: \""+(line[16:])+"\"")
693             #print("expect return "+str(int(line[16:])))
694         elif line[0:15] == "! expect signal":
695             cmd.expect_return = []
696             for sig in (line[16:]).split("|"):
697                 # get the signal integer value from the signal module
698                 if sig not in signal.__dict__:
699                     fatal_error("unrecognized signal '" + sig + "'")
700                 sig = int(signal.__dict__[sig])
701                 # popen return -signal when a process ends with a signal
702                 cmd.expect_return.append(-sig)
703         elif line[0:len("! timeout ")] == "! timeout ":
704             if "no" in line[len("! timeout "):]:
705                 cmd.timeout = None
706             else:
707                 try:
708                     cmd.timeout = int(line[len("! timeout "):])
709                 except ValueError as err:
710                     fatal_error("Invalid timeout value: \""+(line[len("! timeout "):])+"\"")
711
712         elif line[0:len("! output sort")] == "! output sort":
713             if len(line) >= len("! output sort "):
714                 try:
715                     sort = int(line[len("! output sort "):])
716                 except ValueError as err:
717                     fatal_error("Invalid sort value: \""+(line[len("! output sort "):])+"\"")
718             else:
719                 sort = 0
720             cmd.sort = sort
721         elif line[0:len("! setenv ")] == "! setenv ":
722             setenv(line[len("! setenv "):])
723
724         elif line[0:len("! ignore ")] == "! ignore ":
725             cmd.add_ignore(line[len("! ignore "):])
726
727         else:
728             fatal_error(f"UNRECOGNIZED OPTION LINE: {line}\n"
729             "Valid requests:\n"
730             "   ! output ignore\n"
731             "   ! output sort\n"
732             "   ! output display\n"
733             "   ! setenv XX=YY\n"
734             "   ! ignore XYZ\n"
735             "   ! expect return NN\n"
736             "   ! expect signal NN\n"
737             "   ! timeout NN\n")
738
739         line = file.readfullline()
740
741     cmd.run_if_possible()
742
743     TeshState().join_all_threads()
744
745     if TeshState().return_code == 0:
746         if file.filename == "(stdin)":
747             print("Test suite from stdin OK")
748         else:
749             print("Test suite `" + file.filename + "' OK")
750     tesh_exit(TeshState().return_code)
751
752 if __name__ == '__main__':
753     main()