2 # -*- coding: utf-8 -*-
6 ========================
8 Copyright (c) 2012-2022. The SimGrid Team. All rights reserved.
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.
13 #TODO: child of child of child that printfs. Does it work?
14 #TODO: a child dies after its parent. What happen?
16 #TODO: regular expression in output
17 #ex: >> Time taken: [0-9]+s
18 #TODO: linked regular expression in output
20 # >> Bytes sent: ([0-9]+)
36 if sys.version_info[0] == 3:
40 raise "This program is expected to run with Python3 only"
49 return sys.platform.startswith('win')
51 # Singleton metaclass that works in Python 2 & 3
52 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
54 class _Singleton(type):
55 """ A metaclass that creates a Singleton base class when called. """
58 def __call__(cls, *args, **kwargs):
59 if cls not in cls._instances:
60 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
61 return cls._instances[cls]
63 class Singleton(_Singleton('SingletonMeta', (object,), {})):
66 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n)
67 for n in dir(signal) if n.startswith('SIG') and '_' not in n)
72 def tesh_exit(errcode):
73 # If you do not flush some prints are skipped
75 # os._exit exit even when executed within a thread
80 print("[Tesh/CRITICAL] " + str(msg))
84 # Set an environment variable.
85 # arg must be a string with the format "variable=value"
87 print("[Tesh/INFO] setenv " + arg)
89 os.environ[t[0]] = t[1]
90 # os.putenv(t[0], t[1]) does not work
91 # see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env
94 # http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does
95 def expandvars2(path):
96 return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path))
104 # Global variable. Stores which process group should be killed (or None otherwise)
105 running_pids = list()
107 # Tests whether the process is dead already
108 def process_is_dead(pid):
111 except ProcessLookupError:
113 except OSError as err:
114 if err.errno == errno.ESRCH: # ESRCH == No such process. The process is now dead
118 # This function send TERM signal + KILL signal after 0.2s to the group of the specified process
119 def kill_process_group(pid):
120 if pid is None: # Nobody to kill. We don't know who to kill on windows, or we don't have anyone to kill on signal handler
124 pgid = os.getpgid(pid)
126 # os.getpgid failed. Ok, don't cleanup.
130 os.killpg(pgid, signal.SIGTERM)
131 if process_is_dead(pid):
134 os.killpg(pgid, signal.SIGKILL)
136 # os.killpg failed. OK. Some subprocesses may still be running.
139 def signal_handler(signal, frame):
140 print("Caught signal {}".format(SIGNALS_TO_NAMES_DICT[signal]))
142 running_pids_copy = running_pids # Just in case of interthread conflicts.
143 for pid in running_pids_copy:
144 kill_process_group(pid)
156 # read file line per line (and concat line that ends with "\")
157 class FileReader(Singleton):
158 def __init__(self, filename=None):
160 self.filename = "(stdin)"
163 self.filename_raw = filename
164 self.filename = os.path.basename(filename)
165 self.abspath = os.path.abspath(filename)
166 self.f = open(self.filename_raw)
171 return self.filename + ":" + str(self.linenumber)
173 def readfullline(self):
177 except StopIteration:
183 while len(line) > 1 and line[-2] == "\\":
191 # keep the state of tesh (mostly configuration values)
192 class TeshState(Singleton):
195 self.args_suffix = ""
196 self.ignore_regexps_common = []
197 self.jenkins = False # not a Jenkins run by default
198 self.timeout = 10 # default value: 10 sec
202 def add_thread(self, thread):
203 self.threads.append(thread)
205 def join_all_threads(self):
206 for t in self.threads:
210 # Command line object
216 self.output_pipe_stdout = []
217 self.output_pipe_stderr = []
218 self.timeout = TeshState().timeout
222 self.background = False
223 # Python threads loose the cwd
224 self.cwd = os.getcwd()
226 self.ignore_output = False
227 self.expect_return = [0]
229 self.output_display = False
233 self.ignore_regexps = TeshState().ignore_regexps_common
235 def add_input_pipe(self, l):
236 self.input_pipe.append(l)
238 def add_output_pipe_stdout(self, l):
239 self.output_pipe_stdout.append(l)
241 def add_output_pipe_stderr(self, l):
242 self.output_pipe_stderr.append(l)
244 def set_cmd(self, args, linenumber):
246 self.linenumber = linenumber
248 def add_ignore(self, txt):
249 self.ignore_regexps.append(re.compile(txt))
251 def remove_ignored_lines(self, lines):
252 for ign in self.ignore_regexps:
253 lines = [l for l in lines if not ign.match(l)]
256 def _cmd_mkfile(self, argline):
257 filename = argline[len("mkfile "):]
258 file = open(filename, "w")
260 fatal_error("Unable to create file " + filename)
261 file.write("\n".join(self.input_pipe))
265 def _cmd_cd(self, argline):
266 args = shlex.split(argline)
268 fatal_error("Too many arguments to cd")
271 print("[Tesh/INFO] change directory to " + args[1])
272 except FileNotFoundError:
273 print("Chdir to " + args[1] + " failed: No such file or directory")
274 print("Test suite `" + FileReader().filename + "': NOK (system error)")
277 # Run the Cmd if possible.
278 # Return False if nothing has been ran.
280 def run_if_possible(self):
281 if not self.can_run():
284 lock = _thread.allocate_lock()
286 TeshState().add_thread(lock)
287 _thread.start_new_thread(Cmd._run, (self, lock))
292 def _run(self, lock=None):
293 # Python threads loose the cwd
296 # retrocompatibility: support ${aaa:=.} variable format
297 def replace_perl_variables(m):
299 vdefault = m.group(2)
300 if vname in os.environ:
304 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
306 # replace bash environment variables ($THINGS) to their values
307 self.args = expandvars2(self.args)
309 if re.match("^mkfile ", self.args) is not None:
310 self._cmd_mkfile(self.args)
315 if re.match("^cd ", self.args) is not None:
316 self._cmd_cd(self.args)
321 if TeshState().wrapper is not None:
323 self.args = TeshState().wrapper + self.args
324 elif re.match(".*smpirun.*", self.args) is not None:
325 self.args = "sh " + self.args
326 if TeshState().jenkins and self.timeout is not None:
329 self.args += TeshState().args_suffix
332 logs.append("[{file}:{number}] {args}".format(file=FileReader().filename,
333 number=self.linenumber, args=self.args))
335 args = shlex.split(self.args)
342 preexec_function = None
344 preexec_function = lambda: os.setpgid(0, 0)
345 proc = subprocess.Popen(
348 stdin=subprocess.PIPE,
349 stdout=subprocess.PIPE,
350 stderr=subprocess.STDOUT,
351 universal_newlines=True,
352 preexec_fn=preexec_function)
355 running_pids.append(local_pid)
356 except PermissionError:
357 logs.append("[{file}:{number}] Cannot start '{cmd}': The binary is not executable.".format(
358 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
359 logs.append("[{file}:{number}] Current dir: {dir}".format(file=FileReader().filename,
360 number=self.linenumber, dir=os.getcwd()))
361 return_code = max(3, return_code)
362 print('\n'.join(logs))
364 except NotADirectoryError:
365 logs.append("[{file}:{number}] Cannot start '{cmd}': The path to binary does not exist.".format(
366 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
367 logs.append("[{file}:{number}] Current dir: {dir}".format(file=FileReader().filename,
368 number=self.linenumber, dir=os.getcwd()))
369 return_code = max(3, return_code)
370 print('\n'.join(logs))
372 except FileNotFoundError:
373 logs.append("[{file}:{number}] Cannot start '{cmd}': File not found.".format(
374 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
375 return_code = max(3, return_code)
376 print('\n'.join(logs))
378 except OSError as osE:
380 osE.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/usr/bin/env sh)"
383 cmdName = FileReader().filename + ":" + str(self.linenumber)
385 (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
386 timeout_reached = False
387 except subprocess.TimeoutExpired:
388 timeout_reached = True
389 logs.append("Test suite `{file}': NOK (<{cmd}> timeout after {timeout} sec)".format(
390 file=FileReader().filename, cmd=cmdName, timeout=self.timeout))
391 running_pids.remove(local_pid)
392 kill_process_group(local_pid)
393 # Try to get the output of the timeout process, to help in debugging.
395 (stdout_data, stderr_data) = proc.communicate(timeout=1)
396 except subprocess.TimeoutExpired:
397 logs.append("[{file}:{number}] Could not retrieve output. Killing the process group failed?".format(
398 file=FileReader().filename, number=self.linenumber))
399 return_code = max(3, return_code)
400 print('\n'.join(logs))
403 if self.output_display:
404 logs.append(str(stdout_data))
407 ansi_escape = re.compile(r'\x1b[^m]*m')
408 stdout_data = ansi_escape.sub('', stdout_data)
410 if self.ignore_output:
411 logs.append("(ignoring the output of <{cmd}> as requested)".format(cmd=cmdName))
413 stdouta = stdout_data.split("\n")
414 while stdouta and stdouta[-1] == "":
416 stdouta = self.remove_ignored_lines(stdouta)
419 # Mimic the "sort" bash command, which is case unsensitive.
421 stdouta.sort(key=lambda x: x.lower())
422 self.output_pipe_stdout.sort(key=lambda x: x.lower())
424 stdouta.sort(key=lambda x: x[:self.sort].lower())
425 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
428 difflib.unified_diff(
429 self.output_pipe_stdout,
435 logs.append("Output of <{cmd}> mismatch:".format(cmd=cmdName))
436 if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version
443 logs.append("(diff truncated after 50 lines)")
444 logs.append("Unsorted observed output:\n")
447 else: # If not sorted, just display the diff
451 logs.append("Test suite `{file}': NOK (<{cmd}> output mismatch)".format(
452 file=FileReader().filename, cmd=cmdName))
456 f = open('obtained', 'w')
457 obtained = stdout_data.split("\n")
458 while obtained and obtained[-1] == "":
460 obtained = self.remove_ignored_lines(obtained)
461 for line in obtained:
462 f.write("> " + line + "\n")
464 logs.append("Obtained output kept as requested: {path}".format(path=os.path.abspath("obtained")))
465 return_code = max(2, return_code)
466 print('\n'.join(logs))
470 return_code = max(3, return_code)
471 print('\n'.join(logs))
474 if not proc.returncode in self.expect_return:
475 if proc.returncode >= 0:
476 logs.append("Test suite `{file}': NOK (<{cmd}> returned code {code})".format(
477 file=FileReader().filename, cmd=cmdName, code=proc.returncode))
480 return_code = max(2, return_code)
481 print('\n'.join(logs))
484 logs.append("Test suite `{file}': NOK (<{cmd}> got signal {sig})".format(
485 file=FileReader().filename, cmd=cmdName,
486 sig=SIGNALS_TO_NAMES_DICT[-proc.returncode]))
489 return_code = max(max(-proc.returncode, 1), return_code)
490 print('\n'.join(logs))
496 print('\n'.join(logs))
499 return self.args is not None
507 if __name__ == '__main__':
508 signal.signal(signal.SIGINT, signal_handler)
509 signal.signal(signal.SIGTERM, signal_handler)
511 parser = argparse.ArgumentParser(description='tesh -- testing shell')
512 group1 = parser.add_argument_group('Options')
513 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
516 metavar='some/directory',
517 help='ask tesh to switch the working directory before launching the tests')
518 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
519 group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line')
520 group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line')
524 help='ignore all cruft generated on SimGrid continuous integration servers')
525 group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
529 help='Keep the obtained output when it does not match the expected one')
531 options = parser.parse_args()
533 if options.cd is not None:
534 print("[Tesh/INFO] change directory to " + options.cd)
537 if options.ignore_jenkins:
538 print("Ignore all cruft seen on SimGrid's continuous integration servers")
539 # Note: regexps should match at the beginning of lines
540 TeshState().ignore_regexps_common = [
541 re.compile(r"profiling:"),
542 re.compile(r"Unable to clean temporary file C:"),
543 re.compile(r".*Configuration change: Set 'contexts/"),
544 re.compile(r"Picked up JAVA_TOOL_OPTIONS: "),
545 re.compile(r"Picked up _JAVA_OPTIONS: "),
546 re.compile(r"==[0-9]+== ?WARNING: ASan doesn't fully support"),
547 re.compile(r"==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack "),
548 re.compile(r"False positive error reports may follow"),
549 re.compile(r"For details see http://code\.google\.com/p/address-sanitizer/issues/detail\?id=189"),
550 re.compile(r"For details see https://github\.com/google/sanitizers/issues/189"),
551 re.compile(r"Python runtime initialized with LC_CTYPE=C .*"),
553 re.compile(r"cmake: /usr/local/lib/libcurl\.so\.4: no version information available \(required by cmake\)"),
554 re.compile(r".*mmap broken on FreeBSD, but dlopen\+thread broken too\. Switching to dlopen\+raw contexts\."),
555 re.compile(r".*dlopen\+thread broken on Apple and BSD\. Switching to raw contexts\."),
557 TeshState().jenkins = True # This is a Jenkins build
559 if options.teshfile is None:
561 print("Test suite from stdin")
563 if not os.path.isfile(options.teshfile):
564 print("Cannot open teshfile '" + options.teshfile + "': File not found")
566 f = FileReader(options.teshfile)
567 print("Test suite '" + f.abspath + "'")
569 if options.setenv is not None:
570 for e in options.setenv:
573 if options.cfg is not None:
574 for c in options.cfg:
575 TeshState().args_suffix += " --cfg=" + c
576 if options.log is not None:
577 for l in options.log:
578 TeshState().args_suffix += " --log=" + l
580 if options.wrapper is not None:
581 TeshState().wrapper = options.wrapper
584 TeshState().keep = True
586 # cmd holds the current command line
587 # tech commands will add some parameters to it
588 # when ready, we execute it.
591 line = f.readfullline()
592 while line is not None:
593 # print(">>============="+line+"==<<")
595 #print ("END CMD block")
596 if cmd.run_if_possible():
602 elif line[0:2] == "p ":
603 print("[" + str(FileReader()) + "] " + line[2:])
605 elif line[0:2] == "< ":
606 cmd.add_input_pipe(line[2:])
607 elif line[0:1] == "<":
608 cmd.add_input_pipe(line[1:])
610 elif line[0:2] == "> ":
611 cmd.add_output_pipe_stdout(line[2:])
612 elif line[0:1] == ">":
613 cmd.add_output_pipe_stdout(line[1:])
615 elif line[0:2] == "$ ":
616 if cmd.run_if_possible():
618 cmd.set_cmd(line[2:], f.linenumber)
620 elif line[0:2] == "& ":
621 if cmd.run_if_possible():
623 cmd.set_cmd(line[2:], f.linenumber)
624 cmd.background = True
626 elif line[0:15] == "! output ignore":
627 cmd.ignore_output = True
628 #print("cmd.ignore_output = True")
629 elif line[0:16] == "! output display":
630 cmd.output_display = True
631 cmd.ignore_output = True
632 elif line[0:15] == "! expect return":
633 cmd.expect_return = [int(line[16:])]
634 #print("expect return "+str(int(line[16:])))
635 elif line[0:15] == "! expect signal":
636 cmd.expect_return = []
637 for sig in (line[16:]).split("|"):
638 # get the signal integer value from the signal module
639 if sig not in signal.__dict__:
640 fatal_error("unrecognized signal '" + sig + "'")
641 sig = int(signal.__dict__[sig])
642 # popen return -signal when a process ends with a signal
643 cmd.expect_return.append(-sig)
644 elif line[0:len("! timeout ")] == "! timeout ":
645 if "no" in line[len("! timeout "):]:
648 cmd.timeout = int(line[len("! timeout "):])
650 elif line[0:len("! output sort")] == "! output sort":
651 if len(line) >= len("! output sort "):
652 sort = int(line[len("! output sort "):])
656 elif line[0:len("! setenv ")] == "! setenv ":
657 setenv(line[len("! setenv "):])
659 elif line[0:len("! ignore ")] == "! ignore ":
660 cmd.add_ignore(line[len("! ignore "):])
663 fatal_error("UNRECOGNIZED OPTION")
665 line = f.readfullline()
667 cmd.run_if_possible()
669 TeshState().join_all_threads()
672 if f.filename == "(stdin)":
673 print("Test suite from stdin OK")
675 print("Test suite `" + f.filename + "' OK")
676 tesh_exit(return_code)