2 # -*- coding: utf-8 -*-
6 ========================
8 Copyright (c) 2012-2018. 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 return sys.platform.startswith('win')
51 # Singleton metaclass that works in Python 2 & 3
52 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
53 class _Singleton(type):
54 """ A metaclass that creates a Singleton base class when called. """
56 def __call__(cls, *args, **kwargs):
57 if cls not in cls._instances:
58 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
59 return cls._instances[cls]
60 class Singleton(_Singleton('SingletonMeta', (object,), {})): pass
62 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
63 for n in dir(signal) if n.startswith('SIG') and '_' not in n )
68 def tesh_exit(errcode):
69 #If you do not flush some prints are skipped
71 #os._exit exit even when executed within a thread
76 print("[Tesh/CRITICAL] "+str(msg))
80 #Set an environment variable.
81 # arg must be a string with the format "variable=value"
83 print("[Tesh/INFO] setenv "+arg)
85 os.environ[t[0]] = t[1]
86 #os.putenv(t[0], t[1]) does not work
87 #see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env
90 #http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does
91 def expandvars2(path):
92 return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path))
94 # https://github.com/Cadair/jupyter_environment_kernels/issues/10
99 FileNotFoundError = OSError
107 # Global variable. Stores which process group should be killed (or None otherwise)
110 def kill_process_group(pgid):
111 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
114 # print("Kill process group {}".format(pgid))
116 os.killpg(pgid, signal.SIGTERM)
118 # os.killpg failed. OK. Some subprocesses may still be running.
121 def signal_handler(signal, frame):
122 print("Caught signal {}".format(SIGNALS_TO_NAMES_DICT[signal]))
123 if pgtokill is not None:
124 kill_process_group(pgtokill)
137 # read file line per line (and concat line that ends with "\")
138 class FileReader(Singleton):
139 def __init__(self, filename=None):
141 self.filename = "(stdin)"
144 self.filename_raw = filename
145 self.filename = os.path.basename(filename)
146 self.abspath = os.path.abspath(filename)
147 self.f = open(self.filename_raw)
152 return self.filename+":"+str(self.linenumber)
154 def readfullline(self):
158 except StopIteration:
164 while len(line) > 1 and line[-2] == "\\":
172 #keep the state of tesh (mostly configuration values)
173 class TeshState(Singleton):
176 self.args_suffix = ""
177 self.ignore_regexps_common = []
178 self.jenkins = False # not a Jenkins run by default
179 self.timeout = 10 # default value: 10 sec
183 def add_thread(self, thread):
184 self.threads.append(thread)
186 def join_all_threads(self):
187 for t in self.threads:
195 self.output_pipe_stdout = []
196 self.output_pipe_stderr = []
197 self.timeout = TeshState().timeout
201 self.background = False
204 self.ignore_output = False
205 self.expect_return = 0
207 self.output_display = False
211 self.ignore_regexps = TeshState().ignore_regexps_common
213 def add_input_pipe(self, l):
214 self.input_pipe.append(l)
216 def add_output_pipe_stdout(self, l):
217 self.output_pipe_stdout.append(l)
219 def add_output_pipe_stderr(self, l):
220 self.output_pipe_stderr.append(l)
222 def set_cmd(self, args, linenumber):
224 self.linenumber = linenumber
226 def add_ignore(self, txt):
227 self.ignore_regexps.append(re.compile(txt))
229 def remove_ignored_lines(self, lines):
230 for ign in self.ignore_regexps:
231 lines = [l for l in lines if not ign.match(l)]
235 def _cmd_mkfile(self, argline):
236 filename = argline[len("mkfile "):]
237 file = open(filename, "w")
239 fatal_error("Unable to create file "+filename)
240 file.write("\n".join(self.input_pipe))
244 def _cmd_cd(self, argline):
245 args = shlex.split(argline)
247 fatal_error("Too many arguments to cd")
250 print("[Tesh/INFO] change directory to "+args[1])
251 except FileNotFoundError:
252 print("Chdir to "+args[1]+" failed: No such file or directory")
253 print("Test suite `"+FileReader().filename+"': NOK (system error)")
257 #Run the Cmd if possible.
258 # Return False if nothing has been ran.
259 def run_if_possible(self):
262 #Python threads loose the cwd
263 self.cwd = os.getcwd()
264 lock = _thread.allocate_lock()
266 TeshState().add_thread(lock)
267 _thread.start_new_thread( Cmd._run, (self, lock) )
275 def _run(self, lock=None):
276 #Python threads loose the cwd
277 if self.cwd is not None:
281 #retrocompatibility: support ${aaa:=.} variable format
282 def replace_perl_variables(m):
284 vdefault = m.group(2)
285 if vname in os.environ:
289 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
291 #replace bash environment variables ($THINGS) to their values
292 self.args = expandvars2(self.args)
294 if re.match("^mkfile ", self.args) is not None:
295 self._cmd_mkfile(self.args)
296 if lock is not None: lock.release()
299 if re.match("^cd ", self.args) is not None:
300 self._cmd_cd(self.args)
301 if lock is not None: lock.release()
304 if TeshState().wrapper is not None:
306 self.args = TeshState().wrapper + self.args
307 elif re.match(".*smpirun.*", self.args) is not None:
308 self.args = "sh " + self.args
309 if TeshState().jenkins and self.timeout != None:
312 self.args += TeshState().args_suffix
314 print("["+FileReader().filename+":"+str(self.linenumber)+"] "+self.args)
316 args = shlex.split(self.args)
322 proc = subprocess.Popen(args, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, start_new_session=True)
325 pgtokill = os.getpgid(proc.pid)
327 # os.getpgid failed. OK. No cleanup.
329 except PermissionError:
330 print("["+FileReader().filename+":"+str(self.linenumber)+"] Cannot start '"+args[0]+"': The binary is not executable.")
331 print("["+FileReader().filename+":"+str(self.linenumber)+"] Current dir: "+os.getcwd())
333 except NotADirectoryError:
334 print("["+FileReader().filename+":"+str(self.linenumber)+"] Cannot start '"+args[0]+"': The path to binary does not exist.")
335 print("["+FileReader().filename+":"+str(self.linenumber)+"] Current dir: "+os.getcwd())
337 except FileNotFoundError:
338 print("["+FileReader().filename+":"+str(self.linenumber)+"] Cannot start '"+args[0]+"': File not found")
340 except OSError as osE:
342 osE.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/usr/bin/env sh)"
345 cmdName = FileReader().filename+":"+str(self.linenumber)
347 (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
349 except subprocess.TimeoutExpired:
350 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> timeout after "+str(self.timeout)+" sec)")
351 kill_process_group(pgtokill)
354 if self.output_display:
358 ansi_escape = re.compile(r'\x1b[^m]*m')
359 stdout_data = ansi_escape.sub('', stdout_data)
361 #print ((stdout_data, stderr_data))
363 if self.ignore_output:
364 print("(ignoring the output of <"+cmdName+"> as requested)")
366 stdouta = stdout_data.split("\n")
367 while len(stdouta) > 0 and stdouta[-1] == "":
369 stdouta = self.remove_ignored_lines(stdouta)
372 # Mimic the "sort" bash command, which is case unsensitive.
374 stdouta.sort(key=lambda x: x.lower())
375 self.output_pipe_stdout.sort(key=lambda x: x.lower())
377 stdouta.sort(key=lambda x: x[:self.sort].lower())
378 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
380 diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained'))
382 print("Output of <"+cmdName+"> mismatch:")
383 if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version
390 print("(diff truncated after 50 lines)")
391 print("Unsorted observed output:\n")
394 else: # If not sorted, just display the diff
398 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> output mismatch)")
399 if lock is not None: lock.release()
401 f = open('obtained','w')
402 obtained = stdout_data.split("\n")
403 while len(obtained) > 0 and obtained[-1] == "":
405 obtained = self.remove_ignored_lines(obtained)
406 for line in obtained:
407 f.write("> "+line+"\n")
409 print("Obtained output kept as requested: "+os.path.abspath("obtained"))
412 #print ((proc.returncode, self.expect_return))
414 if proc.returncode != self.expect_return:
415 if proc.returncode >= 0:
416 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> returned code "+str(proc.returncode)+")")
417 if lock is not None: lock.release()
420 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> got signal "+SIGNALS_TO_NAMES_DICT[-proc.returncode]+")")
421 if lock is not None: lock.release()
422 tesh_exit(-proc.returncode)
424 if lock is not None: lock.release()
429 return self.args is not None
442 if __name__ == '__main__':
443 signal.signal(signal.SIGINT, signal_handler)
444 signal.signal(signal.SIGTERM, signal_handler)
446 parser = argparse.ArgumentParser(description='tesh -- testing shell', add_help=True)
447 group1 = parser.add_argument_group('Options')
448 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
449 group1.add_argument('--cd', metavar='some/directory', help='ask tesh to switch the working directory before launching the tests')
450 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
451 group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line')
452 group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line')
453 group1.add_argument('--ignore-jenkins', action='store_true', help='ignore all cruft generated on SimGrid continous integration servers')
454 group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
455 group1.add_argument('--keep', action='store_true', help='Keep the obtained output when it does not match the expected one')
458 options = parser.parse_args()
462 if options.cd is not None:
463 print("[Tesh/INFO] change directory to " + options.cd)
466 if options.ignore_jenkins:
467 print("Ignore all cruft seen on SimGrid's continous integration servers")
468 # Note: regexps should match at the beginning of lines
469 TeshState().ignore_regexps_common = [
470 re.compile(r"profiling:"),
471 re.compile(r"Unable to clean temporary file C:"),
472 re.compile(r".*Configuration change: Set 'contexts/"),
473 re.compile(r"Picked up JAVA_TOOL_OPTIONS: "),
474 re.compile(r"Picked up _JAVA_OPTIONS: "),
475 re.compile(r"==[0-9]+== ?WARNING: ASan doesn't fully support"),
476 re.compile(r"==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack top:"),
477 re.compile(r"False positive error reports may follow"),
478 re.compile(r"For details see http://code.google.com/p/address-sanitizer/issues/detail\?id=189"),
479 re.compile(r"For details see https://github.com/google/sanitizers/issues/189"),
480 re.compile(r"Python runtime initialized with LC_CTYPE=C .*"),
481 re.compile(r"cmake: /usr/local/lib/libcurl\.so\.4: no version information available \(required by cmake\)"), # Seen on CircleCI
482 re.compile(r".*mmap broken on FreeBSD, but dlopen\+thread broken too. Switching to dlopen\+raw contexts\."),
483 re.compile(r".*dlopen\+thread broken on Apple and BSD\. Switching to raw contexts\."),
485 TeshState().jenkins = True # This is a Jenkins build
487 if options.teshfile is None:
489 print("Test suite from stdin")
491 if not os.path.isfile(options.teshfile):
492 print("Cannot open teshfile '"+options.teshfile+"': File not found")
494 f = FileReader(options.teshfile)
495 print("Test suite '"+f.abspath+"'")
497 if options.setenv is not None:
498 for e in options.setenv:
501 if options.cfg is not None:
502 for c in options.cfg:
503 TeshState().args_suffix += " --cfg=" + c
504 if options.log is not None:
505 for l in options.log:
506 TeshState().args_suffix += " --log=" + l
508 if options.wrapper is not None:
509 TeshState().wrapper = options.wrapper
512 TeshState().keep = True
514 #cmd holds the current command line
515 # tech commands will add some parameters to it
516 # when ready, we execute it.
519 line = f.readfullline()
520 while line is not None:
521 #print(">>============="+line+"==<<")
523 #print ("END CMD block")
524 if cmd.run_if_possible():
530 elif line[0:2] == "p ":
531 print("["+str(FileReader())+"] "+line[2:])
533 elif line[0:2] == "< ":
534 cmd.add_input_pipe(line[2:])
535 elif line[0:1] == "<":
536 cmd.add_input_pipe(line[1:])
538 elif line[0:2] == "> ":
539 cmd.add_output_pipe_stdout(line[2:])
540 elif line[0:1] == ">":
541 cmd.add_output_pipe_stdout(line[1:])
543 elif line[0:2] == "$ ":
544 if cmd.run_if_possible():
546 cmd.set_cmd(line[2:], f.linenumber)
548 elif line[0:2] == "& ":
549 if cmd.run_if_possible():
551 cmd.set_cmd(line[2:], f.linenumber)
552 cmd.background = True
554 elif line[0:15] == "! output ignore":
555 cmd.ignore_output = True
556 #print("cmd.ignore_output = True")
557 elif line[0:16] == "! output display":
558 cmd.output_display = True
559 cmd.ignore_output = True
560 elif line[0:15] == "! expect return":
561 cmd.expect_return = int(line[16:])
562 #print("expect return "+str(int(line[16:])))
563 elif line[0:15] == "! expect signal":
565 #get the signal integer value from the signal module
566 if sig not in signal.__dict__:
567 fatal_error("unrecognized signal '"+sig+"'")
568 sig = int(signal.__dict__[sig])
569 #popen return -signal when a process ends with a signal
570 cmd.expect_return = -sig
571 elif line[0:len("! timeout ")] == "! timeout ":
572 if "no" in line[len("! timeout "):]:
575 cmd.timeout = int(line[len("! timeout "):])
577 elif line[0:len("! output sort")] == "! output sort":
578 if len(line) >= len("! output sort "):
579 sort = int(line[len("! output sort "):])
583 elif line[0:len("! setenv ")] == "! setenv ":
584 setenv(line[len("! setenv "):])
586 elif line[0:len("! ignore ")] == "! ignore ":
587 cmd.add_ignore(line[len("! ignore "):])
590 fatal_error("UNRECOGNIZED OPTION")
593 line = f.readfullline()
595 cmd.run_if_possible()
597 TeshState().join_all_threads()
599 if f.filename == "(stdin)":
600 print("Test suite from stdin OK")
602 print("Test suite `"+f.filename+"' OK")