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 -1 if none)
108 def kill_process_group(pgid):
109 # print("Kill process group {}".format(pgid))
110 os.killpg(pgid, signal.SIGTERM)
112 def signal_handler(signal, frame):
113 print("Caught signal {}".format(SIGNALS_TO_NAMES_DICT[signal]))
115 kill_process_group(pgtokill)
128 # read file line per line (and concat line that ends with "\")
129 class FileReader(Singleton):
130 def __init__(self, filename=None):
132 self.filename = "(stdin)"
135 self.filename_raw = filename
136 self.filename = os.path.basename(filename)
137 self.abspath = os.path.abspath(filename)
138 self.f = open(self.filename_raw)
143 return self.filename+":"+str(self.linenumber)
145 def readfullline(self):
149 except StopIteration:
155 while len(line) > 1 and line[-2] == "\\":
163 #keep the state of tesh (mostly configuration values)
164 class TeshState(Singleton):
167 self.args_suffix = ""
168 self.ignore_regexps_common = []
169 self.jenkins = False # not a Jenkins run by default
170 self.timeout = 10 # default value: 10 sec
174 def add_thread(self, thread):
175 self.threads.append(thread)
177 def join_all_threads(self):
178 for t in self.threads:
186 self.output_pipe_stdout = []
187 self.output_pipe_stderr = []
188 self.timeout = TeshState().timeout
192 self.background = False
195 self.ignore_output = False
196 self.expect_return = 0
198 self.output_display = False
202 self.ignore_regexps = TeshState().ignore_regexps_common
204 def add_input_pipe(self, l):
205 self.input_pipe.append(l)
207 def add_output_pipe_stdout(self, l):
208 self.output_pipe_stdout.append(l)
210 def add_output_pipe_stderr(self, l):
211 self.output_pipe_stderr.append(l)
213 def set_cmd(self, args, linenumber):
215 self.linenumber = linenumber
217 def add_ignore(self, txt):
218 self.ignore_regexps.append(re.compile(txt))
220 def remove_ignored_lines(self, lines):
221 for ign in self.ignore_regexps:
222 lines = [l for l in lines if not ign.match(l)]
226 def _cmd_mkfile(self, argline):
227 filename = argline[len("mkfile "):]
228 file = open(filename, "w")
230 fatal_error("Unable to create file "+filename)
231 file.write("\n".join(self.input_pipe))
235 def _cmd_cd(self, argline):
236 args = shlex.split(argline)
238 fatal_error("Too many arguments to cd")
241 print("[Tesh/INFO] change directory to "+args[1])
242 except FileNotFoundError:
243 print("Chdir to "+args[1]+" failed: No such file or directory")
244 print("Test suite `"+FileReader().filename+"': NOK (system error)")
248 #Run the Cmd if possible.
249 # Return False if nothing has been ran.
250 def run_if_possible(self):
253 #Python threads loose the cwd
254 self.cwd = os.getcwd()
255 lock = _thread.allocate_lock()
257 TeshState().add_thread(lock)
258 _thread.start_new_thread( Cmd._run, (self, lock) )
266 def _run(self, lock=None):
267 #Python threads loose the cwd
268 if self.cwd is not None:
272 #retrocompatibility: support ${aaa:=.} variable format
273 def replace_perl_variables(m):
275 vdefault = m.group(2)
276 if vname in os.environ:
280 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
282 #replace bash environment variables ($THINGS) to their values
283 self.args = expandvars2(self.args)
285 if re.match("^mkfile ", self.args) is not None:
286 self._cmd_mkfile(self.args)
287 if lock is not None: lock.release()
290 if re.match("^cd ", self.args) is not None:
291 self._cmd_cd(self.args)
292 if lock is not None: lock.release()
295 if TeshState().wrapper is not None:
297 self.args = TeshState().wrapper + self.args
298 elif re.match(".*smpirun.*", self.args) is not None:
299 self.args = "sh " + self.args
300 if TeshState().jenkins and self.timeout != None:
303 self.args += TeshState().args_suffix
305 print("["+FileReader().filename+":"+str(self.linenumber)+"] "+self.args)
307 args = shlex.split(self.args)
313 proc = subprocess.Popen(args, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, preexec_fn=os.setsid)
314 pgtokill = os.getpgid(proc.pid)
315 except FileNotFoundError:
316 print("["+FileReader().filename+":"+str(self.linenumber)+"] Cannot start '"+args[0]+"': File not found")
318 except OSError as osE:
320 osE.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/usr/bin/env sh)"
323 cmdName = FileReader().filename+":"+str(self.linenumber)
325 (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
327 except subprocess.TimeoutExpired:
328 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> timeout after "+str(self.timeout)+" sec)")
329 kill_process_group(pgtokill)
332 if self.output_display:
336 ansi_escape = re.compile(r'\x1b[^m]*m')
337 stdout_data = ansi_escape.sub('', stdout_data)
339 #print ((stdout_data, stderr_data))
341 if self.ignore_output:
342 print("(ignoring the output of <"+cmdName+"> as requested)")
344 stdouta = stdout_data.split("\n")
345 while len(stdouta) > 0 and stdouta[-1] == "":
347 stdouta = self.remove_ignored_lines(stdouta)
350 # Mimic the "sort" bash command, which is case unsensitive.
352 stdouta.sort(key=lambda x: x.lower())
353 self.output_pipe_stdout.sort(key=lambda x: x.lower())
355 stdouta.sort(key=lambda x: x[:self.sort].lower())
356 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
358 diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained'))
360 print("Output of <"+cmdName+"> mismatch:")
361 if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version
368 print("(diff truncated after 50 lines)")
369 print("Unsorted observed output:\n")
372 else: # If not sorted, just display the diff
376 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> output mismatch)")
377 if lock is not None: lock.release()
379 f = open('obtained','w')
380 obtained = stdout_data.split("\n")
381 while len(obtained) > 0 and obtained[-1] == "":
383 obtained = self.remove_ignored_lines(obtained)
384 for line in obtained:
385 f.write("> "+line+"\n")
387 print("Obtained output kept as requested: "+os.path.abspath("obtained"))
390 #print ((proc.returncode, self.expect_return))
392 if proc.returncode != self.expect_return:
393 if proc.returncode >= 0:
394 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> returned code "+str(proc.returncode)+")")
395 if lock is not None: lock.release()
398 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> got signal "+SIGNALS_TO_NAMES_DICT[-proc.returncode]+")")
399 if lock is not None: lock.release()
400 tesh_exit(-proc.returncode)
402 if lock is not None: lock.release()
407 return self.args is not None
420 if __name__ == '__main__':
421 signal.signal(signal.SIGINT, signal_handler)
422 signal.signal(signal.SIGTERM, signal_handler)
424 parser = argparse.ArgumentParser(description='tesh -- testing shell', add_help=True)
425 group1 = parser.add_argument_group('Options')
426 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
427 group1.add_argument('--cd', metavar='some/directory', help='ask tesh to switch the working directory before launching the tests')
428 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
429 group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line')
430 group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line')
431 group1.add_argument('--ignore-jenkins', action='store_true', help='ignore all cruft generated on SimGrid continous integration servers')
432 group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
433 group1.add_argument('--keep', action='store_true', help='Keep the obtained output when it does not match the expected one')
436 options = parser.parse_args()
440 if options.cd is not None:
441 print("[Tesh/INFO] change directory to " + options.cd)
444 if options.ignore_jenkins:
445 print("Ignore all cruft seen on SimGrid's continous integration servers")
446 # Note: regexps should match at the beginning of lines
447 TeshState().ignore_regexps_common = [
448 re.compile("profiling:"),
449 re.compile("Unable to clean temporary file C:"),
450 re.compile(".*Configuration change: Set \'contexts/"),
451 re.compile("Picked up JAVA_TOOL_OPTIONS: "),
452 re.compile("Picked up _JAVA_OPTIONS: "),
453 re.compile("==[0-9]+== ?WARNING: ASan doesn\'t fully support"),
454 re.compile("==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack top:"),
455 re.compile("False positive error reports may follow"),
456 re.compile("For details see http://code.google.com/p/address-sanitizer/issues/detail\\?id=189"),
457 re.compile("For details see https://github.com/google/sanitizers/issues/189"),
458 re.compile("Python runtime initialized with LC_CTYPE=C .*"),
459 re.compile("cmake: /usr/local/lib/libcurl.so.4: no version information available (required by cmake)"), # Seen on CircleCI
461 TeshState().jenkins = True # This is a Jenkins build
463 if options.teshfile is None:
465 print("Test suite from stdin")
467 if not os.path.isfile(options.teshfile):
468 print("Cannot open teshfile '"+options.teshfile+"': File not found")
470 f = FileReader(options.teshfile)
471 print("Test suite '"+f.abspath+"'")
473 if options.setenv is not None:
474 for e in options.setenv:
477 if options.cfg is not None:
478 for c in options.cfg:
479 TeshState().args_suffix += " --cfg=" + c
480 if options.log is not None:
481 for l in options.log:
482 TeshState().args_suffix += " --log=" + l
484 if options.wrapper is not None:
485 TeshState().wrapper = options.wrapper
488 TeshState().keep = True
490 #cmd holds the current command line
491 # tech commands will add some parameters to it
492 # when ready, we execute it.
495 line = f.readfullline()
496 while line is not None:
497 #print(">>============="+line+"==<<")
499 #print ("END CMD block")
500 if cmd.run_if_possible():
506 elif line[0:2] == "p ":
507 print("["+str(FileReader())+"] "+line[2:])
509 elif line[0:2] == "< ":
510 cmd.add_input_pipe(line[2:])
511 elif line[0:1] == "<":
512 cmd.add_input_pipe(line[1:])
514 elif line[0:2] == "> ":
515 cmd.add_output_pipe_stdout(line[2:])
516 elif line[0:1] == ">":
517 cmd.add_output_pipe_stdout(line[1:])
519 elif line[0:2] == "$ ":
520 if cmd.run_if_possible():
522 cmd.set_cmd(line[2:], f.linenumber)
524 elif line[0:2] == "& ":
525 if cmd.run_if_possible():
527 cmd.set_cmd(line[2:], f.linenumber)
528 cmd.background = True
530 elif line[0:15] == "! output ignore":
531 cmd.ignore_output = True
532 #print("cmd.ignore_output = True")
533 elif line[0:16] == "! output display":
534 cmd.output_display = True
535 cmd.ignore_output = True
536 elif line[0:15] == "! expect return":
537 cmd.expect_return = int(line[16:])
538 #print("expect return "+str(int(line[16:])))
539 elif line[0:15] == "! expect signal":
541 #get the signal integer value from the signal module
542 if sig not in signal.__dict__:
543 fatal_error("unrecognized signal '"+sig+"'")
544 sig = int(signal.__dict__[sig])
545 #popen return -signal when a process ends with a signal
546 cmd.expect_return = -sig
547 elif line[0:len("! timeout ")] == "! timeout ":
548 if "no" in line[len("! timeout "):]:
551 cmd.timeout = int(line[len("! timeout "):])
553 elif line[0:len("! output sort")] == "! output sort":
554 if len(line) >= len("! output sort "):
555 sort = int(line[len("! output sort "):])
559 elif line[0:len("! setenv ")] == "! setenv ":
560 setenv(line[len("! setenv "):])
562 elif line[0:len("! ignore ")] == "! ignore ":
563 cmd.add_ignore(line[len("! ignore "):])
566 fatal_error("UNRECOGNIZED OPTION")
569 line = f.readfullline()
571 cmd.run_if_possible()
573 TeshState().join_all_threads()
575 if f.filename == "(stdin)":
576 print("Test suite from stdin OK")
578 print("Test suite `"+f.filename+"' OK")