more macros
[tests.git] / qaapi / qa / utils.py
1 # $Id$
2 import time
3 import os
4 from commands import getstatusoutput
5 from logger import Logfile
6
7 def header(message, log = True, logfile = Logfile('/var/log/qaapi')):
8     now=time.strftime("%H:%M:%S", time.localtime())
9     if isinstance(message, list):
10         message = "".join(message)   
11     output = "*"+now+'--'+message       
12     print output
13     if log:
14         print >> logfile, output        
15
16 def popen(command, fatal=True, verbose = False, logfile = Logfile('/var/log/qaapi.log')):
17     header(command)     
18     if verbose:
19         header(command, False)  
20     (stdin, stdout, stderr) = os.popen3(command)
21     output = stdout.readlines()
22     errors = stderr.readlines()         
23     print >> logfile, "+ "+command
24     print >> logfile, "".join(output).strip() 
25     # filter output generated by set x
26     remove_set_x = lambda line: not line.startswith("+")         
27     errors = filter(remove_set_x, errors)
28     
29     if fatal and errors:
30         raise Exception, "".join(errors)        
31     return (output, errors)    
32
33 def popen3(command, verbose = False, logfile = Logfile('/var/log/qaapi.log')):
34     if verbose:
35         header(command, False)
36     (stdin, stdout, stderr) = os.popen3(command)
37     print >> logfile, "+ "+command
38     return (stdin, stdout, stderr)                      
39     
40 def commands(command, fatal = True, verbose = False, logfile = Logfile('/var/log/qaapi.log')):
41     if verbose:
42         header(command, False)  
43     (status, output) = getstatusoutput(command)
44     print >> logfile, "+ "+command
45     print >> logfile, output.strip()            
46     if fatal and status == 256 and output:
47         raise Exception, "%(command)s Failed:\n%(output)s" % locals()
48     return (status, output)                      
49