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]+)
37 if sys.version_info[0] == 3:
40 elif sys.version_info[0] < 3:
41 import subprocess32 as subprocess
42 import thread as _thread
44 raise "This program has not been made to exist this long"
55 # Singleton metaclass that works in Python 2 & 3
56 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
57 class _Singleton(type):
58 """ A metaclass that creates a Singleton base class when called. """
60 def __call__(cls, *args, **kwargs):
61 if cls not in cls._instances:
62 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
63 return cls._instances[cls]
64 class Singleton(_Singleton('SingletonMeta', (object,), {})): pass
66 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
67 for n in dir(signal) if n.startswith('SIG') and '_' not in n )
73 #If you do not flush some prints are skipped
75 #os._exit exit even when executed within a thread
80 print("[Tesh/CRITICAL] "+str(msg))
84 #Set an environment variable.
85 # arg must be a string with the format "variable=value"
87 print("[Tesh/INFO] setenv "+arg)
89 os.environ[t[0]] = t[1]
90 #os.putenv(t[0], t[1]) does not work
91 #see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env
94 #http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does
95 def expandvars2(path):
96 return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path))
98 # https://github.com/Cadair/jupyter_environment_kernels/issues/10
103 FileNotFoundError = OSError
114 # read file line per line (and concat line that ends with "\")
115 class FileReader(Singleton):
116 def __init__(self, filename):
118 self.filename = "(stdin)"
121 self.filename_raw = filename
122 self.filename = os.path.basename(filename)
123 self.f = open(self.filename_raw)
127 def linenumber(self):
128 return self.linenumber
131 return self.filename+":"+str(self.linenumber)
133 def readfullline(self):
137 except StopIteration:
143 while len(line) > 1 and line[-2] == "\\":
151 #keep the state of tesh (mostly configuration values)
152 class TeshState(Singleton):
155 self.args_suffix = ""
156 self.ignore_regexps_common = []
158 def add_thread(self, thread):
159 self.threads.append(thread)
161 def join_all_threads(self):
162 for t in self.threads:
173 self.output_pipe_stdout = []
174 self.output_pipe_stderr = []
179 self.background = False
182 self.ignore_output = False
183 self.expect_return = 0
185 self.output_display = False
189 self.ignore_regexps = TeshState().ignore_regexps_common
191 def add_input_pipe(self, l):
192 self.input_pipe.append(l)
194 def add_output_pipe_stdout(self, l):
195 self.output_pipe_stdout.append(l)
197 def add_output_pipe_stderr(self, l):
198 self.output_pipe_stderr.append(l)
200 def set_cmd(self, args, linenumber):
202 self.linenumber = linenumber
204 def add_ignore(self, txt):
205 self.ignore_regexps.append(re.compile(txt))
207 def remove_ignored_lines(self, lines):
208 for ign in self.ignore_regexps:
209 lines = [l for l in lines if not ign.match(l)]
213 def _cmd_mkfile(self, argline):
214 filename = argline[len("mkfile "):]
215 file = open(filename, "w")
217 fatal_error("Unable to create file "+filename)
218 file.write("\n".join(self.input_pipe))
221 def _cmd_cd(self, argline):
222 args = shlex.split(argline)
224 fatal_error("Too many arguments to cd")
227 print("[Tesh/INFO] change directory to "+args[1])
228 except FileNotFoundError:
229 print("Chdir to "+args[1]+" failed: No such file or directory")
230 print("Test suite `"+FileReader().filename+"': NOK (system error)")
234 #Run the Cmd if possible.
235 # Return False if nothing has been ran.
236 def run_if_possible(self):
239 #Python threads loose the cwd
240 self.cwd = os.getcwd()
241 lock = _thread.allocate_lock()
243 TeshState().add_thread(lock)
244 _thread.start_new_thread( Cmd._run, (self, lock) )
252 def _run(self, lock=None):
253 #Python threads loose the cwd
254 if self.cwd is not None:
258 #retrocompatibility: support ${aaa:=.} variable format
259 def replace_perl_variables(m):
261 vdefault = m.group(2)
262 if vname in os.environ:
266 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
268 #replace bash environment variables ($THINGS) to their values
269 self.args = expandvars2(self.args)
271 if re.match("^mkfile ", self.args) is not None:
272 self._cmd_mkfile(self.args)
273 if lock is not None: lock.release()
276 if re.match("^cd ", self.args) is not None:
277 self._cmd_cd(self.args)
278 if lock is not None: lock.release()
281 self.args += TeshState().args_suffix
283 print("["+FileReader().filename+":"+str(self.linenumber)+"] "+self.args)
285 args = shlex.split(self.args)
288 proc = subprocess.Popen(args, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
291 e.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/bin/sh)"
295 (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
296 except subprocess.TimeoutExpired:
297 print("Test suite `"+FileReader().filename+"': NOK (<"+FileReader().filename+":"+str(self.linenumber)+"> timeout after "+str(self.timeout)+" sec)")
300 if self.output_display:
304 ansi_escape = re.compile(r'\x1b[^m]*m')
305 stdout_data = ansi_escape.sub('', stdout_data)
307 #print ((stdout_data, stderr_data))
309 if self.ignore_output:
310 print("(ignoring the output of <"+FileReader().filename+":"+str(self.linenumber)+"> as requested)")
312 stdouta = stdout_data.split("\n")
313 while len(stdouta) > 0 and stdouta[-1] == "":
315 stdouta = self.remove_ignored_lines(stdouta)
317 #the "sort" bash command is case unsensitive,
318 # we mimic its behaviour
320 stdouta.sort(key=lambda x: x.lower())
321 self.output_pipe_stdout.sort(key=lambda x: x.lower())
323 stdouta.sort(key=lambda x: x[:self.sort].lower())
324 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
326 diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained'))
328 print("Output of <"+FileReader().filename+":"+str(self.linenumber)+"> mismatch:")
331 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> output mismatch)")
332 if lock is not None: lock.release()
335 #print ((proc.returncode, self.expect_return))
337 if proc.returncode != self.expect_return:
338 if proc.returncode >= 0:
339 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> returned code "+str(proc.returncode)+")")
340 if lock is not None: lock.release()
343 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> got signal "+SIGNALS_TO_NAMES_DICT[-proc.returncode]+")")
344 if lock is not None: lock.release()
345 exit(-proc.returncode)
347 if lock is not None: lock.release()
352 return self.args is not None
371 if __name__ == '__main__':
373 parser = argparse.ArgumentParser(description='tesh -- testing shell', add_help=True)
374 group1 = parser.add_argument_group('Options')
375 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
376 group1.add_argument('--cd', metavar='some/directory', help='ask tesh to switch the working directory before launching the tests')
377 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
378 group1.add_argument('--cfg', metavar='arg', help='add parameter --cfg=arg to each command line')
379 group1.add_argument('--log', metavar='arg', help='add parameter --log=arg to each command line')
380 group1.add_argument('--enable-coverage', action='store_true', help='ignore output lines starting with "profiling:"')
383 options = parser.parse_args()
387 if options.cd is not None:
390 if options.enable_coverage:
391 print("Enable coverage")
392 TeshState().ignore_regexps_common = [re.compile("^profiling:")]
394 if options.teshfile is None:
396 print("Test suite from stdin")
398 f = FileReader(options.teshfile)
399 print("Test suite '"+f.filename+"'")
401 if options.setenv is not None:
402 for e in options.setenv:
405 if options.cfg is not None:
406 TeshState().args_suffix += " --cfg="+options.cfg
407 if options.log is not None:
408 TeshState().args_suffix += " --log="+options.log
411 #cmd holds the current command line
412 # tech commands will add some parameters to it
413 # when ready, we execute it.
416 line = f.readfullline()
417 while line is not None:
418 #print(">>============="+line+"==<<")
420 #print ("END CMD block")
421 if cmd.run_if_possible():
427 elif line[0:2] == "p ":
428 print("["+str(FileReader())+"] "+line[2:])
430 elif line[0:2] == "< ":
431 cmd.add_input_pipe(line[2:])
432 elif line[0:1] == "<":
433 cmd.add_input_pipe(line[1:])
435 elif line[0:2] == "> ":
436 cmd.add_output_pipe_stdout(line[2:])
437 elif line[0:1] == ">":
438 cmd.add_output_pipe_stdout(line[1:])
440 elif line[0:2] == "$ ":
441 if cmd.run_if_possible():
443 cmd.set_cmd(line[2:], f.linenumber)
445 elif line[0:2] == "& ":
446 if cmd.run_if_possible():
448 cmd.set_cmd(line[2:], f.linenumber)
449 cmd.background = True
451 elif line[0:15] == "! output ignore":
452 cmd.ignore_output = True
453 #print("cmd.ignore_output = True")
454 elif line[0:16] == "! output display":
455 cmd.output_display = True
456 cmd.ignore_output = True
457 elif line[0:15] == "! expect return":
458 cmd.expect_return = int(line[16:])
459 #print("expect return "+str(int(line[16:])))
460 elif line[0:15] == "! expect signal":
462 #get the signal integer value from the signal module
463 if sig not in signal.__dict__:
464 fatal_error("unrecognized signal '"+sig+"'")
465 sig = int(signal.__dict__[sig])
466 #popen return -signal when a process ends with a signal
467 cmd.expect_return = -sig
468 elif line[0:len("! timeout ")] == "! timeout ":
469 if "no" in line[len("! timeout "):]:
472 cmd.timeout = int(line[len("! timeout "):])
474 elif line[0:len("! output sort")] == "! output sort":
475 if len(line) >= len("! output sort "):
476 sort = int(line[len("! output sort "):])
480 elif line[0:len("! setenv ")] == "! setenv ":
481 setenv(line[len("! setenv "):])
483 elif line[0:len("! ignore ")] == "! ignore ":
484 cmd.add_ignore(line[len("! ignore "):])
487 fatal_error("UNRECOGNIZED OPTION")
490 line = f.readfullline()
492 cmd.run_if_possible()
494 TeshState().join_all_threads()
496 if f.filename == "(stdin)":
497 print("Test suite from stdin OK")
499 print("Test suite `"+f.filename+"' OK")