blob: b6bed3e274db01f69fd5ba19818e95df3806c10e [file] [log] [blame]
adminbae64d82013-08-01 10:50:15 -07001#!/usr/bin/env python
2'''
3Created on 23-Oct-2012
4
5@authors: Anil Kumar (anilkumar.s@paxterrasolutions.com),
6 Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
7
8
9
10 TestON is free software: you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation, either version 2 of the License, or
13 (at your option) any later version.
14
15 TestON is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with TestON. If not, see <http://www.gnu.org/licenses/>.
22
23
24Utilities will take care about the basic functions like :
25 * Extended assertion,
26 * parse_args for key-value pair handling
27 * Parsing the params or topology file.
28
29'''
30import re
31from configobj import ConfigObj
32import pydoc
33from core import ast as ast
34import smtplib
35
36import mimetypes
37import email
38import os
39import email.mime.application
40
41class Utilities:
42 '''
43 Utilities will take care about the basic functions like :
44 * Extended assertion,
45 * parse_args for key-value pair handling
46 * Parsing the params or topology file.
47 '''
48
49 def __init__(self):
50 self.wrapped = sys.modules[__name__]
51
52 def __getattr__(self, name):
53 '''
54 This will invoke, if the attribute wasn't found the usual ways.
55 Here it will look for assert_attribute and will execute when AttributeError occurs.
56 It will return the result of the assert_attribute.
57 '''
58 try:
59 return getattr(self.wrapped, name)
60 except AttributeError:
61 def assertHandling(**kwargs):
62 nameVar = re.match("^assert",name,flags=0)
63 matchVar = re.match("assert(_not_|_)(equals|matches|greater|lesser)",name,flags=0)
64 notVar = 0
65 operators = ""
66
67 try :
68 if matchVar.group(1) == "_not_" and matchVar.group(2) :
69 notVar = 1
70 operators = matchVar.group(2)
71 elif matchVar.group(1) == "_" and matchVar.group(2):
72 operators = matchVar.group(2)
73
74 except AttributeError:
75 if matchVar==None and nameVar:
76 operators ='equals'
77
78 result = self._assert(NOT=notVar,operator=operators,**kwargs)
79 if result == main.TRUE:
80 main.log.info("Assertion Passed")
81 main.CASERESULT = main.TRUE
82 elif result == main.FALSE:
83 main.log.warn("Assertion Failed")
84 main.CASERESULT = main.FALSE
85
86 else :
87 main.log.error("There is an Error in Assertion")
88 main.CASERESULT = main.ERROR
89
90 return result
91
92 return assertHandling
93
94
95 def _assert (self,**assertParam):
96 '''
97 It will take the arguments :
98 expect:'Expected output'
99 actual:'Actual output'
100 onpass:'Action or string to be triggered or displayed respectively when the assert passed'
101 onfail:'Action or string to be triggered or displayed respectively when the assert failed'
102 not:'optional argument to specify the negation of the each assertion type'
103 operator:'assertion type will be defined by using operator. Like equal , greater, lesser, matches.'
104
105 It will return the assertion result.
106
107 '''
108
109 arguments = self.parse_args(["EXPECT","ACTUAL","ONPASS","ONFAIL","NOT","OPERATOR"],**assertParam)
110
111 result = 0
112 valuetype = ''
113 operation = "not "+ str(arguments["OPERATOR"]) if arguments['NOT'] and arguments['NOT'] == 1 else arguments["OPERATOR"]
114 operators = {'equals':{'STR':'==','NUM':'=='}, 'matches' : '=~', 'greater':'>' ,'lesser':'<'}
115
116 expectMatch = re.match('^\s*[+-]?0(e0)?\s*$', str(arguments["EXPECT"]), re.I+re.M)
117 if not ((not expectMatch) and (arguments["EXPECT"]==0)):
118 valuetype = 'NUM'
119 else :
120 if arguments["OPERATOR"] == 'greater' or arguments["OPERATOR"] == 'lesser':
121 main.log.error("Numeric comparison on strings is not possibele")
122 return main.ERROR
123
124 valuetype = 'STR'
125 arguments["ACTUAL"] = str(arguments["ACTUAL"])
126 if arguments["OPERATOR"] != 'matches':
127 arguments["EXPECT"] = str(arguments["EXPECT"])
128
129 try :
130 opcode = operators[str(arguments["OPERATOR"])][valuetype] if arguments["OPERATOR"] == 'equals' else operators[str(arguments["OPERATOR"])]
131
132 except KeyError:
133 print "Key Error in assertion"
134 return main.FALSE
135
136 if opcode == '=~':
137 try:
138 assert re.search(str(arguments["EXPECT"]),str(arguments["ACTUAL"]))
139 result = main.TRUE
140 except AssertionError:
141 try :
142 assert re.match(str(arguments["EXPECT"]),str(arguments["ACTUAL"]))
143 result = main.TRUE
144 except AssertionError:
145 main.log.error("Assertion Failed")
146 result = main.FALSE
147
148 else :
149 try:
150 if str(opcode)=="==":
151 main.log.info("Verifying the Expected is equal to the actual or not using assert_equal")
152 if (arguments["EXPECT"] == arguments["ACTUAL"]):
153 result = main.TRUE
154 else :
155 result = main.FALSE
156
157 elif str(opcode) == ">":
158 main.log.info("Verifying the Expected is Greater than the actual or not using assert_greater")
159 if (ast.literal_eval(arguments["EXPECT"]) > ast.literal_eval(arguments["ACTUAL"])) :
160 result = main.TRUE
161 else :
162 result = main.FALSE
163
164 elif str(opcode) == "<":
165 main.log.info("Verifying the Expected is Lesser than the actual or not using assert_lesser")
166 if (ast.literal_eval(arguments["EXPECT"]) < ast.literal_eval(arguments["ACTUAL"])):
167 result = main.TRUE
168 else :
169 result = main.FALSE
170
171
172 except AssertionError:
173 main.log.error("Assertion Failed")
174 result = main.FALSE
175
176
177 result = result if result else 0
178 result = not result if arguments["NOT"] and arguments["NOT"] == 1 else result
179 resultString = ""
180 if result :
181 resultString = str(resultString) + "PASS"
182 main.log.info(arguments["ONPASS"])
183 else :
184 resultString = str(resultString) + "FAIL"
185 if not isinstance(arguments["ONFAIL"],str):
186 eval(str(arguments["ONFAIL"]))
187 else :
188 main.log.error(arguments["ONFAIL"])
189 main.log.report(arguments["ONFAIL"])
190
191 msg = arguments["ON" + str(resultString)]
192
193 if not isinstance(msg,str):
194 try:
195 eval(str(msg))
196 except SyntaxError:
197 print "functin definition is not write"
198
199 main.last_result = result
200 return result
201
202
203 def parse_args(self,args, **kwargs):
204 '''
205 It will accept the (key,value) pair and will return the (key,value) pairs with keys in uppercase.
206 '''
207 newArgs = {}
208 for key,value in kwargs.iteritems():
209 #currentKey = str.upper(key)
210 if isinstance(args,list) and str.upper(key) in args:
211 for each in args:
212 if each==str.upper(key):
213 newArgs [str(each)] = value
214 elif each != str.upper(key) and (newArgs.has_key(str(each)) == False ):
215 newArgs[str(each)] = None
216
217
218
219 return newArgs
220
221 def send_mail(self):
222 # Create a text/plain message
223 msg = email.mime.Multipart.MIMEMultipart()
224 try :
225 if main.test_target:
226 sub = "Result summary of \""+main.TEST+"\" run on component \""+main.test_target+"\" Version \""+vars(main)[main.test_target].get_version()+"\": "+str(main.TOTAL_TC_SUCCESS)+"% Passed"
227 else :
228 sub = "Result summary of \""+main.TEST+"\": "+str(main.TOTAL_TC_SUCCESS)+"% Passed"
229 except KeyError,AttributeError:
230 sub = "Result summary of \""+main.TEST+"\": "+str(main.TOTAL_TC_SUCCESS)+"% Passed"
231
232 msg['Subject'] = sub
233 msg['From'] = 'paxweb@paxterrasolutions.com'
234 msg['To'] = main.mail
235 #msg['Cc'] = 'paxweb@paxterrasolutions.com'
236
237 # The main body is just another attachment
238 body = email.mime.Text.MIMEText(main.logHeader+"\n"+main.testResult)
239 msg.attach(body)
240
241 # Attachment
242 for filename in os.listdir(main.logdir):
243 filepath = main.logdir+"/"+filename
244 fp=open(filepath,'rb')
245 att = email.mime.application.MIMEApplication(fp.read(),_subtype="")
246 fp.close()
247 att.add_header('Content-Disposition','attachment',filename=filename)
248 msg.attach(att)
249
250 smtp = smtplib.SMTP('198.57.211.46')
251 smtp.starttls()
252 smtp.login('paxweb@paxterrasolutions.com','pax@peace')
253 smtp.sendmail(msg['From'],[msg['To']], msg.as_string())
254 smtp.quit()
255 return main.TRUE
256
257
258 def parse(self,fileName):
259 '''
260 This will parse the params or topo or cfg file and return content in the file as Dictionary
261 '''
262 self.fileName = fileName
263 matchFileName = re.match(r'(.*)\.(cfg|params|topo)',self.fileName,re.M|re.I)
264 if matchFileName:
265 try :
266 parsedInfo = ConfigObj(self.fileName)
267 return parsedInfo
268 except :
269 print "There is no such file to parse "+fileName
270 else:
271 return 0
272
273
274if __name__ != "__main__":
275 import sys
276
277 sys.modules[__name__] = Utilities()