X-Git-Url: http://info.iut-bm.univ-fcomte.fr/pub/gitweb/simgrid.git/blobdiff_plain/5f938fd54b506a7ace8839af4b837ccdb6a69437..cdd4d20278cbee5a9f11f9f455bff8836410568c:/tools/tesh/tesh.py diff --git a/tools/tesh/tesh.py b/tools/tesh/tesh.py index fd5b08836a..2e0d94a37d 100755 --- a/tools/tesh/tesh.py +++ b/tools/tesh/tesh.py @@ -5,7 +5,7 @@ tesh -- testing shell ======================== -Copyright (c) 2012-2017. The SimGrid Team. All rights reserved. +Copyright (c) 2012-2019. The SimGrid Team. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the license (GNU LGPL) which comes with this package. @@ -26,12 +26,14 @@ under the terms of the license (GNU LGPL) which comes with this package. """ -import sys, os +import sys +import os import shlex import re import difflib import signal import argparse +import time if sys.version_info[0] == 3: import subprocess @@ -39,8 +41,6 @@ if sys.version_info[0] == 3: else: raise "This program is expected to run with Python3 only" - - ############## # # Utilities @@ -48,56 +48,117 @@ else: # +def isWindows(): + return sys.platform.startswith('win') + # Singleton metaclass that works in Python 2 & 3 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python + + class _Singleton(type): """ A metaclass that creates a Singleton base class when called. """ _instances = {} + def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] -class Singleton(_Singleton('SingletonMeta', (object,), {})): pass -SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \ - for n in dir(signal) if n.startswith('SIG') and '_' not in n ) +class Singleton(_Singleton('SingletonMeta', (object,), {})): + pass -#exit correctly -def exit(errcode): - #If you do not flush some prints are skipped +SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) + for n in dir(signal) if n.startswith('SIG') and '_' not in n) + +return_code = 0 + +# exit correctly +def tesh_exit(errcode): + # If you do not flush some prints are skipped sys.stdout.flush() - #os._exit exit even when executed within a thread + # os._exit exit even when executed within a thread os._exit(errcode) def fatal_error(msg): - print("[Tesh/CRITICAL] "+str(msg)) - exit(1) + print("[Tesh/CRITICAL] " + str(msg)) + tesh_exit(1) -#Set an environment variable. +# Set an environment variable. # arg must be a string with the format "variable=value" def setenv(arg): - print("[Tesh/INFO] setenv "+arg) - t = arg.split("=") + print("[Tesh/INFO] setenv " + arg) + t = arg.split("=", 1) os.environ[t[0]] = t[1] - #os.putenv(t[0], t[1]) does not work - #see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env + # os.putenv(t[0], t[1]) does not work + # see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env -#http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does +# http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does def expandvars2(path): return re.sub(r'(? timeout after "+str(self.timeout)+" sec)") - proc.kill() - exit(3) + timeout_reached = True + logs.append("Test suite `{file}': NOK (<{cmd}> timeout after {timeout} sec)".format( + file=FileReader().filename, cmd=cmdName, timeout=self.timeout)) + running_pids.remove(local_pid) + kill_process_group(local_pid) + # Try to get the output of the timeout process, to help in debugging. + try: + (stdout_data, stderr_data) = proc.communicate(timeout=1) + except subprocess.TimeoutExpired: + logs.append("[{file}:{number}] Could not retrieve output. Killing the process group failed?".format( + file=FileReader().filename, number=self.linenumber)) + return_code = max(3, return_code) + print('\n'.join(logs)) + return if self.output_display: - print(stdout_data) + logs.append(str(stdout_data)) - #remove text colors + # remove text colors ansi_escape = re.compile(r'\x1b[^m]*m') stdout_data = ansi_escape.sub('', stdout_data) - #print ((stdout_data, stderr_data)) - if self.ignore_output: - print("(ignoring the output of <"+cmdName+"> as requested)") + logs.append("(ignoring the output of <{cmd}> as requested)".format(cmd=cmdName)) else: stdouta = stdout_data.split("\n") while len(stdouta) > 0 and stdouta[-1] == "": @@ -333,60 +440,81 @@ class Cmd(object): stdouta.sort(key=lambda x: x[:self.sort].lower()) self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower()) - diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained')) + diff = list( + difflib.unified_diff( + self.output_pipe_stdout, + stdouta, + lineterm="", + fromfile='expected', + tofile='obtained')) if len(diff) > 0: - print("Output of <"+cmdName+"> mismatch:") - if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version - difflen = 0; + logs.append("Output of <{cmd}> mismatch:".format(cmd=cmdName)) + if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version + difflen = 0 for line in diff: - if difflen<50: + if difflen < 50: print(line) difflen += 1 if difflen > 50: - print("(diff truncated after 50 lines)") - print("Unsorted observed output:\n") + logs.append("(diff truncated after 50 lines)") + logs.append("Unsorted observed output:\n") for line in stdcpy: - print(line) - else: # If not sorted, just display the diff + logs.append(line) + else: # If not sorted, just display the diff for line in diff: - print(line) + logs.append(line) - print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> output mismatch)") - if lock is not None: lock.release() + logs.append("Test suite `{file}': NOK (<{cmd}> output mismatch)".format( + file=FileReader().filename, cmd=cmdName)) + if lock is not None: + lock.release() if TeshState().keep: - f = open('obtained','w') + f = open('obtained', 'w') obtained = stdout_data.split("\n") while len(obtained) > 0 and obtained[-1] == "": del obtained[-1] obtained = self.remove_ignored_lines(obtained) for line in obtained: - f.write("> "+line+"\n") + f.write("> " + line + "\n") f.close() - print("Obtained output kept as requested: "+os.path.abspath("obtained")) - exit(2) - - #print ((proc.returncode, self.expect_return)) + logs.append("Obtained output kept as requested: {path}".format(path=os.path.abspath("obtained"))) + return_code = max(2, return_code) + print('\n'.join(logs)) + return + + if timeout_reached: + return_code = max(3, return_code) + print('\n'.join(logs)) + return - if proc.returncode != self.expect_return: + if not proc.returncode in self.expect_return: if proc.returncode >= 0: - print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> returned code "+str(proc.returncode)+")") - if lock is not None: lock.release() - exit(2) + logs.append("Test suite `{file}': NOK (<{cmd}> returned code {code})".format( + file=FileReader().filename, cmd=cmdName, code=proc.returncode)) + if lock is not None: + lock.release() + return_code = max(2, return_code) + print('\n'.join(logs)) + return else: - print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> got signal "+SIGNALS_TO_NAMES_DICT[-proc.returncode]+")") - if lock is not None: lock.release() - exit(-proc.returncode) - - if lock is not None: lock.release() + logs.append("Test suite `{file}': NOK (<{cmd}> got signal {sig})".format( + file=FileReader().filename, cmd=cmdName, + sig=SIGNALS_TO_NAMES_DICT[-proc.returncode])) + if lock is not None: + lock.release() + return_code = max(max(-proc.returncode, 1), return_code) + print('\n'.join(logs)) + return + if lock is not None: + lock.release() + print('\n'.join(logs)) def can_run(self): return self.args is not None - - ############## # # Main @@ -394,55 +522,67 @@ class Cmd(object): # - if __name__ == '__main__': + signal.signal(signal.SIGINT, signal_handler) + signal.signal(signal.SIGTERM, signal_handler) - parser = argparse.ArgumentParser(description='tesh -- testing shell', add_help=True) + parser = argparse.ArgumentParser(description='tesh -- testing shell') group1 = parser.add_argument_group('Options') group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted') - group1.add_argument('--cd', metavar='some/directory', help='ask tesh to switch the working directory before launching the tests') + group1.add_argument( + '--cd', + metavar='some/directory', + help='ask tesh to switch the working directory before launching the tests') group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable') group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line') group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line') - group1.add_argument('--ignore-jenkins', action='store_true', help='ignore all cruft generated on SimGrid continous integration servers') + group1.add_argument( + '--ignore-jenkins', + action='store_true', + help='ignore all cruft generated on SimGrid continous integration servers') group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)') - group1.add_argument('--keep', action='store_true', help='Keep the obtained output when it does not match the expected one') + group1.add_argument( + '--keep', + action='store_true', + help='Keep the obtained output when it does not match the expected one') - try: - options = parser.parse_args() - except: - exit(1) + options = parser.parse_args() if options.cd is not None: + print("[Tesh/INFO] change directory to " + options.cd) os.chdir(options.cd) if options.ignore_jenkins: print("Ignore all cruft seen on SimGrid's continous integration servers") # Note: regexps should match at the beginning of lines TeshState().ignore_regexps_common = [ - re.compile("profiling:"), - re.compile("Unable to clean temporary file C:"), - re.compile(".*Configuration change: Set \'contexts/"), - re.compile("Picked up JAVA_TOOL_OPTIONS: "), - re.compile("Picked up _JAVA_OPTIONS: "), - re.compile("==[0-9]+== ?WARNING: ASan doesn\'t fully support"), - re.compile("==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack top:"), - re.compile("False positive error reports may follow"), - re.compile("For details see http://code.google.com/p/address-sanitizer/issues/detail\\?id=189"), - re.compile("For details see https://github.com/google/sanitizers/issues/189"), - re.compile("Python runtime initialized with LC_CTYPE=C .*"), - ] - TeshState().jenkins = True # This is a Jenkins build + re.compile(r"profiling:"), + re.compile(r"Unable to clean temporary file C:"), + re.compile(r".*Configuration change: Set 'contexts/"), + re.compile(r"Picked up JAVA_TOOL_OPTIONS: "), + re.compile(r"Picked up _JAVA_OPTIONS: "), + re.compile(r"==[0-9]+== ?WARNING: ASan doesn't fully support"), + re.compile(r"==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack top:"), + re.compile(r"False positive error reports may follow"), + re.compile(r"For details see http://code.google.com/p/address-sanitizer/issues/detail\?id=189"), + re.compile(r"For details see https://github.com/google/sanitizers/issues/189"), + re.compile(r"Python runtime initialized with LC_CTYPE=C .*"), + # Seen on CircleCI + re.compile(r"cmake: /usr/local/lib/libcurl\.so\.4: no version information available \(required by cmake\)"), + re.compile(r".*mmap broken on FreeBSD, but dlopen\+thread broken too. Switching to dlopen\+raw contexts\."), + re.compile(r".*dlopen\+thread broken on Apple and BSD\. Switching to raw contexts\."), + ] + TeshState().jenkins = True # This is a Jenkins build if options.teshfile is None: f = FileReader(None) print("Test suite from stdin") else: if not os.path.isfile(options.teshfile): - print("Cannot open teshfile '"+options.teshfile+"': File not found") - exit(3) + print("Cannot open teshfile '" + options.teshfile + "': File not found") + tesh_exit(3) f = FileReader(options.teshfile) - print("Test suite '"+f.abspath+"'") + print("Test suite '" + f.abspath + "'") if options.setenv is not None: for e in options.setenv: @@ -461,14 +601,14 @@ if __name__ == '__main__': if options.keep: TeshState().keep = True - #cmd holds the current command line + # cmd holds the current command line # tech commands will add some parameters to it # when ready, we execute it. cmd = Cmd() line = f.readfullline() while line is not None: - #print(">>============="+line+"==<<") + # print(">>============="+line+"==<<") if len(line) == 0: #print ("END CMD block") if cmd.run_if_possible(): @@ -478,7 +618,7 @@ if __name__ == '__main__': pass elif line[0:2] == "p ": - print("["+str(FileReader())+"] "+line[2:]) + print("[" + str(FileReader()) + "] " + line[2:]) elif line[0:2] == "< ": cmd.add_input_pipe(line[2:]) @@ -508,16 +648,17 @@ if __name__ == '__main__': cmd.output_display = True cmd.ignore_output = True elif line[0:15] == "! expect return": - cmd.expect_return = int(line[16:]) + cmd.expect_return = [int(line[16:])] #print("expect return "+str(int(line[16:]))) elif line[0:15] == "! expect signal": - sig = line[16:] - #get the signal integer value from the signal module - if sig not in signal.__dict__: - fatal_error("unrecognized signal '"+sig+"'") - sig = int(signal.__dict__[sig]) - #popen return -signal when a process ends with a signal - cmd.expect_return = -sig + cmd.expect_return = [] + for sig in (line[16:]).split("|"): + # get the signal integer value from the signal module + if sig not in signal.__dict__: + fatal_error("unrecognized signal '" + sig + "'") + sig = int(signal.__dict__[sig]) + # popen return -signal when a process ends with a signal + cmd.expect_return.append(-sig) elif line[0:len("! timeout ")] == "! timeout ": if "no" in line[len("! timeout "):]: cmd.timeout = None @@ -539,14 +680,16 @@ if __name__ == '__main__': else: fatal_error("UNRECOGNIZED OPTION") - line = f.readfullline() cmd.run_if_possible() TeshState().join_all_threads() - if f.filename == "(stdin)": - print("Test suite from stdin OK") + if return_code == 0: + if f.filename == "(stdin)": + print("Test suite from stdin OK") + else: + print("Test suite `" + f.filename + "' OK") else: - print("Test suite `"+f.filename+"' OK") + tesh_exit(return_code)