Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
add header to fix build (numeric for iota)
[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 """
28
29
30 import sys, os
31 import shlex
32 import re
33 import difflib
34 import signal
35 import argparse
36
37 if sys.version_info[0] == 3:
38     import subprocess
39     import _thread
40 elif sys.version_info[0] < 3:
41     import subprocess32 as subprocess
42     import thread as _thread
43 else:
44     raise "This program has not been made to exist this long"
45
46
47
48 ##############
49 #
50 # Utilities
51 #
52 #
53
54
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. """
59     _instances = {}
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
65
66 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
67     for n in dir(signal) if n.startswith('SIG') and '_' not in n )
68
69
70
71 #exit correctly
72 def exit(errcode):
73     #If you do not flush some prints are skipped
74     sys.stdout.flush()
75     #os._exit exit even when executed within a thread
76     os._exit(errcode)
77
78
79 def fatal_error(msg):
80     print("[Tesh/CRITICAL] "+str(msg))
81     exit(1)
82
83
84 #Set an environment variable.
85 # arg must be a string with the format "variable=value"
86 def setenv(arg):
87     print("[Tesh/INFO] setenv "+arg)
88     t = arg.split("=")
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
92
93
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))
97
98 # https://github.com/Cadair/jupyter_environment_kernels/issues/10
99 try:
100     FileNotFoundError
101 except NameError:
102     #py2
103     FileNotFoundError = OSError
104
105
106 ##############
107 #
108 # Classes
109 #
110 #
111
112
113
114 # read file line per line (and concat line that ends with "\")
115 class FileReader(Singleton):
116     def __init__(self, filename):
117         if filename is None:
118             self.filename = "(stdin)"
119             self.f = sys.stdin
120         else:
121             self.filename_raw = filename
122             self.filename = os.path.basename(filename)
123             self.f = open(self.filename_raw)
124         
125         self.linenumber = 0
126
127     def linenumber(self):
128         return self.linenumber
129     
130     def __repr__(self):
131         return self.filename+":"+str(self.linenumber)
132     
133     def readfullline(self):
134         try:
135             line = next(self.f)
136             self.linenumber += 1
137         except StopIteration:
138             return None
139         if line[-1] == "\n":
140             txt = line[0:-1]
141         else:
142             txt = line
143         while len(line) > 1 and line[-2] == "\\":
144             txt = txt[0:-1]
145             line = next(self.f)
146             self.linenumber += 1
147             txt += line[0:-1]
148         return txt
149
150
151 #keep the state of tesh (mostly configuration values)
152 class TeshState(Singleton):
153     def __init__(self):
154         self.threads = []
155         self.args_suffix = ""
156         self.ignore_regexps_common = []
157     
158     def add_thread(self, thread):
159         self.threads.append(thread)
160     
161     def join_all_threads(self):
162         for t in self.threads:
163             t.acquire()
164             t.release()
165
166
167
168
169 #Command line object
170 class Cmd(object):
171     def __init__(self):
172         self.input_pipe = []
173         self.output_pipe_stdout = []
174         self.output_pipe_stderr = []
175         self.timeout = 5
176         self.args = None
177         self.linenumber = -1
178         
179         self.background = False
180         self.cwd = None
181         
182         self.ignore_output = False
183         self.expect_return = 0
184         
185         self.output_display = False
186         
187         self.sort = -1
188         
189         self.ignore_regexps = TeshState().ignore_regexps_common
190
191     def add_input_pipe(self, l):
192         self.input_pipe.append(l)
193
194     def add_output_pipe_stdout(self, l):
195         self.output_pipe_stdout.append(l)
196
197     def add_output_pipe_stderr(self, l):
198         self.output_pipe_stderr.append(l)
199
200     def set_cmd(self, args, linenumber):
201         self.args = args
202         self.linenumber = linenumber
203     
204     def add_ignore(self, txt):
205         self.ignore_regexps.append(re.compile(txt))
206     
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)]
210         return lines
211
212
213     def _cmd_mkfile(self, argline):
214         filename = argline[len("mkfile "):]
215         file = open(filename, "w")
216         if file is None:
217             fatal_error("Unable to create file "+filename)
218         file.write("\n".join(self.input_pipe))
219         file.close()
220
221     def _cmd_cd(self, argline):
222         args = shlex.split(argline)
223         if len(args) != 2:
224             fatal_error("Too many arguments to cd")
225         try:
226             os.chdir(args[1])
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)")
231             exit(4)
232
233
234     #Run the Cmd if possible.
235     # Return False if nothing has been ran.
236     def run_if_possible(self):
237         if self.can_run():
238             if self.background:
239                 #Python threads loose the cwd
240                 self.cwd = os.getcwd()
241                 lock = _thread.allocate_lock()
242                 lock.acquire()
243                 TeshState().add_thread(lock)
244                 _thread.start_new_thread( Cmd._run, (self, lock) )
245             else:
246                 self._run()
247             return True
248         else:
249             return False
250
251
252     def _run(self, lock=None):
253         #Python threads loose the cwd
254         if self.cwd is not None:
255             os.chdir(self.cwd)
256             self.cwd = None
257         
258         #retrocompatibility: support ${aaa:=.} variable format
259         def replace_perl_variables(m):
260             vname = m.group(1)
261             vdefault = m.group(2)
262             if vname in os.environ:
263                 return "$"+vname
264             else:
265                 return vdefault
266         self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
267
268         #replace bash environment variables ($THINGS) to their values
269         self.args = expandvars2(self.args)
270         
271         if re.match("^mkfile ", self.args) is not None:
272             self._cmd_mkfile(self.args)
273             if lock is not None: lock.release()
274             return
275         
276         if re.match("^cd ", self.args) is not None:
277             self._cmd_cd(self.args)
278             if lock is not None: lock.release()
279             return
280         
281         self.args += TeshState().args_suffix
282         
283         print("["+FileReader().filename+":"+str(self.linenumber)+"] "+self.args)
284         
285         args = shlex.split(self.args)
286         #print (args)
287         try:
288             proc = subprocess.Popen(args, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
289         except OSError as e:
290             if e.errno == 8:
291                 e.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/bin/sh)"
292             raise e
293
294         try:
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)")
298             exit(3)
299
300         if self.output_display:
301             print(stdout_data)
302
303         #remove text colors
304         ansi_escape = re.compile(r'\x1b[^m]*m')
305         stdout_data = ansi_escape.sub('', stdout_data)
306         
307         #print ((stdout_data, stderr_data))
308         
309         if self.ignore_output:
310             print("(ignoring the output of <"+FileReader().filename+":"+str(self.linenumber)+"> as requested)")
311         else:
312             stdouta = stdout_data.split("\n")
313             while len(stdouta) > 0 and stdouta[-1] == "":
314                 del stdouta[-1]
315             stdouta = self.remove_ignored_lines(stdouta)
316
317             #the "sort" bash command is case unsensitive,
318             # we mimic its behaviour
319             if self.sort == 0:
320                 stdouta.sort(key=lambda x: x.lower())
321                 self.output_pipe_stdout.sort(key=lambda x: x.lower())
322             elif self.sort > 0:
323                 stdouta.sort(key=lambda x: x[:self.sort].lower())
324                 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
325             
326             diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained'))
327             if len(diff) > 0: 
328                 print("Output of <"+FileReader().filename+":"+str(self.linenumber)+"> mismatch:")
329                 for line in diff:
330                     print(line)
331                 print("Test suite `"+FileReader().filename+"': NOK (<"+str(FileReader())+"> output mismatch)")
332                 if lock is not None: lock.release()
333                 exit(2)
334         
335         #print ((proc.returncode, self.expect_return))
336         
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()
341                 exit(2)
342             else:
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)
346             
347         if lock is not None: lock.release()
348     
349     
350     
351     def can_run(self):
352         return self.args is not None
353
354
355
356
357
358
359
360
361
362
363 ##############
364 #
365 # Main
366 #
367 #
368
369
370
371 if __name__ == '__main__':
372     
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:"')
381
382     try:
383         options = parser.parse_args()
384     except:
385         exit(1)
386
387     if options.cd is not None:
388         os.chdir(options.cd)
389
390     if options.enable_coverage:
391         print("Enable coverage")
392         TeshState().ignore_regexps_common = [re.compile("^profiling:")]
393     
394     if options.teshfile is None:
395         f = FileReader(None)
396         print("Test suite from stdin")
397     else:
398         f = FileReader(options.teshfile)
399         print("Test suite '"+f.filename+"'")
400     
401     if options.setenv is not None:
402         for e in options.setenv:
403             setenv(e)
404     
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
409     
410     
411     #cmd holds the current command line
412     # tech commands will add some parameters to it
413     # when ready, we execute it.
414     cmd = Cmd()
415     
416     line = f.readfullline()
417     while line is not None:
418         #print(">>============="+line+"==<<")
419         if len(line) == 0:
420             #print ("END CMD block")
421             if cmd.run_if_possible():
422                 cmd = Cmd()
423         
424         elif line[0] == "#":
425             pass
426         
427         elif line[0:2] == "p ":
428             print("["+str(FileReader())+"] "+line[2:])
429         
430         elif line[0:2] == "< ":
431             cmd.add_input_pipe(line[2:])
432         elif line[0:1] == "<":
433             cmd.add_input_pipe(line[1:])
434             
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:])
439             
440         elif line[0:2] == "$ ":
441             if cmd.run_if_possible():
442                 cmd = Cmd()
443             cmd.set_cmd(line[2:], f.linenumber)
444         
445         elif line[0:2] == "& ":
446             if cmd.run_if_possible():
447                 cmd = Cmd()
448             cmd.set_cmd(line[2:], f.linenumber)
449             cmd.background = True
450         
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":
461             sig = line[16:]
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 "):]:
470                 cmd.timeout = None
471             else:
472                 cmd.timeout = int(line[len("! timeout "):])
473             
474         elif line[0:len("! output sort")] == "! output sort":
475             if len(line) >= len("! output sort "):
476                 sort = int(line[len("! output sort "):])
477             else:
478                 sort = 0
479             cmd.sort = sort
480         elif line[0:len("! setenv ")] == "! setenv ":
481             setenv(line[len("! setenv "):])
482         
483         elif line[0:len("! ignore ")] == "! ignore ":
484             cmd.add_ignore(line[len("! ignore "):])
485         
486         else:
487             fatal_error("UNRECOGNIZED OPTION")
488             
489         
490         line = f.readfullline()
491
492     cmd.run_if_possible()
493     
494     TeshState().join_all_threads()
495     
496     if f.filename == "(stdin)":
497         print("Test suite from stdin OK")
498     else:
499         print("Test suite `"+f.filename+"' OK")
500
501
502
503
504