Logo AND Algorithmique Numérique Distribuée

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