blob: dda43bfa0ca87198570e64fe9f9f12e5f5f0cf19 [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)
adminbae64d82013-08-01 10:50:15 -070071 except AttributeError:
72 if matchVar==None and nameVar:
73 operators ='equals'
Jon Hall79bec222015-04-30 16:23:30 -070074 result = self._assert(NOT=notVar,operator=operators,**kwargs)
adminbae64d82013-08-01 10:50:15 -070075 if result == main.TRUE:
76 main.log.info("Assertion Passed")
Jon Hall79bec222015-04-30 16:23:30 -070077 main.STEPRESULT = main.TRUE
adminbae64d82013-08-01 10:50:15 -070078 elif result == main.FALSE:
79 main.log.warn("Assertion Failed")
Jon Hall79bec222015-04-30 16:23:30 -070080 main.STEPRESULT = main.FALSE
81 else:
adminbae64d82013-08-01 10:50:15 -070082 main.log.error("There is an Error in Assertion")
Jon Hall79bec222015-04-30 16:23:30 -070083 main.STEPRESULT = main.ERROR
adminbae64d82013-08-01 10:50:15 -070084 return result
adminbae64d82013-08-01 10:50:15 -070085 return assertHandling
Jon Hall79bec222015-04-30 16:23:30 -070086
adminbae64d82013-08-01 10:50:15 -070087 def _assert (self,**assertParam):
88 '''
89 It will take the arguments :
90 expect:'Expected output'
91 actual:'Actual output'
92 onpass:'Action or string to be triggered or displayed respectively when the assert passed'
93 onfail:'Action or string to be triggered or displayed respectively when the assert failed'
94 not:'optional argument to specify the negation of the each assertion type'
95 operator:'assertion type will be defined by using operator. Like equal , greater, lesser, matches.'
96
97 It will return the assertion result.
98
99 '''
100
101 arguments = self.parse_args(["EXPECT","ACTUAL","ONPASS","ONFAIL","NOT","OPERATOR"],**assertParam)
102
103 result = 0
104 valuetype = ''
105 operation = "not "+ str(arguments["OPERATOR"]) if arguments['NOT'] and arguments['NOT'] == 1 else arguments["OPERATOR"]
106 operators = {'equals':{'STR':'==','NUM':'=='}, 'matches' : '=~', 'greater':'>' ,'lesser':'<'}
107
108 expectMatch = re.match('^\s*[+-]?0(e0)?\s*$', str(arguments["EXPECT"]), re.I+re.M)
109 if not ((not expectMatch) and (arguments["EXPECT"]==0)):
110 valuetype = 'NUM'
111 else :
112 if arguments["OPERATOR"] == 'greater' or arguments["OPERATOR"] == 'lesser':
113 main.log.error("Numeric comparison on strings is not possibele")
114 return main.ERROR
115
116 valuetype = 'STR'
117 arguments["ACTUAL"] = str(arguments["ACTUAL"])
118 if arguments["OPERATOR"] != 'matches':
119 arguments["EXPECT"] = str(arguments["EXPECT"])
120
121 try :
122 opcode = operators[str(arguments["OPERATOR"])][valuetype] if arguments["OPERATOR"] == 'equals' else operators[str(arguments["OPERATOR"])]
123
124 except KeyError:
125 print "Key Error in assertion"
126 return main.FALSE
127
128 if opcode == '=~':
129 try:
130 assert re.search(str(arguments["EXPECT"]),str(arguments["ACTUAL"]))
131 result = main.TRUE
132 except AssertionError:
133 try :
134 assert re.match(str(arguments["EXPECT"]),str(arguments["ACTUAL"]))
135 result = main.TRUE
136 except AssertionError:
137 main.log.error("Assertion Failed")
138 result = main.FALSE
139
140 else :
141 try:
142 if str(opcode)=="==":
143 main.log.info("Verifying the Expected is equal to the actual or not using assert_equal")
144 if (arguments["EXPECT"] == arguments["ACTUAL"]):
145 result = main.TRUE
146 else :
147 result = main.FALSE
148
149 elif str(opcode) == ">":
150 main.log.info("Verifying the Expected is Greater than the actual or not using assert_greater")
151 if (ast.literal_eval(arguments["EXPECT"]) > ast.literal_eval(arguments["ACTUAL"])) :
152 result = main.TRUE
153 else :
154 result = main.FALSE
155
156 elif str(opcode) == "<":
157 main.log.info("Verifying the Expected is Lesser than the actual or not using assert_lesser")
158 if (ast.literal_eval(arguments["EXPECT"]) < ast.literal_eval(arguments["ACTUAL"])):
159 result = main.TRUE
160 else :
161 result = main.FALSE
162
163
164 except AssertionError:
165 main.log.error("Assertion Failed")
166 result = main.FALSE
167
168
169 result = result if result else 0
170 result = not result if arguments["NOT"] and arguments["NOT"] == 1 else result
171 resultString = ""
172 if result :
173 resultString = str(resultString) + "PASS"
174 main.log.info(arguments["ONPASS"])
175 else :
176 resultString = str(resultString) + "FAIL"
177 if not isinstance(arguments["ONFAIL"],str):
178 eval(str(arguments["ONFAIL"]))
179 else :
180 main.log.error(arguments["ONFAIL"])
181 main.log.report(arguments["ONFAIL"])
182
183 msg = arguments["ON" + str(resultString)]
184
185 if not isinstance(msg,str):
186 try:
187 eval(str(msg))
188 except SyntaxError:
189 print "functin definition is not write"
190
191 main.last_result = result
192 return result
193
194
195 def parse_args(self,args, **kwargs):
196 '''
197 It will accept the (key,value) pair and will return the (key,value) pairs with keys in uppercase.
198 '''
199 newArgs = {}
200 for key,value in kwargs.iteritems():
201 #currentKey = str.upper(key)
202 if isinstance(args,list) and str.upper(key) in args:
203 for each in args:
204 if each==str.upper(key):
205 newArgs [str(each)] = value
206 elif each != str.upper(key) and (newArgs.has_key(str(each)) == False ):
207 newArgs[str(each)] = None
208
209
210
211 return newArgs
212
213 def send_mail(self):
214 # Create a text/plain message
215 msg = email.mime.Multipart.MIMEMultipart()
216 try :
217 if main.test_target:
218 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"
219 else :
220 sub = "Result summary of \""+main.TEST+"\": "+str(main.TOTAL_TC_SUCCESS)+"% Passed"
221 except KeyError,AttributeError:
222 sub = "Result summary of \""+main.TEST+"\": "+str(main.TOTAL_TC_SUCCESS)+"% Passed"
223
224 msg['Subject'] = sub
225 msg['From'] = 'paxweb@paxterrasolutions.com'
226 msg['To'] = main.mail
227 #msg['Cc'] = 'paxweb@paxterrasolutions.com'
228
229 # The main body is just another attachment
230 body = email.mime.Text.MIMEText(main.logHeader+"\n"+main.testResult)
231 msg.attach(body)
232
233 # Attachment
234 for filename in os.listdir(main.logdir):
235 filepath = main.logdir+"/"+filename
236 fp=open(filepath,'rb')
237 att = email.mime.application.MIMEApplication(fp.read(),_subtype="")
238 fp.close()
239 att.add_header('Content-Disposition','attachment',filename=filename)
240 msg.attach(att)
241
242 smtp = smtplib.SMTP('198.57.211.46')
243 smtp.starttls()
244 smtp.login('paxweb@paxterrasolutions.com','pax@peace')
245 smtp.sendmail(msg['From'],[msg['To']], msg.as_string())
246 smtp.quit()
247 return main.TRUE
248
249
250 def parse(self,fileName):
251 '''
252 This will parse the params or topo or cfg file and return content in the file as Dictionary
253 '''
254 self.fileName = fileName
255 matchFileName = re.match(r'(.*)\.(cfg|params|topo)',self.fileName,re.M|re.I)
256 if matchFileName:
257 try :
258 parsedInfo = ConfigObj(self.fileName)
259 return parsedInfo
Jon Hallfebb1c72015-03-05 13:30:09 -0800260 except Exception:
adminbae64d82013-08-01 10:50:15 -0700261 print "There is no such file to parse "+fileName
262 else:
263 return 0
264
265
266if __name__ != "__main__":
267 import sys
268
269 sys.modules[__name__] = Utilities()