2 # -*- coding: utf-8 -*-
6 ========================
8 Copyright (c) 2012-2015. 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.
14 #TODO: <glesserd> emptty: does "! output display" also disable the comparaison with the output ? yes
16 #TODO: child of child of child printf => tester dans rsg...
18 #TODO: regular expression in output
19 #TODO: linked regular expression in output
32 if sys.version_info[0] == 3:
35 elif sys.version_info[0] < 3:
36 import subprocess32 as subprocess
37 import thread as _thread
39 raise "This program has not been made to exist this long"
50 # Singleton metaclass that works in Python 2 & 3
51 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
52 class _Singleton(type):
53 """ A metaclass that creates a Singleton base class when called. """
55 def __call__(cls, *args, **kwargs):
56 if cls not in cls._instances:
57 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
58 return cls._instances[cls]
59 class Singleton(_Singleton('SingletonMeta', (object,), {})): pass
61 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
62 for n in dir(signal) if n.startswith('SIG') and '_' not in n )
68 #If you do not flush some prints are skipped
70 #os._exit exit even when executed within a thread
75 print("[Tesh/CRITICAL] "+str(msg))
79 #Set an environment variable.
80 # arg must be a string with the format "variable=value"
82 print("[Tesh/INFO] setenv "+arg)
84 os.environ[t[0]] = t[1]
85 #os.putenv(t[0], t[1]) does not work
86 #see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env
89 #http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does
90 def expandvars2(path):
91 return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path))
93 # https://github.com/Cadair/jupyter_environment_kernels/issues/10
98 FileNotFoundError = OSError
109 # read file line per line (and concat line that ends with "\")
110 class FileReader(Singleton):
111 def __init__(self, filename):
113 self.filename = "(stdin)"
116 self.filename_raw = filename
117 self.filename = os.path.basename(filename)
118 self.f = open(self.filename_raw)
122 def linenumber(self):
123 return self.linenumber
126 return self.filename+":"+str(self.linenumber)
128 def readfullline(self):
132 except StopIteration:
138 while len(line) > 1 and line[-2] == "\\":
146 #keep the state of tesh (mostly configuration values)
147 class TeshState(Singleton):
150 self.args_suffix = ""
151 self.ignore_regexps_common = []
153 def add_thread(self, thread):
154 self.threads.append(thread)
156 def join_all_threads(self):
157 for t in self.threads:
168 self.output_pipe_stdout = []
169 self.output_pipe_stderr = []
174 self.background = False
177 self.ignore_output = False
178 self.expect_return = 0
180 self.output_display = False
184 self.ignore_regexps = TeshState().ignore_regexps_common
186 def add_input_pipe(self, l):
187 self.input_pipe.append(l)
189 def add_output_pipe_stdout(self, l):
190 self.output_pipe_stdout.append(l)
192 def add_output_pipe_stderr(self, l):
193 self.output_pipe_stderr.append(l)
195 def set_cmd(self, args, linenumber):
197 self.linenumber = linenumber
199 def add_ignore(self, txt):
200 self.ignore_regexps.append(re.compile(txt))
202 def remove_ignored_lines(self, lines):
203 for ign in self.ignore_regexps:
204 lines = [l for l in lines if not ign.match(l)]
208 def _cmd_mkfile(self, argline):
209 filename = argline[len("mkfile "):]
210 file = open(filename, "w")
212 fatal_error("Unable to create file "+filename)
213 file.write("\n".join(self.input_pipe))
216 def _cmd_cd(self, argline):
217 args = shlex.split(argline)
219 fatal_error("Too many arguments to cd")
222 print("[Tesh/INFO] change directory to "+args[1])
223 except FileNotFoundError:
224 print("Chdir to "+args[1]+" failed: No such file or directory")
225 print("Test suite `"+FileReader().filename+"': NOK (system error)")
229 #Run the Cmd if possible.
230 # Return False if nothing has been ran.
231 def run_if_possible(self):
234 #Python threads loose the cwd
235 self.cwd = os.getcwd()
236 lock = _thread.allocate_lock()
238 TeshState().add_thread(lock)
239 _thread.start_new_thread( Cmd._run, (self, lock) )
247 def _run(self, lock=None):
248 #Python threads loose the cwd
249 if self.cwd is not None:
253 #retrocompatibility: support ${aaa:=.} variable format
254 def replace_perl_variables(m):
256 vdefault = m.group(2)
257 if vname in os.environ:
261 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
263 #replace bash environment variables ($THINGS) to their values
264 self.args = expandvars2(self.args)
266 if re.match("^mkfile ", self.args) is not None:
267 self._cmd_mkfile(self.args)
268 if lock is not None: lock.release()
271 if re.match("^cd ", self.args) is not None:
272 self._cmd_cd(self.args)
273 if lock is not None: lock.release()
276 self.args += TeshState().args_suffix
278 print("["+FileReader().filename+":"+str(self.linenumber)+"] "+self.args)
280 args = shlex.split(self.args)
283 proc = subprocess.Popen(args, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
286 e.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/bin/sh)"
290 (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
291 except subprocess.TimeoutExpired:
292 print("Test suite `"+FileReader().filename+"': NOK (<"+FileReader().filename+":"+str(self.linenumber)+"> timeout after "+str(self.timeout)+" sec)")
295 if self.output_display:
299 ansi_escape = re.compile(r'\x1b[^m]*m')
300 stdout_data = ansi_escape.sub('', stdout_data)
302 #print ((stdout_data, stderr_data))
304 if self.ignore_output:
305 print("(ignoring the output of <"+FileReader().filename+":"+str(self.linenumber)+"> as requested)")
307 stdouta = stdout_data.split("\n")
308 while len(stdouta) > 0 and stdouta[-1] == "":
310 stdouta = self.remove_ignored_lines(stdouta)
312 #the "sort" bash command is case unsensitive,
313 # we mimic its behaviour
315 stdouta.sort(key=lambda x: x.lower())
316 self.output_pipe_stdout.sort(key=lambda x: x.lower())
318 stdouta.sort(key=lambda x: x[:self.sort].lower())
319 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
321 diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained'))
323 print("Output of <"+FileReader().filename+":"+str(self.linenumber)+"> mismatch:")
326 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> output mismatch)")
327 if lock is not None: lock.release()
330 #print ((proc.returncode, self.expect_return))
332 if proc.returncode != self.expect_return:
333 if proc.returncode >= 0:
334 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> returned code "+str(proc.returncode)+")")
335 if lock is not None: lock.release()
338 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> got signal "+SIGNALS_TO_NAMES_DICT[-proc.returncode]+")")
339 if lock is not None: lock.release()
340 exit(-proc.returncode)
342 if lock is not None: lock.release()
347 return self.args is not None
366 if __name__ == '__main__':
368 parser = argparse.ArgumentParser(description='tesh -- testing shell', add_help=True)
369 group1 = parser.add_argument_group('Options')
370 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
371 group1.add_argument('--cd', metavar='some/directory', help='ask tesh to switch the working directory before launching the tests')
372 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
373 group1.add_argument('--cfg', metavar='arg', help='add parameter --cfg=arg to each command line')
374 group1.add_argument('--log', metavar='arg', help='add parameter --log=arg to each command line')
375 group1.add_argument('--enable-coverage', action='store_true', help='ignore output lines starting with "profiling:"')
378 options = parser.parse_args()
382 if options.cd is not None:
385 if options.enable_coverage:
386 print("Enable coverage")
387 TeshState().ignore_regexps_common = [re.compile("^profiling:")]
389 if options.teshfile is None:
391 print("Test suite from stdin")
393 f = FileReader(options.teshfile)
394 print("Test suite '"+f.filename+"'")
396 if options.setenv is not None:
397 for e in options.setenv:
400 if options.cfg is not None:
401 TeshState().args_suffix += " --cfg="+options.cfg
402 if options.log is not None:
403 TeshState().args_suffix += " --log="+options.log
406 #cmd holds the current command line
407 # tech commands will add some parameters to it
408 # when ready, we execute it.
411 line = f.readfullline()
412 while line is not None:
413 #print(">>============="+line+"==<<")
415 #print ("END CMD block")
416 if cmd.run_if_possible():
422 elif line[0:2] == "p ":
423 print("["+str(FileReader())+"] "+line[2:])
425 elif line[0:2] == "< ":
426 cmd.add_input_pipe(line[2:])
427 elif line[0:1] == "<":
428 cmd.add_input_pipe(line[1:])
430 elif line[0:2] == "> ":
431 cmd.add_output_pipe_stdout(line[2:])
432 elif line[0:1] == ">":
433 cmd.add_output_pipe_stdout(line[1:])
435 elif line[0:2] == "$ ":
436 if cmd.run_if_possible():
438 cmd.set_cmd(line[2:], f.linenumber)
440 elif line[0:2] == "& ":
441 if cmd.run_if_possible():
443 cmd.set_cmd(line[2:], f.linenumber)
444 cmd.background = True
446 elif line[0:15] == "! output ignore":
447 cmd.ignore_output = True
448 #print("cmd.ignore_output = True")
449 elif line[0:16] == "! output display":
450 cmd.output_display = True
451 cmd.ignore_output = True
452 elif line[0:15] == "! expect return":
453 cmd.expect_return = int(line[16:])
454 #print("expect return "+str(int(line[16:])))
455 elif line[0:15] == "! expect signal":
457 #get the signal integer value from the signal module
458 if sig not in signal.__dict__:
459 fatal_error("unrecognized signal '"+sig+"'")
460 sig = int(signal.__dict__[sig])
461 #popen return -signal when a process ends with a signal
462 cmd.expect_return = -sig
463 elif line[0:len("! timeout ")] == "! timeout ":
464 if "no" in line[len("! timeout "):]:
467 cmd.timeout = int(line[len("! timeout "):])
469 elif line[0:len("! output sort")] == "! output sort":
470 if len(line) >= len("! output sort "):
471 sort = int(line[len("! output sort "):])
475 elif line[0:len("! setenv ")] == "! setenv ":
476 setenv(line[len("! setenv "):])
478 elif line[0:len("! ignore ")] == "! ignore ":
479 cmd.add_ignore(line[len("! ignore "):])
482 fatal_error("UNRECOGNIZED OPTION")
485 line = f.readfullline()
487 cmd.run_if_possible()
489 TeshState().join_all_threads()
491 if f.filename == "(stdin)":
492 print("Test suite from stdin OK")
494 print("Test suite `"+f.filename+"' OK")