2 # -*- coding: utf-8 -*-
6 ========================
8 Copyright (c) 2012-2020. 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))
99 # https://github.com/Cadair/jupyter_environment_kernels/issues/10
104 FileNotFoundError = OSError
112 # Global variable. Stores which process group should be killed (or None otherwise)
113 running_pids = list()
115 # Tests whether the process is dead already
116 def process_is_dead(pid):
119 except ProcessLookupError:
121 except OSError as err:
122 if err.errno == errno.ESRCH: # ESRCH == No such process. The process is now dead
126 # This function send TERM signal + KILL signal after 0.2s to the group of the specified process
127 def kill_process_group(pid):
128 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
132 pgid = os.getpgid(pid)
134 # os.getpgid failed. Ok, don't cleanup.
138 os.killpg(pgid, signal.SIGTERM)
139 if process_is_dead(pid):
142 os.killpg(pgid, signal.SIGKILL)
144 # os.killpg failed. OK. Some subprocesses may still be running.
147 def signal_handler(signal, frame):
148 print("Caught signal {}".format(SIGNALS_TO_NAMES_DICT[signal]))
150 running_pids_copy = running_pids # Just in case of interthread conflicts.
151 for pid in running_pids_copy:
152 kill_process_group(pid)
164 # read file line per line (and concat line that ends with "\")
165 class FileReader(Singleton):
166 def __init__(self, filename=None):
168 self.filename = "(stdin)"
171 self.filename_raw = filename
172 self.filename = os.path.basename(filename)
173 self.abspath = os.path.abspath(filename)
174 self.f = open(self.filename_raw)
179 return self.filename + ":" + str(self.linenumber)
181 def readfullline(self):
185 except StopIteration:
191 while len(line) > 1 and line[-2] == "\\":
199 # keep the state of tesh (mostly configuration values)
200 class TeshState(Singleton):
203 self.args_suffix = ""
204 self.ignore_regexps_common = []
205 self.jenkins = False # not a Jenkins run by default
206 self.timeout = 10 # default value: 10 sec
210 def add_thread(self, thread):
211 self.threads.append(thread)
213 def join_all_threads(self):
214 for t in self.threads:
218 # Command line object
224 self.output_pipe_stdout = []
225 self.output_pipe_stderr = []
226 self.timeout = TeshState().timeout
230 self.background = False
231 # Python threads loose the cwd
232 self.cwd = os.getcwd()
234 self.ignore_output = False
235 self.expect_return = [0]
237 self.output_display = False
241 self.ignore_regexps = TeshState().ignore_regexps_common
243 def add_input_pipe(self, l):
244 self.input_pipe.append(l)
246 def add_output_pipe_stdout(self, l):
247 self.output_pipe_stdout.append(l)
249 def add_output_pipe_stderr(self, l):
250 self.output_pipe_stderr.append(l)
252 def set_cmd(self, args, linenumber):
254 self.linenumber = linenumber
256 def add_ignore(self, txt):
257 self.ignore_regexps.append(re.compile(txt))
259 def remove_ignored_lines(self, lines):
260 for ign in self.ignore_regexps:
261 lines = [l for l in lines if not ign.match(l)]
264 def _cmd_mkfile(self, argline):
265 filename = argline[len("mkfile "):]
266 file = open(filename, "w")
268 fatal_error("Unable to create file " + filename)
269 file.write("\n".join(self.input_pipe))
273 def _cmd_cd(self, argline):
274 args = shlex.split(argline)
276 fatal_error("Too many arguments to cd")
279 print("[Tesh/INFO] change directory to " + args[1])
280 except FileNotFoundError:
281 print("Chdir to " + args[1] + " failed: No such file or directory")
282 print("Test suite `" + FileReader().filename + "': NOK (system error)")
285 # Run the Cmd if possible.
286 # Return False if nothing has been ran.
288 def run_if_possible(self):
291 lock = _thread.allocate_lock()
293 TeshState().add_thread(lock)
294 _thread.start_new_thread(Cmd._run, (self, lock))
301 def _run(self, lock=None):
302 # Python threads loose the cwd
305 # retrocompatibility: support ${aaa:=.} variable format
306 def replace_perl_variables(m):
308 vdefault = m.group(2)
309 if vname in os.environ:
313 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
315 # replace bash environment variables ($THINGS) to their values
316 self.args = expandvars2(self.args)
318 if re.match("^mkfile ", self.args) is not None:
319 self._cmd_mkfile(self.args)
324 if re.match("^cd ", self.args) is not None:
325 self._cmd_cd(self.args)
330 if TeshState().wrapper is not None:
332 self.args = TeshState().wrapper + self.args
333 elif re.match(".*smpirun.*", self.args) is not None:
334 self.args = "sh " + self.args
335 if TeshState().jenkins and self.timeout is not None:
338 self.args += TeshState().args_suffix
341 logs.append("[{file}:{number}] {args}".format(file=FileReader().filename,
342 number=self.linenumber, args=self.args))
344 args = shlex.split(self.args)
351 preexec_function = None
353 preexec_function = lambda: os.setpgid(0, 0)
354 proc = subprocess.Popen(
357 stdin=subprocess.PIPE,
358 stdout=subprocess.PIPE,
359 stderr=subprocess.STDOUT,
360 universal_newlines=True,
361 preexec_fn=preexec_function)
364 running_pids.append(local_pid)
365 except PermissionError:
366 logs.append("[{file}:{number}] Cannot start '{cmd}': The binary is not executable.".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 NotADirectoryError:
374 logs.append("[{file}:{number}] Cannot start '{cmd}': The path to binary does not exist.".format(
375 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
376 logs.append("[{file}:{number}] Current dir: {dir}".format(file=FileReader().filename,
377 number=self.linenumber, dir=os.getcwd()))
378 return_code = max(3, return_code)
379 print('\n'.join(logs))
381 except FileNotFoundError:
382 logs.append("[{file}:{number}] Cannot start '{cmd}': File not found.".format(
383 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
384 return_code = max(3, return_code)
385 print('\n'.join(logs))
387 except OSError as osE:
389 osE.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/usr/bin/env sh)"
392 cmdName = FileReader().filename + ":" + str(self.linenumber)
394 (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
396 timeout_reached = False
397 except subprocess.TimeoutExpired:
398 timeout_reached = True
399 logs.append("Test suite `{file}': NOK (<{cmd}> timeout after {timeout} sec)".format(
400 file=FileReader().filename, cmd=cmdName, timeout=self.timeout))
401 running_pids.remove(local_pid)
402 kill_process_group(local_pid)
403 # Try to get the output of the timeout process, to help in debugging.
405 (stdout_data, stderr_data) = proc.communicate(timeout=1)
406 except subprocess.TimeoutExpired:
407 logs.append("[{file}:{number}] Could not retrieve output. Killing the process group failed?".format(
408 file=FileReader().filename, number=self.linenumber))
409 return_code = max(3, return_code)
410 print('\n'.join(logs))
413 if self.output_display:
414 logs.append(str(stdout_data))
417 ansi_escape = re.compile(r'\x1b[^m]*m')
418 stdout_data = ansi_escape.sub('', stdout_data)
420 if self.ignore_output:
421 logs.append("(ignoring the output of <{cmd}> as requested)".format(cmd=cmdName))
423 stdouta = stdout_data.split("\n")
424 while stdouta and stdouta[-1] == "":
426 stdouta = self.remove_ignored_lines(stdouta)
429 # Mimic the "sort" bash command, which is case unsensitive.
431 stdouta.sort(key=lambda x: x.lower())
432 self.output_pipe_stdout.sort(key=lambda x: x.lower())
434 stdouta.sort(key=lambda x: x[:self.sort].lower())
435 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
438 difflib.unified_diff(
439 self.output_pipe_stdout,
445 logs.append("Output of <{cmd}> mismatch:".format(cmd=cmdName))
446 if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version
453 logs.append("(diff truncated after 50 lines)")
454 logs.append("Unsorted observed output:\n")
457 else: # If not sorted, just display the diff
461 logs.append("Test suite `{file}': NOK (<{cmd}> output mismatch)".format(
462 file=FileReader().filename, cmd=cmdName))
466 f = open('obtained', 'w')
467 obtained = stdout_data.split("\n")
468 while obtained and obtained[-1] == "":
470 obtained = self.remove_ignored_lines(obtained)
471 for line in obtained:
472 f.write("> " + line + "\n")
474 logs.append("Obtained output kept as requested: {path}".format(path=os.path.abspath("obtained")))
475 return_code = max(2, return_code)
476 print('\n'.join(logs))
480 return_code = max(3, return_code)
481 print('\n'.join(logs))
484 if not proc.returncode in self.expect_return:
485 if proc.returncode >= 0:
486 logs.append("Test suite `{file}': NOK (<{cmd}> returned code {code})".format(
487 file=FileReader().filename, cmd=cmdName, code=proc.returncode))
490 return_code = max(2, return_code)
491 print('\n'.join(logs))
494 logs.append("Test suite `{file}': NOK (<{cmd}> got signal {sig})".format(
495 file=FileReader().filename, cmd=cmdName,
496 sig=SIGNALS_TO_NAMES_DICT[-proc.returncode]))
499 return_code = max(max(-proc.returncode, 1), return_code)
500 print('\n'.join(logs))
506 print('\n'.join(logs))
509 return self.args is not None
517 if __name__ == '__main__':
518 signal.signal(signal.SIGINT, signal_handler)
519 signal.signal(signal.SIGTERM, signal_handler)
521 parser = argparse.ArgumentParser(description='tesh -- testing shell')
522 group1 = parser.add_argument_group('Options')
523 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
526 metavar='some/directory',
527 help='ask tesh to switch the working directory before launching the tests')
528 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
529 group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line')
530 group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line')
534 help='ignore all cruft generated on SimGrid continuous integration servers')
535 group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
539 help='Keep the obtained output when it does not match the expected one')
541 options = parser.parse_args()
543 if options.cd is not None:
544 print("[Tesh/INFO] change directory to " + options.cd)
547 if options.ignore_jenkins:
548 print("Ignore all cruft seen on SimGrid's continuous integration servers")
549 # Note: regexps should match at the beginning of lines
550 TeshState().ignore_regexps_common = [
551 re.compile(r"profiling:"),
552 re.compile(r"Unable to clean temporary file C:"),
553 re.compile(r".*Configuration change: Set 'contexts/"),
554 re.compile(r"Picked up JAVA_TOOL_OPTIONS: "),
555 re.compile(r"Picked up _JAVA_OPTIONS: "),
556 re.compile(r"==[0-9]+== ?WARNING: ASan doesn't fully support"),
557 re.compile(r"==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack top:"),
558 re.compile(r"False positive error reports may follow"),
559 re.compile(r"For details see http://code.google.com/p/address-sanitizer/issues/detail\?id=189"),
560 re.compile(r"For details see https://github.com/google/sanitizers/issues/189"),
561 re.compile(r"Python runtime initialized with LC_CTYPE=C .*"),
563 re.compile(r"cmake: /usr/local/lib/libcurl\.so\.4: no version information available \(required by cmake\)"),
564 re.compile(r".*mmap broken on FreeBSD, but dlopen\+thread broken too. Switching to dlopen\+raw contexts\."),
565 re.compile(r".*dlopen\+thread broken on Apple and BSD\. Switching to raw contexts\."),
567 TeshState().jenkins = True # This is a Jenkins build
569 if options.teshfile is None:
571 print("Test suite from stdin")
573 if not os.path.isfile(options.teshfile):
574 print("Cannot open teshfile '" + options.teshfile + "': File not found")
576 f = FileReader(options.teshfile)
577 print("Test suite '" + f.abspath + "'")
579 if options.setenv is not None:
580 for e in options.setenv:
583 if options.cfg is not None:
584 for c in options.cfg:
585 TeshState().args_suffix += " --cfg=" + c
586 if options.log is not None:
587 for l in options.log:
588 TeshState().args_suffix += " --log=" + l
590 if options.wrapper is not None:
591 TeshState().wrapper = options.wrapper
594 TeshState().keep = True
596 # cmd holds the current command line
597 # tech commands will add some parameters to it
598 # when ready, we execute it.
601 line = f.readfullline()
602 while line is not None:
603 # print(">>============="+line+"==<<")
605 #print ("END CMD block")
606 if cmd.run_if_possible():
612 elif line[0:2] == "p ":
613 print("[" + str(FileReader()) + "] " + line[2:])
615 elif line[0:2] == "< ":
616 cmd.add_input_pipe(line[2:])
617 elif line[0:1] == "<":
618 cmd.add_input_pipe(line[1:])
620 elif line[0:2] == "> ":
621 cmd.add_output_pipe_stdout(line[2:])
622 elif line[0:1] == ">":
623 cmd.add_output_pipe_stdout(line[1:])
625 elif line[0:2] == "$ ":
626 if cmd.run_if_possible():
628 cmd.set_cmd(line[2:], f.linenumber)
630 elif line[0:2] == "& ":
631 if cmd.run_if_possible():
633 cmd.set_cmd(line[2:], f.linenumber)
634 cmd.background = True
636 elif line[0:15] == "! output ignore":
637 cmd.ignore_output = True
638 #print("cmd.ignore_output = True")
639 elif line[0:16] == "! output display":
640 cmd.output_display = True
641 cmd.ignore_output = True
642 elif line[0:15] == "! expect return":
643 cmd.expect_return = [int(line[16:])]
644 #print("expect return "+str(int(line[16:])))
645 elif line[0:15] == "! expect signal":
646 cmd.expect_return = []
647 for sig in (line[16:]).split("|"):
648 # get the signal integer value from the signal module
649 if sig not in signal.__dict__:
650 fatal_error("unrecognized signal '" + sig + "'")
651 sig = int(signal.__dict__[sig])
652 # popen return -signal when a process ends with a signal
653 cmd.expect_return.append(-sig)
654 elif line[0:len("! timeout ")] == "! timeout ":
655 if "no" in line[len("! timeout "):]:
658 cmd.timeout = int(line[len("! timeout "):])
660 elif line[0:len("! output sort")] == "! output sort":
661 if len(line) >= len("! output sort "):
662 sort = int(line[len("! output sort "):])
666 elif line[0:len("! setenv ")] == "! setenv ":
667 setenv(line[len("! setenv "):])
669 elif line[0:len("! ignore ")] == "! ignore ":
670 cmd.add_ignore(line[len("! ignore "):])
673 fatal_error("UNRECOGNIZED OPTION")
675 line = f.readfullline()
677 cmd.run_if_possible()
679 TeshState().join_all_threads()
682 if f.filename == "(stdin)":
683 print("Test suite from stdin OK")
685 print("Test suite `" + f.filename + "' OK")
687 tesh_exit(return_code)