2 # -*- coding: utf-8 -*-
6 ========================
8 Copyright (c) 2012-2019. 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.
14 #TODO: child of child of child that printfs. Does it work?
15 #TODO: a child dies after its parent. What happen?
17 #TODO: regular expression in output
18 #ex: >> Time taken: [0-9]+s
19 #TODO: linked regular expression in output
21 # >> Bytes sent: ([0-9]+)
37 if sys.version_info[0] == 3:
41 raise "This program is expected to run with Python3 only"
51 return sys.platform.startswith('win')
53 # Singleton metaclass that works in Python 2 & 3
54 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
57 class _Singleton(type):
58 """ A metaclass that creates a Singleton base class when called. """
61 def __call__(cls, *args, **kwargs):
62 if cls not in cls._instances:
63 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
64 return cls._instances[cls]
67 class Singleton(_Singleton('SingletonMeta', (object,), {})):
71 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n)
72 for n in dir(signal) if n.startswith('SIG') and '_' not in n)
77 def tesh_exit(errcode):
78 # If you do not flush some prints are skipped
80 # os._exit exit even when executed within a thread
85 print("[Tesh/CRITICAL] " + str(msg))
89 # Set an environment variable.
90 # arg must be a string with the format "variable=value"
92 print("[Tesh/INFO] setenv " + arg)
94 os.environ[t[0]] = t[1]
95 # os.putenv(t[0], t[1]) does not work
96 # see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env
99 # http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does
100 def expandvars2(path):
101 return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path))
104 # https://github.com/Cadair/jupyter_environment_kernels/issues/10
109 FileNotFoundError = OSError
117 # Global variable. Stores which process group should be killed (or None otherwise)
118 running_pgids = list()
120 def kill_process_group(pgid):
121 if pgid 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 # print("Kill process group {}".format(pgid))
126 os.killpg(pgid, signal.SIGTERM)
128 # os.killpg failed. OK. Some subprocesses may still be running.
132 def signal_handler(signal, frame):
133 print("Caught signal {}".format(SIGNALS_TO_NAMES_DICT[signal]))
135 running_pgids_copy = running_pgids # Just in case of interthread conflicts.
136 for pgid in running_pgids_copy:
137 kill_process_group(pgid)
138 running_pgids.clear()
149 # read file line per line (and concat line that ends with "\")
150 class FileReader(Singleton):
151 def __init__(self, filename=None):
153 self.filename = "(stdin)"
156 self.filename_raw = filename
157 self.filename = os.path.basename(filename)
158 self.abspath = os.path.abspath(filename)
159 self.f = open(self.filename_raw)
164 return self.filename + ":" + str(self.linenumber)
166 def readfullline(self):
170 except StopIteration:
176 while len(line) > 1 and line[-2] == "\\":
184 # keep the state of tesh (mostly configuration values)
185 class TeshState(Singleton):
188 self.args_suffix = ""
189 self.ignore_regexps_common = []
190 self.jenkins = False # not a Jenkins run by default
191 self.timeout = 10 # default value: 10 sec
195 def add_thread(self, thread):
196 self.threads.append(thread)
198 def join_all_threads(self):
199 for t in self.threads:
203 # Command line object
209 self.output_pipe_stdout = []
210 self.output_pipe_stderr = []
211 self.timeout = TeshState().timeout
215 self.background = False
216 # Python threads loose the cwd
217 self.cwd = os.getcwd()
219 self.ignore_output = False
220 self.expect_return = 0
222 self.output_display = False
226 self.ignore_regexps = TeshState().ignore_regexps_common
228 def add_input_pipe(self, l):
229 self.input_pipe.append(l)
231 def add_output_pipe_stdout(self, l):
232 self.output_pipe_stdout.append(l)
234 def add_output_pipe_stderr(self, l):
235 self.output_pipe_stderr.append(l)
237 def set_cmd(self, args, linenumber):
239 self.linenumber = linenumber
241 def add_ignore(self, txt):
242 self.ignore_regexps.append(re.compile(txt))
244 def remove_ignored_lines(self, lines):
245 for ign in self.ignore_regexps:
246 lines = [l for l in lines if not ign.match(l)]
249 def _cmd_mkfile(self, argline):
250 filename = argline[len("mkfile "):]
251 file = open(filename, "w")
253 fatal_error("Unable to create file " + filename)
254 file.write("\n".join(self.input_pipe))
258 def _cmd_cd(self, argline):
259 args = shlex.split(argline)
261 fatal_error("Too many arguments to cd")
264 print("[Tesh/INFO] change directory to " + args[1])
265 except FileNotFoundError:
266 print("Chdir to " + args[1] + " failed: No such file or directory")
267 print("Test suite `" + FileReader().filename + "': NOK (system error)")
270 # Run the Cmd if possible.
271 # Return False if nothing has been ran.
273 def run_if_possible(self):
276 lock = _thread.allocate_lock()
278 TeshState().add_thread(lock)
279 _thread.start_new_thread(Cmd._run, (self, lock))
286 def _run(self, lock=None):
287 # Python threads loose the cwd
290 # retrocompatibility: support ${aaa:=.} variable format
291 def replace_perl_variables(m):
293 vdefault = m.group(2)
294 if vname in os.environ:
298 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
300 # replace bash environment variables ($THINGS) to their values
301 self.args = expandvars2(self.args)
303 if re.match("^mkfile ", self.args) is not None:
304 self._cmd_mkfile(self.args)
309 if re.match("^cd ", self.args) is not None:
310 self._cmd_cd(self.args)
315 if TeshState().wrapper is not None:
317 self.args = TeshState().wrapper + self.args
318 elif re.match(".*smpirun.*", self.args) is not None:
319 self.args = "sh " + self.args
320 if TeshState().jenkins and self.timeout is not None:
323 self.args += TeshState().args_suffix
325 print("[" + FileReader().filename + ":" + str(self.linenumber) + "] " + self.args)
327 args = shlex.split(self.args)
335 preexec_function = None
337 preexec_function = lambda: os.setpgid(0, 0)
338 proc = subprocess.Popen(
341 stdin=subprocess.PIPE,
342 stdout=subprocess.PIPE,
343 stderr=subprocess.STDOUT,
344 universal_newlines=True,
345 preexec_fn=preexec_function)
348 local_pgid = os.getpgid(proc.pid)
349 running_pgids.append(local_pgid)
351 # os.getpgid failed. OK. No cleanup.
353 except PermissionError:
354 print("[" + FileReader().filename + ":" + str(self.linenumber) +
355 "] Cannot start '" + args[0] + "': The binary is not executable.")
356 print("[" + FileReader().filename + ":" + str(self.linenumber) + "] Current dir: " + os.getcwd())
357 return_code = max(3, return_code)
359 except NotADirectoryError:
360 print("[" + FileReader().filename + ":" + str(self.linenumber) + "] Cannot start '" +
361 args[0] + "': The path to binary does not exist.")
362 print("[" + FileReader().filename + ":" + str(self.linenumber) + "] Current dir: " + os.getcwd())
363 return_code = max(3, return_code)
365 except FileNotFoundError:
366 print("[" + FileReader().filename + ":" + str(self.linenumber) +
367 "] Cannot start '" + args[0] + "': File not found")
368 return_code = max(3, return_code)
370 except OSError as osE:
372 osE.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/usr/bin/env sh)"
375 cmdName = FileReader().filename + ":" + str(self.linenumber)
377 (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
379 timeout_reached = False
380 except subprocess.TimeoutExpired:
381 timeout_reached = True
382 print("Test suite `" + FileReader().filename + "': NOK (<" +
383 cmdName + "> timeout after " + str(self.timeout) + " sec)")
384 running_pgids.remove(local_pgid)
385 kill_process_group(local_pgid)
386 # Try to get the output of the timeout process, to help in debugging.
388 (stdout_data, stderr_data) = proc.communicate(timeout=1)
389 except subprocess.TimeoutExpired:
390 print("[{file}:{number}] Could not retrieve output. Killing the process group failed?".format(
391 file=FileReader().filename, number=self.linenumber))
392 return_code = max(3, return_code)
395 if self.output_display:
399 ansi_escape = re.compile(r'\x1b[^m]*m')
400 stdout_data = ansi_escape.sub('', stdout_data)
402 #print ((stdout_data, stderr_data))
404 if self.ignore_output:
405 print("(ignoring the output of <" + cmdName + "> as requested)")
407 stdouta = stdout_data.split("\n")
408 while len(stdouta) > 0 and stdouta[-1] == "":
410 stdouta = self.remove_ignored_lines(stdouta)
413 # Mimic the "sort" bash command, which is case unsensitive.
415 stdouta.sort(key=lambda x: x.lower())
416 self.output_pipe_stdout.sort(key=lambda x: x.lower())
418 stdouta.sort(key=lambda x: x[:self.sort].lower())
419 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
422 difflib.unified_diff(
423 self.output_pipe_stdout,
429 print("Output of <" + cmdName + "> mismatch:")
430 if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version
437 print("(diff truncated after 50 lines)")
438 print("Unsorted observed output:\n")
441 else: # If not sorted, just display the diff
445 print("Test suite `" + FileReader().filename + "': NOK (<" + cmdName + "> output mismatch)")
449 f = open('obtained', 'w')
450 obtained = stdout_data.split("\n")
451 while len(obtained) > 0 and obtained[-1] == "":
453 obtained = self.remove_ignored_lines(obtained)
454 for line in obtained:
455 f.write("> " + line + "\n")
457 print("Obtained output kept as requested: " + os.path.abspath("obtained"))
458 return_code = max(2, return_code)
462 return_code = max(3, return_code)
465 #print ((proc.returncode, self.expect_return))
467 if proc.returncode != self.expect_return:
468 if proc.returncode >= 0:
469 print("Test suite `" + FileReader().filename + "': NOK (<" +
470 cmdName + "> returned code " + str(proc.returncode) + ")")
473 return_code = max(2, return_code)
476 print("Test suite `" + FileReader().filename + "': NOK (<" + cmdName +
477 "> got signal " + SIGNALS_TO_NAMES_DICT[-proc.returncode] + ")")
480 return_code = max(max(-proc.returncode, 1), return_code)
487 return self.args is not None
497 if __name__ == '__main__':
498 signal.signal(signal.SIGINT, signal_handler)
499 signal.signal(signal.SIGTERM, signal_handler)
501 parser = argparse.ArgumentParser(description='tesh -- testing shell')
502 group1 = parser.add_argument_group('Options')
503 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
506 metavar='some/directory',
507 help='ask tesh to switch the working directory before launching the tests')
508 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
509 group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line')
510 group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line')
514 help='ignore all cruft generated on SimGrid continous integration servers')
515 group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
519 help='Keep the obtained output when it does not match the expected one')
521 options = parser.parse_args()
523 if options.cd is not None:
524 print("[Tesh/INFO] change directory to " + options.cd)
527 if options.ignore_jenkins:
528 print("Ignore all cruft seen on SimGrid's continous integration servers")
529 # Note: regexps should match at the beginning of lines
530 TeshState().ignore_regexps_common = [
531 re.compile(r"profiling:"),
532 re.compile(r"Unable to clean temporary file C:"),
533 re.compile(r".*Configuration change: Set 'contexts/"),
534 re.compile(r"Picked up JAVA_TOOL_OPTIONS: "),
535 re.compile(r"Picked up _JAVA_OPTIONS: "),
536 re.compile(r"==[0-9]+== ?WARNING: ASan doesn't fully support"),
537 re.compile(r"==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack top:"),
538 re.compile(r"False positive error reports may follow"),
539 re.compile(r"For details see http://code.google.com/p/address-sanitizer/issues/detail\?id=189"),
540 re.compile(r"For details see https://github.com/google/sanitizers/issues/189"),
541 re.compile(r"Python runtime initialized with LC_CTYPE=C .*"),
543 re.compile(r"cmake: /usr/local/lib/libcurl\.so\.4: no version information available \(required by cmake\)"),
544 re.compile(r".*mmap broken on FreeBSD, but dlopen\+thread broken too. Switching to dlopen\+raw contexts\."),
545 re.compile(r".*dlopen\+thread broken on Apple and BSD\. Switching to raw contexts\."),
547 TeshState().jenkins = True # This is a Jenkins build
549 if options.teshfile is None:
551 print("Test suite from stdin")
553 if not os.path.isfile(options.teshfile):
554 print("Cannot open teshfile '" + options.teshfile + "': File not found")
556 f = FileReader(options.teshfile)
557 print("Test suite '" + f.abspath + "'")
559 if options.setenv is not None:
560 for e in options.setenv:
563 if options.cfg is not None:
564 for c in options.cfg:
565 TeshState().args_suffix += " --cfg=" + c
566 if options.log is not None:
567 for l in options.log:
568 TeshState().args_suffix += " --log=" + l
570 if options.wrapper is not None:
571 TeshState().wrapper = options.wrapper
574 TeshState().keep = True
576 # cmd holds the current command line
577 # tech commands will add some parameters to it
578 # when ready, we execute it.
581 line = f.readfullline()
582 while line is not None:
583 # print(">>============="+line+"==<<")
585 #print ("END CMD block")
586 if cmd.run_if_possible():
592 elif line[0:2] == "p ":
593 print("[" + str(FileReader()) + "] " + line[2:])
595 elif line[0:2] == "< ":
596 cmd.add_input_pipe(line[2:])
597 elif line[0:1] == "<":
598 cmd.add_input_pipe(line[1:])
600 elif line[0:2] == "> ":
601 cmd.add_output_pipe_stdout(line[2:])
602 elif line[0:1] == ">":
603 cmd.add_output_pipe_stdout(line[1:])
605 elif line[0:2] == "$ ":
606 if cmd.run_if_possible():
608 cmd.set_cmd(line[2:], f.linenumber)
610 elif line[0:2] == "& ":
611 if cmd.run_if_possible():
613 cmd.set_cmd(line[2:], f.linenumber)
614 cmd.background = True
616 elif line[0:15] == "! output ignore":
617 cmd.ignore_output = True
618 #print("cmd.ignore_output = True")
619 elif line[0:16] == "! output display":
620 cmd.output_display = True
621 cmd.ignore_output = True
622 elif line[0:15] == "! expect return":
623 cmd.expect_return = int(line[16:])
624 #print("expect return "+str(int(line[16:])))
625 elif line[0:15] == "! expect signal":
627 # get the signal integer value from the signal module
628 if sig not in signal.__dict__:
629 fatal_error("unrecognized signal '" + sig + "'")
630 sig = int(signal.__dict__[sig])
631 # popen return -signal when a process ends with a signal
632 cmd.expect_return = -sig
633 elif line[0:len("! timeout ")] == "! timeout ":
634 if "no" in line[len("! timeout "):]:
637 cmd.timeout = int(line[len("! timeout "):])
639 elif line[0:len("! output sort")] == "! output sort":
640 if len(line) >= len("! output sort "):
641 sort = int(line[len("! output sort "):])
645 elif line[0:len("! setenv ")] == "! setenv ":
646 setenv(line[len("! setenv "):])
648 elif line[0:len("! ignore ")] == "! ignore ":
649 cmd.add_ignore(line[len("! ignore "):])
652 fatal_error("UNRECOGNIZED OPTION")
654 line = f.readfullline()
656 cmd.run_if_possible()
658 TeshState().join_all_threads()
661 if f.filename == "(stdin)":
662 print("Test suite from stdin OK")
664 print("Test suite `" + f.filename + "' OK")
666 tesh_exit(return_code)