2 # -*- coding: utf-8 -*-
6 ========================
8 Copyright (c) 2012-2017. 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]+)
36 if sys.version_info[0] == 3:
40 raise "This program is expected to run with Python3 only"
49 # Singleton metaclass that works in Python 2 & 3
50 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
51 class _Singleton(type):
52 """ A metaclass that creates a Singleton base class when called. """
54 def __call__(cls, *args, **kwargs):
55 if cls not in cls._instances:
56 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
57 return cls._instances[cls]
58 class Singleton(_Singleton('SingletonMeta', (object,), {})): pass
60 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
61 for n in dir(signal) if n.startswith('SIG') and '_' not in n )
66 def tesh_exit(errcode):
67 #If you do not flush some prints are skipped
69 #os._exit exit even when executed within a thread
74 print("[Tesh/CRITICAL] "+str(msg))
78 #Set an environment variable.
79 # arg must be a string with the format "variable=value"
81 print("[Tesh/INFO] setenv "+arg)
83 os.environ[t[0]] = t[1]
84 #os.putenv(t[0], t[1]) does not work
85 #see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env
88 #http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does
89 def expandvars2(path):
90 return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path))
92 # https://github.com/Cadair/jupyter_environment_kernels/issues/10
97 FileNotFoundError = OSError
105 # Global variable. Stores which process group should be killed (or None otherwise)
108 def kill_process_group(pgid):
109 # print("Kill process group {}".format(pgid))
111 os.killpg(pgid, signal.SIGTERM)
112 except: # Ugly and psychorigid. Please improve python doc so we know what exceptions killpg can throw.
115 def signal_handler(signal, frame):
116 print("Caught signal {}".format(SIGNALS_TO_NAMES_DICT[signal]))
117 if pgtokill is not None:
118 kill_process_group(pgtokill)
131 # read file line per line (and concat line that ends with "\")
132 class FileReader(Singleton):
133 def __init__(self, filename=None):
135 self.filename = "(stdin)"
138 self.filename_raw = filename
139 self.filename = os.path.basename(filename)
140 self.abspath = os.path.abspath(filename)
141 self.f = open(self.filename_raw)
146 return self.filename+":"+str(self.linenumber)
148 def readfullline(self):
152 except StopIteration:
158 while len(line) > 1 and line[-2] == "\\":
166 #keep the state of tesh (mostly configuration values)
167 class TeshState(Singleton):
170 self.args_suffix = ""
171 self.ignore_regexps_common = []
172 self.jenkins = False # not a Jenkins run by default
173 self.timeout = 10 # default value: 10 sec
177 def add_thread(self, thread):
178 self.threads.append(thread)
180 def join_all_threads(self):
181 for t in self.threads:
189 self.output_pipe_stdout = []
190 self.output_pipe_stderr = []
191 self.timeout = TeshState().timeout
195 self.background = False
198 self.ignore_output = False
199 self.expect_return = 0
201 self.output_display = False
205 self.ignore_regexps = TeshState().ignore_regexps_common
207 def add_input_pipe(self, l):
208 self.input_pipe.append(l)
210 def add_output_pipe_stdout(self, l):
211 self.output_pipe_stdout.append(l)
213 def add_output_pipe_stderr(self, l):
214 self.output_pipe_stderr.append(l)
216 def set_cmd(self, args, linenumber):
218 self.linenumber = linenumber
220 def add_ignore(self, txt):
221 self.ignore_regexps.append(re.compile(txt))
223 def remove_ignored_lines(self, lines):
224 for ign in self.ignore_regexps:
225 lines = [l for l in lines if not ign.match(l)]
229 def _cmd_mkfile(self, argline):
230 filename = argline[len("mkfile "):]
231 file = open(filename, "w")
233 fatal_error("Unable to create file "+filename)
234 file.write("\n".join(self.input_pipe))
238 def _cmd_cd(self, argline):
239 args = shlex.split(argline)
241 fatal_error("Too many arguments to cd")
244 print("[Tesh/INFO] change directory to "+args[1])
245 except FileNotFoundError:
246 print("Chdir to "+args[1]+" failed: No such file or directory")
247 print("Test suite `"+FileReader().filename+"': NOK (system error)")
251 #Run the Cmd if possible.
252 # Return False if nothing has been ran.
253 def run_if_possible(self):
256 #Python threads loose the cwd
257 self.cwd = os.getcwd()
258 lock = _thread.allocate_lock()
260 TeshState().add_thread(lock)
261 _thread.start_new_thread( Cmd._run, (self, lock) )
269 def _run(self, lock=None):
270 #Python threads loose the cwd
271 if self.cwd is not None:
275 #retrocompatibility: support ${aaa:=.} variable format
276 def replace_perl_variables(m):
278 vdefault = m.group(2)
279 if vname in os.environ:
283 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
285 #replace bash environment variables ($THINGS) to their values
286 self.args = expandvars2(self.args)
288 if re.match("^mkfile ", self.args) is not None:
289 self._cmd_mkfile(self.args)
290 if lock is not None: lock.release()
293 if re.match("^cd ", self.args) is not None:
294 self._cmd_cd(self.args)
295 if lock is not None: lock.release()
298 if TeshState().wrapper is not None:
300 self.args = TeshState().wrapper + self.args
301 elif re.match(".*smpirun.*", self.args) is not None:
302 self.args = "sh " + self.args
303 if TeshState().jenkins and self.timeout != None:
306 self.args += TeshState().args_suffix
308 print("["+FileReader().filename+":"+str(self.linenumber)+"] "+self.args)
310 args = shlex.split(self.args)
316 proc = subprocess.Popen(args, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, preexec_fn=os.setsid)
318 pgtokill = os.getpgid(proc.pid)
319 except: # Ugly and psychorigid. Please improve python doc so we know what exceptions getpgid can throw.
320 # os.getpgid failed. OK, no cleanup.
322 except FileNotFoundError:
323 print("["+FileReader().filename+":"+str(self.linenumber)+"] Cannot start '"+args[0]+"': File not found")
325 except OSError as osE:
327 osE.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/usr/bin/env sh)"
330 cmdName = FileReader().filename+":"+str(self.linenumber)
332 (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
334 except subprocess.TimeoutExpired:
335 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> timeout after "+str(self.timeout)+" sec)")
336 kill_process_group(pgtokill)
339 if self.output_display:
343 ansi_escape = re.compile(r'\x1b[^m]*m')
344 stdout_data = ansi_escape.sub('', stdout_data)
346 #print ((stdout_data, stderr_data))
348 if self.ignore_output:
349 print("(ignoring the output of <"+cmdName+"> as requested)")
351 stdouta = stdout_data.split("\n")
352 while len(stdouta) > 0 and stdouta[-1] == "":
354 stdouta = self.remove_ignored_lines(stdouta)
357 # Mimic the "sort" bash command, which is case unsensitive.
359 stdouta.sort(key=lambda x: x.lower())
360 self.output_pipe_stdout.sort(key=lambda x: x.lower())
362 stdouta.sort(key=lambda x: x[:self.sort].lower())
363 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
365 diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained'))
367 print("Output of <"+cmdName+"> mismatch:")
368 if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version
375 print("(diff truncated after 50 lines)")
376 print("Unsorted observed output:\n")
379 else: # If not sorted, just display the diff
383 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> output mismatch)")
384 if lock is not None: lock.release()
386 f = open('obtained','w')
387 obtained = stdout_data.split("\n")
388 while len(obtained) > 0 and obtained[-1] == "":
390 obtained = self.remove_ignored_lines(obtained)
391 for line in obtained:
392 f.write("> "+line+"\n")
394 print("Obtained output kept as requested: "+os.path.abspath("obtained"))
397 #print ((proc.returncode, self.expect_return))
399 if proc.returncode != self.expect_return:
400 if proc.returncode >= 0:
401 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> returned code "+str(proc.returncode)+")")
402 if lock is not None: lock.release()
405 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> got signal "+SIGNALS_TO_NAMES_DICT[-proc.returncode]+")")
406 if lock is not None: lock.release()
407 tesh_exit(-proc.returncode)
409 if lock is not None: lock.release()
414 return self.args is not None
427 if __name__ == '__main__':
428 signal.signal(signal.SIGINT, signal_handler)
429 signal.signal(signal.SIGTERM, signal_handler)
431 parser = argparse.ArgumentParser(description='tesh -- testing shell', add_help=True)
432 group1 = parser.add_argument_group('Options')
433 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
434 group1.add_argument('--cd', metavar='some/directory', help='ask tesh to switch the working directory before launching the tests')
435 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
436 group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line')
437 group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line')
438 group1.add_argument('--ignore-jenkins', action='store_true', help='ignore all cruft generated on SimGrid continous integration servers')
439 group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
440 group1.add_argument('--keep', action='store_true', help='Keep the obtained output when it does not match the expected one')
443 options = parser.parse_args()
447 if options.cd is not None:
448 print("[Tesh/INFO] change directory to " + options.cd)
451 if options.ignore_jenkins:
452 print("Ignore all cruft seen on SimGrid's continous integration servers")
453 # Note: regexps should match at the beginning of lines
454 TeshState().ignore_regexps_common = [
455 re.compile("profiling:"),
456 re.compile("Unable to clean temporary file C:"),
457 re.compile(".*Configuration change: Set \'contexts/"),
458 re.compile("Picked up JAVA_TOOL_OPTIONS: "),
459 re.compile("Picked up _JAVA_OPTIONS: "),
460 re.compile("==[0-9]+== ?WARNING: ASan doesn\'t fully support"),
461 re.compile("==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack top:"),
462 re.compile("False positive error reports may follow"),
463 re.compile("For details see http://code.google.com/p/address-sanitizer/issues/detail\\?id=189"),
464 re.compile("For details see https://github.com/google/sanitizers/issues/189"),
465 re.compile("Python runtime initialized with LC_CTYPE=C .*"),
466 re.compile("cmake: /usr/local/lib/libcurl.so.4: no version information available (required by cmake)"), # Seen on CircleCI
468 TeshState().jenkins = True # This is a Jenkins build
470 if options.teshfile is None:
472 print("Test suite from stdin")
474 if not os.path.isfile(options.teshfile):
475 print("Cannot open teshfile '"+options.teshfile+"': File not found")
477 f = FileReader(options.teshfile)
478 print("Test suite '"+f.abspath+"'")
480 if options.setenv is not None:
481 for e in options.setenv:
484 if options.cfg is not None:
485 for c in options.cfg:
486 TeshState().args_suffix += " --cfg=" + c
487 if options.log is not None:
488 for l in options.log:
489 TeshState().args_suffix += " --log=" + l
491 if options.wrapper is not None:
492 TeshState().wrapper = options.wrapper
495 TeshState().keep = True
497 #cmd holds the current command line
498 # tech commands will add some parameters to it
499 # when ready, we execute it.
502 line = f.readfullline()
503 while line is not None:
504 #print(">>============="+line+"==<<")
506 #print ("END CMD block")
507 if cmd.run_if_possible():
513 elif line[0:2] == "p ":
514 print("["+str(FileReader())+"] "+line[2:])
516 elif line[0:2] == "< ":
517 cmd.add_input_pipe(line[2:])
518 elif line[0:1] == "<":
519 cmd.add_input_pipe(line[1:])
521 elif line[0:2] == "> ":
522 cmd.add_output_pipe_stdout(line[2:])
523 elif line[0:1] == ">":
524 cmd.add_output_pipe_stdout(line[1:])
526 elif line[0:2] == "$ ":
527 if cmd.run_if_possible():
529 cmd.set_cmd(line[2:], f.linenumber)
531 elif line[0:2] == "& ":
532 if cmd.run_if_possible():
534 cmd.set_cmd(line[2:], f.linenumber)
535 cmd.background = True
537 elif line[0:15] == "! output ignore":
538 cmd.ignore_output = True
539 #print("cmd.ignore_output = True")
540 elif line[0:16] == "! output display":
541 cmd.output_display = True
542 cmd.ignore_output = True
543 elif line[0:15] == "! expect return":
544 cmd.expect_return = int(line[16:])
545 #print("expect return "+str(int(line[16:])))
546 elif line[0:15] == "! expect signal":
548 #get the signal integer value from the signal module
549 if sig not in signal.__dict__:
550 fatal_error("unrecognized signal '"+sig+"'")
551 sig = int(signal.__dict__[sig])
552 #popen return -signal when a process ends with a signal
553 cmd.expect_return = -sig
554 elif line[0:len("! timeout ")] == "! timeout ":
555 if "no" in line[len("! timeout "):]:
558 cmd.timeout = int(line[len("! timeout "):])
560 elif line[0:len("! output sort")] == "! output sort":
561 if len(line) >= len("! output sort "):
562 sort = int(line[len("! output sort "):])
566 elif line[0:len("! setenv ")] == "! setenv ":
567 setenv(line[len("! setenv "):])
569 elif line[0:len("! ignore ")] == "! ignore ":
570 cmd.add_ignore(line[len("! ignore "):])
573 fatal_error("UNRECOGNIZED OPTION")
576 line = f.readfullline()
578 cmd.run_if_possible()
580 TeshState().join_all_threads()
582 if f.filename == "(stdin)":
583 print("Test suite from stdin OK")
585 print("Test suite `"+f.filename+"' OK")