2 # -*- coding: utf-8 -*-
6 ========================
8 Copyright (c) 2012-2021. 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):
283 lock = _thread.allocate_lock()
285 TeshState().add_thread(lock)
286 _thread.start_new_thread(Cmd._run, (self, lock))
293 def _run(self, lock=None):
294 # Python threads loose the cwd
297 # retrocompatibility: support ${aaa:=.} variable format
298 def replace_perl_variables(m):
300 vdefault = m.group(2)
301 if vname in os.environ:
305 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
307 # replace bash environment variables ($THINGS) to their values
308 self.args = expandvars2(self.args)
310 if re.match("^mkfile ", self.args) is not None:
311 self._cmd_mkfile(self.args)
316 if re.match("^cd ", self.args) is not None:
317 self._cmd_cd(self.args)
322 if TeshState().wrapper is not None:
324 self.args = TeshState().wrapper + self.args
325 elif re.match(".*smpirun.*", self.args) is not None:
326 self.args = "sh " + self.args
327 if TeshState().jenkins and self.timeout is not None:
330 self.args += TeshState().args_suffix
333 logs.append("[{file}:{number}] {args}".format(file=FileReader().filename,
334 number=self.linenumber, args=self.args))
336 args = shlex.split(self.args)
343 preexec_function = None
345 preexec_function = lambda: os.setpgid(0, 0)
346 proc = subprocess.Popen(
349 stdin=subprocess.PIPE,
350 stdout=subprocess.PIPE,
351 stderr=subprocess.STDOUT,
352 universal_newlines=True,
353 preexec_fn=preexec_function)
356 running_pids.append(local_pid)
357 except PermissionError:
358 logs.append("[{file}:{number}] Cannot start '{cmd}': The binary is not executable.".format(
359 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
360 logs.append("[{file}:{number}] Current dir: {dir}".format(file=FileReader().filename,
361 number=self.linenumber, dir=os.getcwd()))
362 return_code = max(3, return_code)
363 print('\n'.join(logs))
365 except NotADirectoryError:
366 logs.append("[{file}:{number}] Cannot start '{cmd}': The path to binary does not exist.".format(
367 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
368 logs.append("[{file}:{number}] Current dir: {dir}".format(file=FileReader().filename,
369 number=self.linenumber, dir=os.getcwd()))
370 return_code = max(3, return_code)
371 print('\n'.join(logs))
373 except FileNotFoundError:
374 logs.append("[{file}:{number}] Cannot start '{cmd}': File not found.".format(
375 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
376 return_code = max(3, return_code)
377 print('\n'.join(logs))
379 except OSError as osE:
381 osE.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/usr/bin/env sh)"
384 cmdName = FileReader().filename + ":" + str(self.linenumber)
386 (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
388 timeout_reached = False
389 except subprocess.TimeoutExpired:
390 timeout_reached = True
391 logs.append("Test suite `{file}': NOK (<{cmd}> timeout after {timeout} sec)".format(
392 file=FileReader().filename, cmd=cmdName, timeout=self.timeout))
393 running_pids.remove(local_pid)
394 kill_process_group(local_pid)
395 # Try to get the output of the timeout process, to help in debugging.
397 (stdout_data, stderr_data) = proc.communicate(timeout=1)
398 except subprocess.TimeoutExpired:
399 logs.append("[{file}:{number}] Could not retrieve output. Killing the process group failed?".format(
400 file=FileReader().filename, number=self.linenumber))
401 return_code = max(3, return_code)
402 print('\n'.join(logs))
405 if self.output_display:
406 logs.append(str(stdout_data))
409 ansi_escape = re.compile(r'\x1b[^m]*m')
410 stdout_data = ansi_escape.sub('', stdout_data)
412 if self.ignore_output:
413 logs.append("(ignoring the output of <{cmd}> as requested)".format(cmd=cmdName))
415 stdouta = stdout_data.split("\n")
416 while stdouta and stdouta[-1] == "":
418 stdouta = self.remove_ignored_lines(stdouta)
421 # Mimic the "sort" bash command, which is case unsensitive.
423 stdouta.sort(key=lambda x: x.lower())
424 self.output_pipe_stdout.sort(key=lambda x: x.lower())
426 stdouta.sort(key=lambda x: x[:self.sort].lower())
427 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
430 difflib.unified_diff(
431 self.output_pipe_stdout,
437 logs.append("Output of <{cmd}> mismatch:".format(cmd=cmdName))
438 if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version
445 logs.append("(diff truncated after 50 lines)")
446 logs.append("Unsorted observed output:\n")
449 else: # If not sorted, just display the diff
453 logs.append("Test suite `{file}': NOK (<{cmd}> output mismatch)".format(
454 file=FileReader().filename, cmd=cmdName))
458 f = open('obtained', 'w')
459 obtained = stdout_data.split("\n")
460 while obtained and obtained[-1] == "":
462 obtained = self.remove_ignored_lines(obtained)
463 for line in obtained:
464 f.write("> " + line + "\n")
466 logs.append("Obtained output kept as requested: {path}".format(path=os.path.abspath("obtained")))
467 return_code = max(2, return_code)
468 print('\n'.join(logs))
472 return_code = max(3, return_code)
473 print('\n'.join(logs))
476 if not proc.returncode in self.expect_return:
477 if proc.returncode >= 0:
478 logs.append("Test suite `{file}': NOK (<{cmd}> returned code {code})".format(
479 file=FileReader().filename, cmd=cmdName, code=proc.returncode))
482 return_code = max(2, return_code)
483 print('\n'.join(logs))
486 logs.append("Test suite `{file}': NOK (<{cmd}> got signal {sig})".format(
487 file=FileReader().filename, cmd=cmdName,
488 sig=SIGNALS_TO_NAMES_DICT[-proc.returncode]))
491 return_code = max(max(-proc.returncode, 1), return_code)
492 print('\n'.join(logs))
498 print('\n'.join(logs))
501 return self.args is not None
509 if __name__ == '__main__':
510 signal.signal(signal.SIGINT, signal_handler)
511 signal.signal(signal.SIGTERM, signal_handler)
513 parser = argparse.ArgumentParser(description='tesh -- testing shell')
514 group1 = parser.add_argument_group('Options')
515 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
518 metavar='some/directory',
519 help='ask tesh to switch the working directory before launching the tests')
520 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
521 group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line')
522 group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line')
526 help='ignore all cruft generated on SimGrid continuous integration servers')
527 group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
531 help='Keep the obtained output when it does not match the expected one')
533 options = parser.parse_args()
535 if options.cd is not None:
536 print("[Tesh/INFO] change directory to " + options.cd)
539 if options.ignore_jenkins:
540 print("Ignore all cruft seen on SimGrid's continuous integration servers")
541 # Note: regexps should match at the beginning of lines
542 TeshState().ignore_regexps_common = [
543 re.compile(r"profiling:"),
544 re.compile(r"Unable to clean temporary file C:"),
545 re.compile(r".*Configuration change: Set 'contexts/"),
546 re.compile(r"Picked up JAVA_TOOL_OPTIONS: "),
547 re.compile(r"Picked up _JAVA_OPTIONS: "),
548 re.compile(r"==[0-9]+== ?WARNING: ASan doesn't fully support"),
549 re.compile(r"==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack top:"),
550 re.compile(r"False positive error reports may follow"),
551 re.compile(r"For details see http://code\.google\.com/p/address-sanitizer/issues/detail\?id=189"),
552 re.compile(r"For details see https://github\.com/google/sanitizers/issues/189"),
553 re.compile(r"Python runtime initialized with LC_CTYPE=C .*"),
555 re.compile(r"cmake: /usr/local/lib/libcurl\.so\.4: no version information available \(required by cmake\)"),
556 re.compile(r".*mmap broken on FreeBSD, but dlopen\+thread broken too\. Switching to dlopen\+raw contexts\."),
557 re.compile(r".*dlopen\+thread broken on Apple and BSD\. Switching to raw contexts\."),
559 TeshState().jenkins = True # This is a Jenkins build
561 if options.teshfile is None:
563 print("Test suite from stdin")
565 if not os.path.isfile(options.teshfile):
566 print("Cannot open teshfile '" + options.teshfile + "': File not found")
568 f = FileReader(options.teshfile)
569 print("Test suite '" + f.abspath + "'")
571 if options.setenv is not None:
572 for e in options.setenv:
575 if options.cfg is not None:
576 for c in options.cfg:
577 TeshState().args_suffix += " --cfg=" + c
578 if options.log is not None:
579 for l in options.log:
580 TeshState().args_suffix += " --log=" + l
582 if options.wrapper is not None:
583 TeshState().wrapper = options.wrapper
586 TeshState().keep = True
588 # cmd holds the current command line
589 # tech commands will add some parameters to it
590 # when ready, we execute it.
593 line = f.readfullline()
594 while line is not None:
595 # print(">>============="+line+"==<<")
597 #print ("END CMD block")
598 if cmd.run_if_possible():
604 elif line[0:2] == "p ":
605 print("[" + str(FileReader()) + "] " + line[2:])
607 elif line[0:2] == "< ":
608 cmd.add_input_pipe(line[2:])
609 elif line[0:1] == "<":
610 cmd.add_input_pipe(line[1:])
612 elif line[0:2] == "> ":
613 cmd.add_output_pipe_stdout(line[2:])
614 elif line[0:1] == ">":
615 cmd.add_output_pipe_stdout(line[1:])
617 elif line[0:2] == "$ ":
618 if cmd.run_if_possible():
620 cmd.set_cmd(line[2:], f.linenumber)
622 elif line[0:2] == "& ":
623 if cmd.run_if_possible():
625 cmd.set_cmd(line[2:], f.linenumber)
626 cmd.background = True
628 elif line[0:15] == "! output ignore":
629 cmd.ignore_output = True
630 #print("cmd.ignore_output = True")
631 elif line[0:16] == "! output display":
632 cmd.output_display = True
633 cmd.ignore_output = True
634 elif line[0:15] == "! expect return":
635 cmd.expect_return = [int(line[16:])]
636 #print("expect return "+str(int(line[16:])))
637 elif line[0:15] == "! expect signal":
638 cmd.expect_return = []
639 for sig in (line[16:]).split("|"):
640 # get the signal integer value from the signal module
641 if sig not in signal.__dict__:
642 fatal_error("unrecognized signal '" + sig + "'")
643 sig = int(signal.__dict__[sig])
644 # popen return -signal when a process ends with a signal
645 cmd.expect_return.append(-sig)
646 elif line[0:len("! timeout ")] == "! timeout ":
647 if "no" in line[len("! timeout "):]:
650 cmd.timeout = int(line[len("! timeout "):])
652 elif line[0:len("! output sort")] == "! output sort":
653 if len(line) >= len("! output sort "):
654 sort = int(line[len("! output sort "):])
658 elif line[0:len("! setenv ")] == "! setenv ":
659 setenv(line[len("! setenv "):])
661 elif line[0:len("! ignore ")] == "! ignore ":
662 cmd.add_ignore(line[len("! ignore "):])
665 fatal_error("UNRECOGNIZED OPTION")
667 line = f.readfullline()
669 cmd.run_if_possible()
671 TeshState().join_all_threads()
674 if f.filename == "(stdin)":
675 print("Test suite from stdin OK")
677 print("Test suite `" + f.filename + "' OK")
679 tesh_exit(return_code)