2 # -*- coding: utf-8 -*-
6 ========================
8 Copyright (c) 2012-2016. The SimGrid Team.
11 This program is free software; you can redistribute it and/or modify it
12 under the terms of the license (GNU LGPL) which comes with this package.
15 #TODO: child of child of child that printfs. Does it work?
16 #TODO: a child dies after its parent. What happen?
18 #TODO: regular expression in output
19 #ex: >> Time taken: [0-9]+s
20 #TODO: linked regular expression in output
22 # >> Bytes sent: ([0-9]+)
27 # TODO: If the output is sorted, we should report it to the users. Corresponding perl chunk
28 # print "WARNING: Both the observed output and expected output were sorted as requested.\n";
29 # print "WARNING: Output were only sorted using the $sort_prefix first chars.\n"
30 # if ( $sort_prefix > 0 );
31 # print "WARNING: Use <! output sort 19> to sort by simulated date and process ID only.\n";
33 # print "----8<--------------- Begin of unprocessed observed output (as it should appear in file):\n";
34 # map {print "> $_\n"} @{$cmd{'unsorted got'}};
35 # print "--------------->8---- End of the unprocessed observed output.\n";
48 if sys.version_info[0] == 3:
52 raise "This program is expected to run with Python3 only"
63 # Singleton metaclass that works in Python 2 & 3
64 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
65 class _Singleton(type):
66 """ A metaclass that creates a Singleton base class when called. """
68 def __call__(cls, *args, **kwargs):
69 if cls not in cls._instances:
70 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
71 return cls._instances[cls]
72 class Singleton(_Singleton('SingletonMeta', (object,), {})): pass
74 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
75 for n in dir(signal) if n.startswith('SIG') and '_' not in n )
81 #If you do not flush some prints are skipped
83 #os._exit exit even when executed within a thread
88 print("[Tesh/CRITICAL] "+str(msg))
92 #Set an environment variable.
93 # arg must be a string with the format "variable=value"
95 print("[Tesh/INFO] setenv "+arg)
97 os.environ[t[0]] = t[1]
98 #os.putenv(t[0], t[1]) does not work
99 #see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env
102 #http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does
103 def expandvars2(path):
104 return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path))
106 # https://github.com/Cadair/jupyter_environment_kernels/issues/10
111 FileNotFoundError = OSError
122 # read file line per line (and concat line that ends with "\")
123 class FileReader(Singleton):
124 def __init__(self, filename):
126 self.filename = "(stdin)"
129 self.filename_raw = filename
130 self.filename = os.path.basename(filename)
131 self.abspath = os.path.abspath(filename)
132 self.f = open(self.filename_raw)
136 def linenumber(self):
137 return self.linenumber
140 return self.filename+":"+str(self.linenumber)
142 def readfullline(self):
146 except StopIteration:
152 while len(line) > 1 and line[-2] == "\\":
160 #keep the state of tesh (mostly configuration values)
161 class TeshState(Singleton):
164 self.args_suffix = ""
165 self.ignore_regexps_common = []
168 def add_thread(self, thread):
169 self.threads.append(thread)
171 def join_all_threads(self):
172 for t in self.threads:
180 self.output_pipe_stdout = []
181 self.output_pipe_stderr = []
186 self.background = False
189 self.ignore_output = False
190 self.expect_return = 0
192 self.output_display = False
196 self.ignore_regexps = TeshState().ignore_regexps_common
198 def add_input_pipe(self, l):
199 self.input_pipe.append(l)
201 def add_output_pipe_stdout(self, l):
202 self.output_pipe_stdout.append(l)
204 def add_output_pipe_stderr(self, l):
205 self.output_pipe_stderr.append(l)
207 def set_cmd(self, args, linenumber):
209 self.linenumber = linenumber
211 def add_ignore(self, txt):
212 self.ignore_regexps.append(re.compile(txt))
214 def remove_ignored_lines(self, lines):
215 for ign in self.ignore_regexps:
216 lines = [l for l in lines if not ign.match(l)]
220 def _cmd_mkfile(self, argline):
221 filename = argline[len("mkfile "):]
222 file = open(filename, "w")
224 fatal_error("Unable to create file "+filename)
225 file.write("\n".join(self.input_pipe))
229 def _cmd_cd(self, argline):
230 args = shlex.split(argline)
232 fatal_error("Too many arguments to cd")
235 print("[Tesh/INFO] change directory to "+args[1])
236 except FileNotFoundError:
237 print("Chdir to "+args[1]+" failed: No such file or directory")
238 print("Test suite `"+FileReader().filename+"': NOK (system error)")
242 #Run the Cmd if possible.
243 # Return False if nothing has been ran.
244 def run_if_possible(self):
247 #Python threads loose the cwd
248 self.cwd = os.getcwd()
249 lock = _thread.allocate_lock()
251 TeshState().add_thread(lock)
252 _thread.start_new_thread( Cmd._run, (self, lock) )
260 def _run(self, lock=None):
261 #Python threads loose the cwd
262 if self.cwd is not None:
266 #retrocompatibility: support ${aaa:=.} variable format
267 def replace_perl_variables(m):
269 vdefault = m.group(2)
270 if vname in os.environ:
274 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
276 #replace bash environment variables ($THINGS) to their values
277 self.args = expandvars2(self.args)
279 if re.match("^mkfile ", self.args) is not None:
280 self._cmd_mkfile(self.args)
281 if lock is not None: lock.release()
284 if re.match("^cd ", self.args) is not None:
285 self._cmd_cd(self.args)
286 if lock is not None: lock.release()
289 if TeshState().wrapper is not None:
291 self.args = TeshState().wrapper + self.args
292 elif re.match(".*smpirun.*", self.args) is not None:
293 self.args = "sh " + self.args
295 self.args += TeshState().args_suffix
297 print("["+FileReader().filename+":"+str(self.linenumber)+"] "+self.args)
299 args = shlex.split(self.args)
302 proc = subprocess.Popen(args, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
305 e.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/bin/sh)"
309 (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
310 except subprocess.TimeoutExpired:
311 print("Test suite `"+FileReader().filename+"': NOK (<"+FileReader().filename+":"+str(self.linenumber)+"> timeout after "+str(self.timeout)+" sec)")
314 if self.output_display:
318 ansi_escape = re.compile(r'\x1b[^m]*m')
319 stdout_data = ansi_escape.sub('', stdout_data)
321 #print ((stdout_data, stderr_data))
323 if self.ignore_output:
324 print("(ignoring the output of <"+FileReader().filename+":"+str(self.linenumber)+"> as requested)")
326 stdouta = stdout_data.split("\n")
327 while len(stdouta) > 0 and stdouta[-1] == "":
329 stdouta = self.remove_ignored_lines(stdouta)
331 #the "sort" bash command is case unsensitive,
332 # we mimic its behaviour
334 stdouta.sort(key=lambda x: x.lower())
335 self.output_pipe_stdout.sort(key=lambda x: x.lower())
337 stdouta.sort(key=lambda x: x[:self.sort].lower())
338 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
340 diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained'))
342 print("Output of <"+FileReader().filename+":"+str(self.linenumber)+"> mismatch:")
345 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> output mismatch)")
346 if lock is not None: lock.release()
349 #print ((proc.returncode, self.expect_return))
351 if proc.returncode != self.expect_return:
352 if proc.returncode >= 0:
353 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> returned code "+str(proc.returncode)+")")
354 if lock is not None: lock.release()
357 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> got signal "+SIGNALS_TO_NAMES_DICT[-proc.returncode]+")")
358 if lock is not None: lock.release()
359 exit(-proc.returncode)
361 if lock is not None: lock.release()
366 return self.args is not None
379 if __name__ == '__main__':
381 parser = argparse.ArgumentParser(description='tesh -- testing shell', add_help=True)
382 group1 = parser.add_argument_group('Options')
383 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
384 group1.add_argument('--cd', metavar='some/directory', help='ask tesh to switch the working directory before launching the tests')
385 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
386 group1.add_argument('--cfg', metavar='arg', help='add parameter --cfg=arg to each command line')
387 group1.add_argument('--log', metavar='arg', help='add parameter --log=arg to each command line')
388 group1.add_argument('--ignore-jenkins', action='store_true', help='ignore all cruft generated on SimGrid continous integration servers')
389 group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
392 options = parser.parse_args()
396 if options.cd is not None:
399 if options.ignore_jenkins:
400 print("Ignore all cruft seen on SimGrid's continous integration servers")
401 TeshState().ignore_regexps_common = [
402 re.compile("^profiling:"),
403 re.compile(".*WARNING: ASan doesn\'t fully support"),
404 re.compile("Unable to clean temporary file C:.*")]
406 if options.teshfile is None:
408 print("Test suite from stdin")
410 f = FileReader(options.teshfile)
411 print("Test suite '"+f.abspath+"'")
413 if options.setenv is not None:
414 for e in options.setenv:
417 if options.cfg is not None:
418 TeshState().args_suffix += " --cfg="+options.cfg
419 if options.log is not None:
420 TeshState().args_suffix += " --log="+options.log
422 if options.wrapper is not None:
423 TeshState().wrapper = options.wrapper
425 #cmd holds the current command line
426 # tech commands will add some parameters to it
427 # when ready, we execute it.
430 line = f.readfullline()
431 while line is not None:
432 #print(">>============="+line+"==<<")
434 #print ("END CMD block")
435 if cmd.run_if_possible():
441 elif line[0:2] == "p ":
442 print("["+str(FileReader())+"] "+line[2:])
444 elif line[0:2] == "< ":
445 cmd.add_input_pipe(line[2:])
446 elif line[0:1] == "<":
447 cmd.add_input_pipe(line[1:])
449 elif line[0:2] == "> ":
450 cmd.add_output_pipe_stdout(line[2:])
451 elif line[0:1] == ">":
452 cmd.add_output_pipe_stdout(line[1:])
454 elif line[0:2] == "$ ":
455 if cmd.run_if_possible():
457 cmd.set_cmd(line[2:], f.linenumber)
459 elif line[0:2] == "& ":
460 if cmd.run_if_possible():
462 cmd.set_cmd(line[2:], f.linenumber)
463 cmd.background = True
465 elif line[0:15] == "! output ignore":
466 cmd.ignore_output = True
467 #print("cmd.ignore_output = True")
468 elif line[0:16] == "! output display":
469 cmd.output_display = True
470 cmd.ignore_output = True
471 elif line[0:15] == "! expect return":
472 cmd.expect_return = int(line[16:])
473 #print("expect return "+str(int(line[16:])))
474 elif line[0:15] == "! expect signal":
476 #get the signal integer value from the signal module
477 if sig not in signal.__dict__:
478 fatal_error("unrecognized signal '"+sig+"'")
479 sig = int(signal.__dict__[sig])
480 #popen return -signal when a process ends with a signal
481 cmd.expect_return = -sig
482 elif line[0:len("! timeout ")] == "! timeout ":
483 if "no" in line[len("! timeout "):]:
486 cmd.timeout = int(line[len("! timeout "):])
488 elif line[0:len("! output sort")] == "! output sort":
489 if len(line) >= len("! output sort "):
490 sort = int(line[len("! output sort "):])
494 elif line[0:len("! setenv ")] == "! setenv ":
495 setenv(line[len("! setenv "):])
497 elif line[0:len("! ignore ")] == "! ignore ":
498 cmd.add_ignore(line[len("! ignore "):])
501 fatal_error("UNRECOGNIZED OPTION")
504 line = f.readfullline()
506 cmd.run_if_possible()
508 TeshState().join_all_threads()
510 if f.filename == "(stdin)":
511 print("Test suite from stdin OK")
513 print("Test suite `"+f.filename+"' OK")