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]+)
26 # TODO: If the output is sorted, we should report it to the users. Corresponding perl chunk
27 # print "WARNING: Both the observed output and expected output were sorted as requested.\n";
28 # print "WARNING: Output were only sorted using the $sort_prefix first chars.\n"
29 # if ( $sort_prefix > 0 );
30 # print "WARNING: Use <! output sort 19> to sort by simulated date and process ID only.\n";
32 # print "----8<--------------- Begin of unprocessed observed output (as it should appear in file):\n";
33 # map {print "> $_\n"} @{$cmd{'unsorted got'}};
34 # print "--------------->8---- End of the unprocessed observed output.\n";
47 if sys.version_info[0] == 3:
51 raise "This program is expected to run with Python3 only"
62 # Singleton metaclass that works in Python 2 & 3
63 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
64 class _Singleton(type):
65 """ A metaclass that creates a Singleton base class when called. """
67 def __call__(cls, *args, **kwargs):
68 if cls not in cls._instances:
69 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
70 return cls._instances[cls]
71 class Singleton(_Singleton('SingletonMeta', (object,), {})): pass
73 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
74 for n in dir(signal) if n.startswith('SIG') and '_' not in n )
80 #If you do not flush some prints are skipped
82 #os._exit exit even when executed within a thread
87 print("[Tesh/CRITICAL] "+str(msg))
91 #Set an environment variable.
92 # arg must be a string with the format "variable=value"
94 print("[Tesh/INFO] setenv "+arg)
96 os.environ[t[0]] = t[1]
97 #os.putenv(t[0], t[1]) does not work
98 #see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env
101 #http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does
102 def expandvars2(path):
103 return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path))
105 # https://github.com/Cadair/jupyter_environment_kernels/issues/10
110 FileNotFoundError = OSError
121 # read file line per line (and concat line that ends with "\")
122 class FileReader(Singleton):
123 def __init__(self, filename=None):
125 self.filename = "(stdin)"
128 self.filename_raw = filename
129 self.filename = os.path.basename(filename)
130 self.abspath = os.path.abspath(filename)
131 self.f = open(self.filename_raw)
136 return self.filename+":"+str(self.linenumber)
138 def readfullline(self):
142 except StopIteration:
148 while len(line) > 1 and line[-2] == "\\":
156 #keep the state of tesh (mostly configuration values)
157 class TeshState(Singleton):
160 self.args_suffix = ""
161 self.ignore_regexps_common = []
162 self.jenkins = False # not a Jenkins run by default
163 self.timeout = 10 # default value: 10 sec
167 def add_thread(self, thread):
168 self.threads.append(thread)
170 def join_all_threads(self):
171 for t in self.threads:
179 self.output_pipe_stdout = []
180 self.output_pipe_stderr = []
181 self.timeout = TeshState().timeout
185 self.background = False
188 self.ignore_output = False
189 self.expect_return = 0
191 self.output_display = False
195 self.ignore_regexps = TeshState().ignore_regexps_common
197 def add_input_pipe(self, l):
198 self.input_pipe.append(l)
200 def add_output_pipe_stdout(self, l):
201 self.output_pipe_stdout.append(l)
203 def add_output_pipe_stderr(self, l):
204 self.output_pipe_stderr.append(l)
206 def set_cmd(self, args, linenumber):
208 self.linenumber = linenumber
210 def add_ignore(self, txt):
211 self.ignore_regexps.append(re.compile(txt))
213 def remove_ignored_lines(self, lines):
214 for ign in self.ignore_regexps:
215 lines = [l for l in lines if not ign.match(l)]
219 def _cmd_mkfile(self, argline):
220 filename = argline[len("mkfile "):]
221 file = open(filename, "w")
223 fatal_error("Unable to create file "+filename)
224 file.write("\n".join(self.input_pipe))
228 def _cmd_cd(self, argline):
229 args = shlex.split(argline)
231 fatal_error("Too many arguments to cd")
234 print("[Tesh/INFO] change directory to "+args[1])
235 except FileNotFoundError:
236 print("Chdir to "+args[1]+" failed: No such file or directory")
237 print("Test suite `"+FileReader().filename+"': NOK (system error)")
241 #Run the Cmd if possible.
242 # Return False if nothing has been ran.
243 def run_if_possible(self):
246 #Python threads loose the cwd
247 self.cwd = os.getcwd()
248 lock = _thread.allocate_lock()
250 TeshState().add_thread(lock)
251 _thread.start_new_thread( Cmd._run, (self, lock) )
259 def _run(self, lock=None):
260 #Python threads loose the cwd
261 if self.cwd is not None:
265 #retrocompatibility: support ${aaa:=.} variable format
266 def replace_perl_variables(m):
268 vdefault = m.group(2)
269 if vname in os.environ:
273 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
275 #replace bash environment variables ($THINGS) to their values
276 self.args = expandvars2(self.args)
278 if re.match("^mkfile ", self.args) is not None:
279 self._cmd_mkfile(self.args)
280 if lock is not None: lock.release()
283 if re.match("^cd ", self.args) is not None:
284 self._cmd_cd(self.args)
285 if lock is not None: lock.release()
288 if TeshState().wrapper is not None:
290 self.args = TeshState().wrapper + self.args
291 elif re.match(".*smpirun.*", self.args) is not None:
292 self.args = "sh " + self.args
293 if TeshState().jenkins and self.timeout != None:
296 self.args += TeshState().args_suffix
298 print("["+FileReader().filename+":"+str(self.linenumber)+"] "+self.args)
300 args = shlex.split(self.args)
304 proc = subprocess.Popen(args, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
305 except FileNotFoundError:
306 print("["+FileReader().filename+":"+str(self.linenumber)+"] Cannot start '"+args[0]+"': File not found")
308 except OSError as osE:
310 osE.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/bin/sh)"
313 cmdName = FileReader().filename+":"+str(self.linenumber)
315 (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
316 except subprocess.TimeoutExpired:
317 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> timeout after "+str(self.timeout)+" sec)")
321 if self.output_display:
325 ansi_escape = re.compile(r'\x1b[^m]*m')
326 stdout_data = ansi_escape.sub('', stdout_data)
328 #print ((stdout_data, stderr_data))
330 if self.ignore_output:
331 print("(ignoring the output of <"+cmdName+"> as requested)")
333 stdouta = stdout_data.split("\n")
334 while len(stdouta) > 0 and stdouta[-1] == "":
336 stdouta = self.remove_ignored_lines(stdouta)
339 # Mimic the "sort" bash command, which is case unsensitive.
341 stdouta.sort(key=lambda x: x.lower())
342 self.output_pipe_stdout.sort(key=lambda x: x.lower())
344 stdouta.sort(key=lambda x: x[:self.sort].lower())
345 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
347 diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained'))
349 print("Output of <"+cmdName+"> mismatch:")
350 if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version
357 print("(diff truncated after 50 lines)")
358 print("Unsorted observed output:\n")
361 else: # If not sorted, just display the diff
365 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> output mismatch)")
366 if lock is not None: lock.release()
368 f = open('obtained','w')
369 obtained = stdout_data.split("\n")
370 while len(obtained) > 0 and obtained[-1] == "":
372 obtained = self.remove_ignored_lines(obtained)
373 for line in obtained:
374 f.write("> "+line+"\n")
376 print("Obtained output kept as requested: "+os.path.abspath("obtained"))
379 #print ((proc.returncode, self.expect_return))
381 if proc.returncode != self.expect_return:
382 if proc.returncode >= 0:
383 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> returned code "+str(proc.returncode)+")")
384 if lock is not None: lock.release()
387 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> got signal "+SIGNALS_TO_NAMES_DICT[-proc.returncode]+")")
388 if lock is not None: lock.release()
389 exit(-proc.returncode)
391 if lock is not None: lock.release()
396 return self.args is not None
409 if __name__ == '__main__':
411 parser = argparse.ArgumentParser(description='tesh -- testing shell', add_help=True)
412 group1 = parser.add_argument_group('Options')
413 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
414 group1.add_argument('--cd', metavar='some/directory', help='ask tesh to switch the working directory before launching the tests')
415 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
416 group1.add_argument('--cfg', metavar='arg', help='add parameter --cfg=arg to each command line')
417 group1.add_argument('--log', metavar='arg', help='add parameter --log=arg to each command line')
418 group1.add_argument('--ignore-jenkins', action='store_true', help='ignore all cruft generated on SimGrid continous integration servers')
419 group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
420 group1.add_argument('--keep', action='store_true', help='Keep the obtained output when it does not match the expected one')
423 options = parser.parse_args()
427 if options.cd is not None:
430 if options.ignore_jenkins:
431 print("Ignore all cruft seen on SimGrid's continous integration servers")
432 TeshState().ignore_regexps_common = [
433 re.compile("^profiling:"),
434 re.compile(".*WARNING: ASan doesn\'t fully support"),
435 re.compile("Unable to clean temporary file C:.*"),
436 re.compile(".*Configuration change: Set \'contexts/"),
437 re.compile(".*Picked up JAVA_TOOL_OPTIONS.*"),
439 re.compile("==WARNING: ASan is ignoring requested __asan_handle_no_return: stack top:"),
440 re.compile("False positive error reports may follow"),
441 re.compile("For details see http://code.google.com/p/address-sanitizer/issues/detail?id=189"),
443 re.compile("Python runtime initialized with LC_CTYPE=C .*"),
445 TeshState().jenkins = True # This is a Jenkins build
447 if options.teshfile is None:
449 print("Test suite from stdin")
451 if not os.path.isfile(options.teshfile):
452 print("Cannot open teshfile '"+options.teshfile+"': File not found")
454 f = FileReader(options.teshfile)
455 print("Test suite '"+f.abspath+"'")
457 if options.setenv is not None:
458 for e in options.setenv:
461 if options.cfg is not None:
462 TeshState().args_suffix += " --cfg="+options.cfg
463 if options.log is not None:
464 TeshState().args_suffix += " --log="+options.log
466 if options.wrapper is not None:
467 TeshState().wrapper = options.wrapper
470 TeshState().keep = True
472 #cmd holds the current command line
473 # tech commands will add some parameters to it
474 # when ready, we execute it.
477 line = f.readfullline()
478 while line is not None:
479 #print(">>============="+line+"==<<")
481 #print ("END CMD block")
482 if cmd.run_if_possible():
488 elif line[0:2] == "p ":
489 print("["+str(FileReader())+"] "+line[2:])
491 elif line[0:2] == "< ":
492 cmd.add_input_pipe(line[2:])
493 elif line[0:1] == "<":
494 cmd.add_input_pipe(line[1:])
496 elif line[0:2] == "> ":
497 cmd.add_output_pipe_stdout(line[2:])
498 elif line[0:1] == ">":
499 cmd.add_output_pipe_stdout(line[1:])
501 elif line[0:2] == "$ ":
502 if cmd.run_if_possible():
504 cmd.set_cmd(line[2:], f.linenumber)
506 elif line[0:2] == "& ":
507 if cmd.run_if_possible():
509 cmd.set_cmd(line[2:], f.linenumber)
510 cmd.background = True
512 elif line[0:15] == "! output ignore":
513 cmd.ignore_output = True
514 #print("cmd.ignore_output = True")
515 elif line[0:16] == "! output display":
516 cmd.output_display = True
517 cmd.ignore_output = True
518 elif line[0:15] == "! expect return":
519 cmd.expect_return = int(line[16:])
520 #print("expect return "+str(int(line[16:])))
521 elif line[0:15] == "! expect signal":
523 #get the signal integer value from the signal module
524 if sig not in signal.__dict__:
525 fatal_error("unrecognized signal '"+sig+"'")
526 sig = int(signal.__dict__[sig])
527 #popen return -signal when a process ends with a signal
528 cmd.expect_return = -sig
529 elif line[0:len("! timeout ")] == "! timeout ":
530 if "no" in line[len("! timeout "):]:
533 cmd.timeout = int(line[len("! timeout "):])
535 elif line[0:len("! output sort")] == "! output sort":
536 if len(line) >= len("! output sort "):
537 sort = int(line[len("! output sort "):])
541 elif line[0:len("! setenv ")] == "! setenv ":
542 setenv(line[len("! setenv "):])
544 elif line[0:len("! ignore ")] == "! ignore ":
545 cmd.add_ignore(line[len("! ignore "):])
548 fatal_error("UNRECOGNIZED OPTION")
551 line = f.readfullline()
553 cmd.run_if_possible()
555 TeshState().join_all_threads()
557 if f.filename == "(stdin)":
558 print("Test suite from stdin OK")
560 print("Test suite `"+f.filename+"' OK")