blob: 7abed251619698ea1b05cbfffde69b021486e8de [file] [log] [blame]
adminbae64d82013-08-01 10:50:15 -07001#/usr/bin/env python
2'''
3Created on 07-Jan-2013
Jon Hall81d3d392015-04-24 14:40:35 -07004
adminbae64d82013-08-01 10:50:15 -07005@author: Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
6
7 TestON is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
11
12 TestON is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
Jon Hall81d3d392015-04-24 14:40:35 -070018 along with TestON. If not, see <http://www.gnu.org/licenses/>.
adminbae64d82013-08-01 10:50:15 -070019
20
21'''
22
23import logging
24import datetime
25import re
26import os
27class Logger:
28 '''
29 Add continuous logs and reports of the test.
Jon Hall81d3d392015-04-24 14:40:35 -070030
adminbae64d82013-08-01 10:50:15 -070031 @author: Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
32 '''
33 def _printHeader(self,main) :
34 '''
35 Log's header will be append to the Log file
36 '''
37 logmsg = "\n"+" " * 32+"+----------------+\n" +"-" * 30+" { Script And Files } "+"-" * 30+"\n" +" " * 32+"+----------------+\n";
38 logmsg = logmsg + "\n\tScript Log File : " + main.LogFileName + ""
39 logmsg = logmsg + "\n\tReport Log File : " + main.ReportFileName + ""
40 for component in main.componentDictionary.keys():
41 logmsg = logmsg + "\n\t"+component+" Session Log : " + main.logdir+"/"+component+".session" + ""
Jon Hall81d3d392015-04-24 14:40:35 -070042
adminbae64d82013-08-01 10:50:15 -070043 logmsg = logmsg + "\n\tTest Script :" + path + "Tests/" + main.TEST + ".py"+ ""
44 logmsg = logmsg + "\n\tTest Params : " + path + "Tests/" + main.TEST + ".params" + ""
Jon Hall368769f2014-11-19 15:43:35 -080045 logmsg = logmsg + "\n\tTopology : " + path + "Tests/" +main.TEST + ".topo" + ""
adminbae64d82013-08-01 10:50:15 -070046 logmsg = logmsg + "\n"+" " * 30+"+" +"-" * 18+"+" +"\n" +"-" * 27+" { Script Exec Params } "+"-" * 27 +"\n" +" " * 30 +"+"+"-" * 18 +"+\n";
47 values = "\n\t" + str(main.params)
48 values = re.sub(",", "\n\t", values)
49 values = re.sub("{", "\n\t", values)
50 values = re.sub("}", "\n\t", values)
51 logmsg = logmsg + values
adminbae64d82013-08-01 10:50:15 -070052 logmsg = logmsg + "\n\n"+" " * 31+"+---------------+\n" +"-" * 29+" { Components Used } " +"-" * 29+"\n"+" " * 31+"+---------------+\n"
53 component_list = []
54 component_list.append(None)
Jon Hall81d3d392015-04-24 14:40:35 -070055
adminbae64d82013-08-01 10:50:15 -070056 # Listing the components in the order of test_target component should be first.
57 if type(main.componentDictionary) == dict:
58 for key in main.componentDictionary.keys():
59 if main.test_target == key :
60 component_list[0] = key+"-Test Target"
61 else :
62 component_list.append(key)
Jon Hall81d3d392015-04-24 14:40:35 -070063
adminbae64d82013-08-01 10:50:15 -070064 for index in range(len(component_list)) :
65 if index==0:
66 if component_list[index]:
67 logmsg+="\t"+component_list[index]+"\n"
68 elif index > 0 :
69 logmsg+="\t"+str(component_list[index])+"\n"
Jon Hall81d3d392015-04-24 14:40:35 -070070
adminbae64d82013-08-01 10:50:15 -070071 logmsg = logmsg + "\n\n"+" " * 30+"+--------+\n" +"-" * 28+" { Topology } "+"-" * 28 +"\n" +" " * 30+"+--------+\n"
72 values = "\n\t" + str(main.topology['COMPONENT'])
73 values = re.sub(",", "\n\t", values)
74 values = re.sub("{", "\n\t", values)
75 values = re.sub("}", "\n\t", values)
76 logmsg = logmsg + values
adminbae64d82013-08-01 10:50:15 -070077 logmsg = logmsg + "\n"+"-" * 60+"\n"
Jon Hall81d3d392015-04-24 14:40:35 -070078
adminbae64d82013-08-01 10:50:15 -070079 # enter into log file all headers
80 logfile = open(main.LogFileName,"w+")
81 logfile.write (logmsg)
82 print logmsg
83 main.logHeader = logmsg
adminbae64d82013-08-01 10:50:15 -070084 logfile.close()
Jon Hall81d3d392015-04-24 14:40:35 -070085
adminbae64d82013-08-01 10:50:15 -070086 #enter into report file all headers
87 main.reportFile = open(main.ReportFileName,"w+")
88 main.reportFile.write(logmsg)
89 main.reportFile.close()
Jon Hall81d3d392015-04-24 14:40:35 -070090
Jon Hall79bec222015-04-30 16:23:30 -070091 #Sumamry file header
92 currentTime = str( main.STARTTIME.strftime("%d %b %Y %H:%M:%S") )
93 main.summaryFile = open( main.SummaryFileName, "w+" )
94 main.summaryFile.write( main.TEST + " at " + currentTime + "\n" )
95 main.summaryFile.close()
96
Jon Hall81d3d392015-04-24 14:40:35 -070097 #wiki file header
98 currentTime = str( main.STARTTIME.strftime("%d %b %Y %H:%M:%S") )
99 main.wikiFile = open( main.WikiFileName, "w+" )
Jon Hall79bec222015-04-30 16:23:30 -0700100 main.wikiFile.write( main.TEST + " at " + currentTime + "<p></p>\n" )
Jon Hall81d3d392015-04-24 14:40:35 -0700101 main.wikiFile.close()
102
adminbae64d82013-08-01 10:50:15 -0700103 def initlog(self,main):
104 '''
105 Initialise all the log handles.
106 '''
107 main._getTest()
Jon Hall81d3d392015-04-24 14:40:35 -0700108 main.STARTTIME = datetime.datetime.now()
adminbae64d82013-08-01 10:50:15 -0700109
110 currentTime = re.sub("-|\s|:|\.", "_", str(main.STARTTIME.strftime("%d %b %Y %H:%M:%S")))
111 if main.logdir:
112 main.logdir = main.logdir+ "/"+main.TEST + "_" + currentTime
113 else:
114 main.logdir = main.logs_path + main.TEST + "_" + currentTime
Jon Hall81d3d392015-04-24 14:40:35 -0700115
adminbae64d82013-08-01 10:50:15 -0700116 os.mkdir(main.logdir)
Jon Hall81d3d392015-04-24 14:40:35 -0700117
adminbae64d82013-08-01 10:50:15 -0700118 main.LogFileName = main.logdir + "/" + main.TEST + "_" +str(currentTime) + ".log"
119 main.ReportFileName = main.logdir + "/" + main.TEST + "_" + str(currentTime) + ".rpt"
Jon Hall79bec222015-04-30 16:23:30 -0700120 main.WikiFileName = main.logdir + "/" + main.TEST + "Wiki.txt"
Jon Hallef822822016-02-19 10:36:47 -0800121 main.DemoCodeFileName = main.logdir + "/" + main.TEST + "-DemoCode.txt"
122 main.DemoSummaryFileName = main.logdir + "/" + main.TEST + "-DemoSummary.txt"
Jon Hall79bec222015-04-30 16:23:30 -0700123 main.SummaryFileName = main.logdir + "/" + main.TEST + "Summary.txt"
Jon Hall94fd0472014-12-08 11:52:42 -0800124 main.JenkinsCSV = main.logdir + "/" + main.TEST + ".csv"
Jon Hall25079782015-10-13 13:54:39 -0700125 main.TOTAL_TC_SUCCESS = 0
Jon Hall81d3d392015-04-24 14:40:35 -0700126
adminbae64d82013-08-01 10:50:15 -0700127 #### Add log-level - Report
128 logging.addLevelName(9, "REPORT")
129 logging.addLevelName(7, "EXACT")
Jon Hall0bde9ba2015-03-19 11:32:57 -0700130 logging.addLevelName(11, "CASE")
131 logging.addLevelName(12, "STEP")
adminbae64d82013-08-01 10:50:15 -0700132 main.log = logging.getLogger(main.TEST)
Jon Hall81d3d392015-04-24 14:40:35 -0700133 def report(msg):
adminbae64d82013-08-01 10:50:15 -0700134 '''
135 Will append the report message to the logs.
136 '''
137 main.log._log(9,msg,"OpenFlowAutoMattion","OFAutoMation")
138 currentTime = datetime.datetime.now()
139 currentTime = currentTime.strftime("%d %b %Y %H:%M:%S")
140 newmsg = "\n[REPORT] " +"["+ str(currentTime)+"] "+msg
141 print newmsg
142 main.reportFile = open(main.ReportFileName,"a+")
143 main.reportFile.write(newmsg)
144 main.reportFile.close()
Jon Hall81d3d392015-04-24 14:40:35 -0700145
146 main.log.report = report
147
Jon Hall79bec222015-04-30 16:23:30 -0700148 def summary( msg ):
149 '''
150 Will append the message to the txt file for the summary.
151 '''
152 main.log._log(6,msg,"OpenFlowAutoMattion","OFAutoMation")
153 main.summaryFile = open(main.SummaryFileName,"a+")
154 main.summaryFile.write(msg+"\n")
155 main.summaryFile.close()
156
157 main.log.summary = summary
158
Jon Hall81d3d392015-04-24 14:40:35 -0700159 def wiki( msg ):
160 '''
161 Will append the message to the txt file for the wiki.
162 '''
163 main.log._log(6,msg,"OpenFlowAutoMattion","OFAutoMation")
164 main.wikiFile = open(main.WikiFileName,"a+")
165 main.wikiFile.write(msg+"\n")
166 main.wikiFile.close()
167
168 main.log.wiki = wiki
169
Jon Hallef822822016-02-19 10:36:47 -0800170 def demoCode( msg ):
171 '''
172 Will append the message to the txt file for the Demo.
173 '''
174 colors = { 'cyan': '\033[96m', 'purple': '\033[95m',
175 'blue': '\033[94m', 'green': '\033[92m',
176 'yellow': '\033[93m', 'red': '\033[91m',
177 'end': '\033[0m' }
178
179 main.demoCodeFile = open( main.DemoCodeFileName, "a+" )
180 parsedMsg = ''
181 wrapped = False
182 for line in msg.splitlines():
183 if wrapped:
184 parsedMsg += line
185 if ')' in line:
186 wrapped = False
187 parsedMsg += colors['end']
188 elif "main.case(" in line:
189 parsedMsg += colors['cyan'] + line + colors['end']
190 elif "main.step" in line:
191 parsedMsg += colors['red'] + line + colors['end']
192 elif "utilities.assert_" in line and "(" in line:
193 parsedMsg += colors['purple'] + line
194 if ')' not in line:
195 wrapped = True
196 else:
197 parsedMsg += colors['end']
198 else:
199 parsedMsg += line
200 parsedMsg += '\n'
201 main.demoCodeFile.write( parsedMsg + "\n" )
202 main.demoCodeFile.close()
203
204 main.log.demo = demoCode
205
206 def demoSummary( msg, level=None ):
207 '''
208 Will append the message to the txt file for the Demo.
209 '''
210 colors = { 'cyan': '\033[96m', 'purple': '\033[95m',
211 'blue': '\033[94m', 'green': '\033[92m',
212 'yellow': '\033[93m', 'red': '\033[91m',
213 'end': '\033[0m' }
214
215 main.demoSummaryFile = open( main.DemoSummaryFileName, "a+" )
216 parsedMsg = ''
217 if level is None:
218 parsedMsg += msg
219 elif level.lower() == "case":
220 parsedMsg += colors['cyan'] + "CASE:" + msg
221 elif level.lower() == "step":
222 parsedMsg += colors['yellow'] + "\tSTEP:"
223 parsedMsg += msg[ msg.find( ':' ) + 1 :]
224 parsedMsg += colors['end']
225 main.demoSummaryFile.write( parsedMsg + "\n" )
226 main.demoSummaryFile.close()
227
228 main.log.demoSummary = demoSummary
229
230
231
Jon Hall81d3d392015-04-24 14:40:35 -0700232 def exact(exmsg):
adminbae64d82013-08-01 10:50:15 -0700233 '''
234 Will append the raw formatted message to the logs
235 '''
236 main.log._log(7,exmsg,"OpenFlowAutoMattion","OFAutoMation")
237 main.reportFile = open(main.ReportFileName,"a+")
238 main.reportFile.write(exmsg)
239 main.reportFile.close()
240 logfile = open(main.LogFileName,"a")
241 logfile.write("\n"+ str(exmsg) +"\n")
242 logfile.close()
243 print exmsg
Jon Hall81d3d392015-04-24 14:40:35 -0700244
245 main.log.exact = exact
246
adminbae64d82013-08-01 10:50:15 -0700247 def case(msg):
248 '''
249 Format of the case type log defined here.
250 '''
251 main.log._log(9,msg,"OpenFlowAutoMattion","OFAutoMation")
252 currentTime = datetime.datetime.now()
253 newmsg = "["+str(currentTime)+"] " + "["+main.TEST+"] " + "[CASE] " +msg
254 logfile = open(main.LogFileName,"a")
255 logfile.write("\n"+ str(newmsg) +"\n")
256 logfile.close()
Jon Hallef822822016-02-19 10:36:47 -0800257 main.log.demoSummary( msg, "case" )
adminbae64d82013-08-01 10:50:15 -0700258 print newmsg
Jon Hall81d3d392015-04-24 14:40:35 -0700259
Jon Hall4ba53f02015-07-29 13:07:41 -0700260 main.log.case = case
Jon Hall81d3d392015-04-24 14:40:35 -0700261
262 def step(msg):
adminbae64d82013-08-01 10:50:15 -0700263 '''
264 Format of the step type log defined here.
265 '''
266 main.log._log(9,msg,"OpenFlowAutoMattion","OFAutoMation")
267 currentTime = datetime.datetime.now()
268 newmsg = "["+str(currentTime)+"] " + "["+main.TEST+"] " + "[STEP] " +msg
269 logfile = open(main.LogFileName,"a")
270 logfile.write("\n"+ str(newmsg) +"\n")
271 logfile.close()
Jon Hallef822822016-02-19 10:36:47 -0800272 main.log.demoSummary( msg, "step" )
adminbae64d82013-08-01 10:50:15 -0700273 print newmsg
Jon Hall81d3d392015-04-24 14:40:35 -0700274
275 main.log.step = step
276
adminbae64d82013-08-01 10:50:15 -0700277 main.LogFileHandler = logging.FileHandler(main.LogFileName)
278 self._printHeader(main)
279
280 ### initializing logging module and settig log level
281 main.log.setLevel(logging.INFO)
Jon Hall0bde9ba2015-03-19 11:32:57 -0700282 main.log.setLevel(logging.DEBUG) # Temporary
adminbae64d82013-08-01 10:50:15 -0700283 main.LogFileHandler.setLevel(logging.INFO)
Jon Hall81d3d392015-04-24 14:40:35 -0700284
adminbae64d82013-08-01 10:50:15 -0700285 # create console handler with a higher log level
286 main.ConsoleHandler = logging.StreamHandler()
287 main.ConsoleHandler.setLevel(logging.INFO)
Jon Hall0bde9ba2015-03-19 11:32:57 -0700288 main.ConsoleHandler.setLevel(logging.DEBUG) #Temporary
adminbae64d82013-08-01 10:50:15 -0700289 # create formatter and add it to the handlers
Jon Hall0bde9ba2015-03-19 11:32:57 -0700290 #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
291 class MyFormatter( logging.Formatter ):
292 colors = { 'cyan': '\033[96m', 'purple': '\033[95m',
293 'blue': '\033[94m', 'green': '\033[92m',
294 'yellow': '\033[93m', 'red': '\033[91m',
295 'end': '\033[0m' }
296
297 FORMATS = {'DEFAULT': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'}
298 if COLORS: # NOTE:colors will only be loaded if command is run from one line
299 # IE: './cli.py run testname'
300 # This is to prevent issues with Jenkins parsing
301 # TODO: Make colors configurable
302 levels = { logging.ERROR : colors['red'] +
303 FORMATS['DEFAULT'] +
304 colors['end'],
305 logging.WARN : colors['yellow'] +
306 FORMATS['DEFAULT'] +
307 colors['end'],
308 logging.DEBUG : colors['purple'] +
309 FORMATS['DEFAULT'] +
310 colors['end'] }
311 FORMATS.update( levels )
312
313 def format( self, record ):
314 self._fmt = self.FORMATS.get( record.levelno,
315 self.FORMATS[ 'DEFAULT' ] )
316 return logging.Formatter.format( self, record )
317 formatter = MyFormatter()
adminbae64d82013-08-01 10:50:15 -0700318 main.ConsoleHandler.setFormatter(formatter)
319 main.LogFileHandler.setFormatter(formatter)
320
321 # add the handlers to logger
322 main.log.addHandler(main.ConsoleHandler)
323 main.log.addHandler(main.LogFileHandler)
Jon Hall81d3d392015-04-24 14:40:35 -0700324
adminbae64d82013-08-01 10:50:15 -0700325 def testSummary(self,main):
326 '''
327 testSummary will take care about the Summary of test.
328 '''
329
330 main.ENDTIME = datetime.datetime.now()
331 main.EXECTIME = main.ENDTIME - main.STARTTIME
332 if (main.TOTAL_TC_PASS == 0):
333 main.TOTAL_TC_SUCCESS = 0
334 else:
335 main.TOTAL_TC_SUCCESS = str((main.TOTAL_TC_PASS*100)/main.TOTAL_TC_RUN)
adminbae64d82013-08-01 10:50:15 -0700336 if (main.TOTAL_TC_RUN == 0) :
337 main.TOTAL_TC_EXECPERCENT = 0
338 else :
339 main.TOTAL_TC_EXECPERCENT = str((main.TOTAL_TC_RUN*100)/main.TOTAL_TC_PLANNED)
adminbae64d82013-08-01 10:50:15 -0700340 testResult = "\n\n"+"*" * 37+"\n" + "\tTest Execution Summary\n" + "\n"+"*" * 37+" \n"
341 testResult = testResult + "\n Test Start : " + str(main.STARTTIME.strftime("%d %b %Y %H:%M:%S"))
342 testResult = testResult + "\n Test End : " + str(main.ENDTIME.strftime("%d %b %Y %H:%M:%S"))
343 testResult = testResult + "\n Execution Time : " + str(main.EXECTIME)
344 testResult = testResult + "\n Total tests planned : " + str(main.TOTAL_TC_PLANNED)
345 testResult = testResult + "\n Total tests RUN : " + str(main.TOTAL_TC_RUN)
346 testResult = testResult + "\n Total Pass : " + str(main.TOTAL_TC_PASS)
347 testResult = testResult + "\n Total Fail : " + str(main.TOTAL_TC_FAIL)
348 testResult = testResult + "\n Total No Result : " + str(main.TOTAL_TC_NORESULT)
349 testResult = testResult + "\n Success Percentage : " + str(main.TOTAL_TC_SUCCESS) + "%"
350 testResult = testResult + "\n Execution Result : " + str(main.TOTAL_TC_EXECPERCENT) + "%"
Jon Hall81d3d392015-04-24 14:40:35 -0700351
adminbae64d82013-08-01 10:50:15 -0700352 #main.log.report(testResult)
353 main.testResult = testResult
354 main.log.exact(testResult)
Jon Hall94fd0472014-12-08 11:52:42 -0800355
Jon Hall368769f2014-11-19 15:43:35 -0800356 ##CSV output needed for Jenkin's plot plugin
357 #NOTE: the elements were orded based on the colors assigned to the data
358 logfile = open(main.JenkinsCSV ,"w")
359 logfile.write(",".join( ['Tests Failed', 'Tests Passed', 'Tests Planned'] ) + "\n")
Jon Hall94fd0472014-12-08 11:52:42 -0800360 logfile.write(",".join( [str(int(main.TOTAL_TC_FAIL)), str(int(main.TOTAL_TC_PASS)), str(int(main.TOTAL_TC_PLANNED))] ))
361 logfile.close()
362
adminbae64d82013-08-01 10:50:15 -0700363 def updateCaseResults(self,main):
364 '''
365 Update the case result based on the steps execution and asserting each step in the test-case
366 '''
367 case = str(main.CurrentTestCaseNumber)
Jon Hall79bec222015-04-30 16:23:30 -0700368 currentResult = main.testCaseResult.get(case, 2)
Jon Hall81d3d392015-04-24 14:40:35 -0700369
Jon Hall79bec222015-04-30 16:23:30 -0700370 if currentResult == 2:
adminbae64d82013-08-01 10:50:15 -0700371 main.TOTAL_TC_RUN = main.TOTAL_TC_RUN + 1
372 main.TOTAL_TC_NORESULT = main.TOTAL_TC_NORESULT + 1
373 main.log.exact("\n "+"*" * 29+"\n" + "\n Result: No Assertion Called \n"+"*" * 29+"\n")
Jon Hall79bec222015-04-30 16:23:30 -0700374 line = "Case "+case+": "+main.CurrentTestCase+" - No Result"
375 elif currentResult == 1:
adminbae64d82013-08-01 10:50:15 -0700376 main.TOTAL_TC_RUN = main.TOTAL_TC_RUN + 1
377 main.TOTAL_TC_PASS = main.TOTAL_TC_PASS + 1
378 main.log.exact("\n"+"*" * 29+"\n Result: Pass \n"+"*" * 29+"\n")
Jon Hall79bec222015-04-30 16:23:30 -0700379 line = "Case "+case+": "+main.CurrentTestCase+" - PASS"
380 elif currentResult == 0:
adminbae64d82013-08-01 10:50:15 -0700381 main.TOTAL_TC_RUN = main.TOTAL_TC_RUN + 1
382 main.TOTAL_TC_FAIL = main.TOTAL_TC_FAIL + 1
383 main.log.exact("\n"+"*" * 29+"\n Result: Failed \n"+"*" * 29+"\n")
Jon Hall79bec222015-04-30 16:23:30 -0700384 line = "Case "+case+": "+main.CurrentTestCase+" - FAIL"
385 else:
386 main.log.error( " Unknown result of case " + case +
387 ". Result was: " + currentResult )
388 line = "Case "+case+": "+main.CurrentTestCase+" - ERROR"
389 main.log.wiki( "<h3>" + line + "</h3>" )
390 main.log.summary( line )
Jon Hall81d3d392015-04-24 14:40:35 -0700391