Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
tesh.py: if there is a wrapper, increase the timeout value
[simgrid.git] / tools / tesh / tesh.py
1 #! @PYTHON_EXECUTABLE@
2 # -*- coding: utf-8 -*-
3 """
4
5 tesh -- testing shell
6 ========================
7
8 Copyright (c) 2012-2016. The SimGrid Team.
9 All rights reserved.
10
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.
13
14
15 #TODO: child of child of child that printfs. Does it work?
16 #TODO: a child dies after its parent. What happen?
17
18 #TODO: regular expression in output
19 #ex: >> Time taken: [0-9]+s
20 #TODO: linked regular expression in output
21 #ex:
22 # >> Bytes sent: ([0-9]+)
23 # >> Bytes recv: \1
24 # then, even better:
25 # ! expect (\1 > 500)
26
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";
32 #    
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";
36
37
38 """
39
40
41 import sys, os
42 import shlex
43 import re
44 import difflib
45 import signal
46 import argparse
47
48 if sys.version_info[0] == 3:
49     import subprocess
50     import _thread
51 else:
52     raise "This program is expected to run with Python3 only"
53
54
55
56 ##############
57 #
58 # Utilities
59 #
60 #
61
62
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. """
67     _instances = {}
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
73
74 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
75     for n in dir(signal) if n.startswith('SIG') and '_' not in n )
76
77
78
79 #exit correctly
80 def exit(errcode):
81     #If you do not flush some prints are skipped
82     sys.stdout.flush()
83     #os._exit exit even when executed within a thread
84     os._exit(errcode)
85
86
87 def fatal_error(msg):
88     print("[Tesh/CRITICAL] "+str(msg))
89     exit(1)
90
91
92 #Set an environment variable.
93 # arg must be a string with the format "variable=value"
94 def setenv(arg):
95     print("[Tesh/INFO] setenv "+arg)
96     t = arg.split("=")
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
100
101
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))
105
106 # https://github.com/Cadair/jupyter_environment_kernels/issues/10
107 try:
108     FileNotFoundError
109 except NameError:
110     #py2
111     FileNotFoundError = OSError
112
113
114 ##############
115 #
116 # Classes
117 #
118 #
119
120
121
122 # read file line per line (and concat line that ends with "\")
123 class FileReader(Singleton):
124     def __init__(self, filename):
125         if filename is None:
126             self.filename = "(stdin)"
127             self.f = sys.stdin
128         else:
129             self.filename_raw = filename
130             self.filename = os.path.basename(filename)
131             self.f = open(self.filename_raw)
132         
133         self.linenumber = 0
134
135     def linenumber(self):
136         return self.linenumber
137     
138     def __repr__(self):
139         return self.filename+":"+str(self.linenumber)
140     
141     def readfullline(self):
142         try:
143             line = next(self.f)
144             self.linenumber += 1
145         except StopIteration:
146             return None
147         if line[-1] == "\n":
148             txt = line[0:-1]
149         else:
150             txt = line
151         while len(line) > 1 and line[-2] == "\\":
152             txt = txt[0:-1]
153             line = next(self.f)
154             self.linenumber += 1
155             txt += line[0:-1]
156         return txt
157
158
159 #keep the state of tesh (mostly configuration values)
160 class TeshState(Singleton):
161     def __init__(self):
162         self.threads = []
163         self.args_suffix = ""
164         self.ignore_regexps_common = []
165     
166     def add_thread(self, thread):
167         self.threads.append(thread)
168     
169     def join_all_threads(self):
170         for t in self.threads:
171             t.acquire()
172             t.release()
173
174 #Command line object
175 class Cmd(object):
176     def __init__(self):
177         self.input_pipe = []
178         self.output_pipe_stdout = []
179         self.output_pipe_stderr = []
180         self.timeout = 5
181         self.args = None
182         self.linenumber = -1
183         
184         self.background = False
185         self.cwd = None
186         
187         self.ignore_output = False
188         self.expect_return = 0
189         
190         self.output_display = False
191         
192         self.sort = -1
193         
194         self.ignore_regexps = TeshState().ignore_regexps_common
195
196     def add_input_pipe(self, l):
197         self.input_pipe.append(l)
198
199     def add_output_pipe_stdout(self, l):
200         self.output_pipe_stdout.append(l)
201
202     def add_output_pipe_stderr(self, l):
203         self.output_pipe_stderr.append(l)
204
205     def set_cmd(self, args, linenumber):
206         self.args = args
207         self.linenumber = linenumber
208     
209     def add_ignore(self, txt):
210         self.ignore_regexps.append(re.compile(txt))
211     
212     def remove_ignored_lines(self, lines):
213         for ign in self.ignore_regexps:
214                 lines = [l for l in lines if not ign.match(l)]
215         return lines
216
217
218     def _cmd_mkfile(self, argline):
219         filename = argline[len("mkfile "):]
220         file = open(filename, "w")
221         if file is None:
222             fatal_error("Unable to create file "+filename)
223         file.write("\n".join(self.input_pipe))
224         file.close()
225
226     def _cmd_cd(self, argline):
227         args = shlex.split(argline)
228         if len(args) != 2:
229             fatal_error("Too many arguments to cd")
230         try:
231             os.chdir(args[1])
232             print("[Tesh/INFO] change directory to "+args[1])
233         except FileNotFoundError:
234             print("Chdir to "+args[1]+" failed: No such file or directory")
235             print("Test suite `"+FileReader().filename+"': NOK (system error)")
236             exit(4)
237
238
239     #Run the Cmd if possible.
240     # Return False if nothing has been ran.
241     def run_if_possible(self):
242         if self.can_run():
243             if self.background:
244                 #Python threads loose the cwd
245                 self.cwd = os.getcwd()
246                 lock = _thread.allocate_lock()
247                 lock.acquire()
248                 TeshState().add_thread(lock)
249                 _thread.start_new_thread( Cmd._run, (self, lock) )
250             else:
251                 self._run()
252             return True
253         else:
254             return False
255
256
257     def _run(self, lock=None):
258         #Python threads loose the cwd
259         if self.cwd is not None:
260             os.chdir(self.cwd)
261             self.cwd = None
262         
263         #retrocompatibility: support ${aaa:=.} variable format
264         def replace_perl_variables(m):
265             vname = m.group(1)
266             vdefault = m.group(2)
267             if vname in os.environ:
268                 return "$"+vname
269             else:
270                 return vdefault
271         self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
272
273         #replace bash environment variables ($THINGS) to their values
274         self.args = expandvars2(self.args)
275         
276         if re.match("^mkfile ", self.args) is not None:
277             self._cmd_mkfile(self.args)
278             if lock is not None: lock.release()
279             return
280         
281         if re.match("^cd ", self.args) is not None:
282             self._cmd_cd(self.args)
283             if lock is not None: lock.release()
284             return
285         
286         self.args = TeshState().wrapper + self.args + TeshState().args_suffix
287         
288         print("["+FileReader().filename+":"+str(self.linenumber)+"] "+self.args)
289         
290         if TeshState().wrapper is not None:
291             self.timeout *= 20
292         
293         args = shlex.split(self.args)
294         #print (args)
295         try:
296             proc = subprocess.Popen(args, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
297         except OSError as e:
298             if e.errno == 8:
299                 e.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/bin/sh)"
300             raise e
301
302         try:
303             (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
304         except subprocess.TimeoutExpired:
305             print("Test suite `"+FileReader().filename+"': NOK (<"+FileReader().filename+":"+str(self.linenumber)+"> timeout after "+str(self.timeout)+" sec)")
306             exit(3)
307
308         if self.output_display:
309             print(stdout_data)
310
311         #remove text colors
312         ansi_escape = re.compile(r'\x1b[^m]*m')
313         stdout_data = ansi_escape.sub('', stdout_data)
314         
315         #print ((stdout_data, stderr_data))
316         
317         if self.ignore_output:
318             print("(ignoring the output of <"+FileReader().filename+":"+str(self.linenumber)+"> as requested)")
319         else:
320             stdouta = stdout_data.split("\n")
321             while len(stdouta) > 0 and stdouta[-1] == "":
322                 del stdouta[-1]
323             stdouta = self.remove_ignored_lines(stdouta)
324
325             #the "sort" bash command is case unsensitive,
326             # we mimic its behaviour
327             if self.sort == 0:
328                 stdouta.sort(key=lambda x: x.lower())
329                 self.output_pipe_stdout.sort(key=lambda x: x.lower())
330             elif self.sort > 0:
331                 stdouta.sort(key=lambda x: x[:self.sort].lower())
332                 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
333             
334             diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained'))
335             if len(diff) > 0: 
336                 print("Output of <"+FileReader().filename+":"+str(self.linenumber)+"> mismatch:")
337                 for line in diff:
338                     print(line)
339                 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> output mismatch)")
340                 if lock is not None: lock.release()
341                 exit(2)
342         
343         #print ((proc.returncode, self.expect_return))
344         
345         if proc.returncode != self.expect_return:
346             if proc.returncode >= 0:
347                 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> returned code "+str(proc.returncode)+")")
348                 if lock is not None: lock.release()
349                 exit(2)
350             else:
351                 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> got signal "+SIGNALS_TO_NAMES_DICT[-proc.returncode]+")")
352                 if lock is not None: lock.release()
353                 exit(-proc.returncode)
354             
355         if lock is not None: lock.release()
356     
357     
358     
359     def can_run(self):
360         return self.args is not None
361
362
363
364
365 ##############
366 #
367 # Main
368 #
369 #
370
371
372
373 if __name__ == '__main__':
374     
375     parser = argparse.ArgumentParser(description='tesh -- testing shell', add_help=True)
376     group1 = parser.add_argument_group('Options')
377     group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
378     group1.add_argument('--cd', metavar='some/directory', help='ask tesh to switch the working directory before launching the tests')
379     group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
380     group1.add_argument('--cfg', metavar='arg', help='add parameter --cfg=arg to each command line')
381     group1.add_argument('--log', metavar='arg', help='add parameter --log=arg to each command line')
382     group1.add_argument('--enable-coverage', action='store_true', help='ignore output lines starting with "profiling:"')
383     group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
384
385     try:
386         options = parser.parse_args()
387     except:
388         exit(1)
389
390     if options.cd is not None:
391         os.chdir(options.cd)
392
393     if options.enable_coverage:
394         print("Enable coverage")
395         TeshState().ignore_regexps_common = [re.compile("^profiling:")]
396     
397     if options.teshfile is None:
398         f = FileReader(None)
399         print("Test suite from stdin")
400     else:
401         f = FileReader(options.teshfile)
402         print("Test suite '"+f.filename+"'")
403     
404     if options.setenv is not None:
405         for e in options.setenv:
406             setenv(e)
407     
408     if options.cfg is not None:
409         TeshState().args_suffix += " --cfg="+options.cfg
410     if options.log is not None:
411         TeshState().args_suffix += " --log="+options.log
412
413     if options.wrapper is not None:
414         TeshState().wrapper = options.wrapper
415     
416     #cmd holds the current command line
417     # tech commands will add some parameters to it
418     # when ready, we execute it.
419     cmd = Cmd()
420     
421     line = f.readfullline()
422     while line is not None:
423         #print(">>============="+line+"==<<")
424         if len(line) == 0:
425             #print ("END CMD block")
426             if cmd.run_if_possible():
427                 cmd = Cmd()
428         
429         elif line[0] == "#":
430             pass
431         
432         elif line[0:2] == "p ":
433             print("["+str(FileReader())+"] "+line[2:])
434         
435         elif line[0:2] == "< ":
436             cmd.add_input_pipe(line[2:])
437         elif line[0:1] == "<":
438             cmd.add_input_pipe(line[1:])
439             
440         elif line[0:2] == "> ":
441             cmd.add_output_pipe_stdout(line[2:])
442         elif line[0:1] == ">":
443             cmd.add_output_pipe_stdout(line[1:])
444             
445         elif line[0:2] == "$ ":
446             if cmd.run_if_possible():
447                 cmd = Cmd()
448             cmd.set_cmd(line[2:], f.linenumber)
449         
450         elif line[0:2] == "& ":
451             if cmd.run_if_possible():
452                 cmd = Cmd()
453             cmd.set_cmd(line[2:], f.linenumber)
454             cmd.background = True
455         
456         elif line[0:15] == "! output ignore":
457             cmd.ignore_output = True
458             #print("cmd.ignore_output = True")
459         elif line[0:16] == "! output display":
460             cmd.output_display = True
461             cmd.ignore_output = True
462         elif line[0:15] == "! expect return":
463             cmd.expect_return = int(line[16:])
464             #print("expect return "+str(int(line[16:])))
465         elif line[0:15] == "! expect signal":
466             sig = line[16:]
467             #get the signal integer value from the signal module
468             if sig not in signal.__dict__:
469                 fatal_error("unrecognized signal '"+sig+"'")
470             sig = int(signal.__dict__[sig])
471             #popen return -signal when a process ends with a signal
472             cmd.expect_return = -sig
473         elif line[0:len("! timeout ")] == "! timeout ":
474             if "no" in line[len("! timeout "):]:
475                 cmd.timeout = None
476             else:
477                 cmd.timeout = int(line[len("! timeout "):])
478             
479         elif line[0:len("! output sort")] == "! output sort":
480             if len(line) >= len("! output sort "):
481                 sort = int(line[len("! output sort "):])
482             else:
483                 sort = 0
484             cmd.sort = sort
485         elif line[0:len("! setenv ")] == "! setenv ":
486             setenv(line[len("! setenv "):])
487         
488         elif line[0:len("! ignore ")] == "! ignore ":
489             cmd.add_ignore(line[len("! ignore "):])
490         
491         else:
492             fatal_error("UNRECOGNIZED OPTION")
493             
494         
495         line = f.readfullline()
496
497     cmd.run_if_possible()
498     
499     TeshState().join_all_threads()
500     
501     if f.filename == "(stdin)":
502         print("Test suite from stdin OK")
503     else:
504         print("Test suite `"+f.filename+"' OK")