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