blob: 961e82496de2b872b3644f755b9cccbeca4dcc06 [file] [log] [blame]
adminbae64d82013-08-01 10:50:15 -07001#!/usr/bin/env python
2'''
3Created on 22-Oct-2012
Jon Hall65844a32015-03-09 19:09:37 -07004
adminbae64d82013-08-01 10:50:15 -07005@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
6
7
8 TestON is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
12
13 TestON is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
Jon Hall65844a32015-03-09 19:09:37 -070019 along with TestON. If not, see <http://www.gnu.org/licenses/>.
adminbae64d82013-08-01 10:50:15 -070020
21
22
23teston is the main module.
24
25'''
26
27import sys
28import getpass
29import os
30import re
31import __builtin__
32import new
33import xmldict
Jon Hall30b82fa2015-03-04 17:15:43 -080034import importlib
adminbae64d82013-08-01 10:50:15 -070035module = new.module("test")
36import openspeak
37global path, drivers_path, core_path, tests_path,logs_path
38path = re.sub("(core|bin)$", "", os.getcwd())
39drivers_path = path+"drivers/"
40core_path = path+"core"
41tests_path = path+"tests"
42logs_path = path+"logs/"
43config_path = path + "config/"
44sys.path.append(path)
45sys.path.append( drivers_path)
46sys.path.append(core_path )
47sys.path.append(tests_path)
48
49from core.utilities import Utilities
kelvin-onlabfb521662015-02-27 09:52:40 -080050from core.Thread import Thread
adminbae64d82013-08-01 10:50:15 -070051
adminbae64d82013-08-01 10:50:15 -070052
53class TestON:
54 '''
55
56 TestON will initiate the specified test.
57 The main tasks are :
58 * Initiate the required Component handles for the test.
59 * Create Log file Handles.
60
61 '''
62 def __init__(self,options):
63 '''
64 Initialise the component handles specified in the topology file of the specified test.
65
66 '''
67 # Initialization of the variables.
68 __builtin__.main = self
Jon Halla1185982014-09-15 14:55:10 -070069
adminbae64d82013-08-01 10:50:15 -070070 __builtin__.path = path
71 __builtin__.utilities = Utilities()
72 self.TRUE = 1
73 self.FALSE = 0
74 self.ERROR = -1
75 self.FAIL = False
76 self.PASS = True
77 self.CASERESULT = self.TRUE
78 self.init_result = self.TRUE
79 self.testResult = "Summary"
80 self.stepName =""
Jon Halld61331b2015-02-17 16:35:47 -080081 self.EXPERIMENTAL_MODE = False
adminbae64d82013-08-01 10:50:15 -070082 self.test_target = None
83 self.lastcommand = None
Jon Halld61331b2015-02-17 16:35:47 -080084 self.testDir = tests_path
85 self.configFile = config_path + "teston.cfg"
adminbae64d82013-08-01 10:50:15 -070086 self.parsingClass = "xmlparser"
87 self.parserPath = core_path + "/xmlparser"
88 self.loggerPath = core_path + "/logger"
89 self.loggerClass = "Logger"
90 self.logs_path = logs_path
91 self.driver = ''
kelvin-onlabfb521662015-02-27 09:52:40 -080092 self.Thread = Thread
Jon Hall65844a32015-03-09 19:09:37 -070093
adminbae64d82013-08-01 10:50:15 -070094 self.configparser()
95 verifyOptions(options)
96 load_logger()
97 self.componentDictionary = {}
98 self.componentDictionary = self.topology ['COMPONENT']
99 self.driversList=[]
100 if type(self.componentDictionary) == str :
101 self.componentDictionary = dict(self.componentDictionary)
Jon Hall65844a32015-03-09 19:09:37 -0700102
adminbae64d82013-08-01 10:50:15 -0700103 for component in self.componentDictionary :
104 self.driversList.append(self.componentDictionary[component]['type'])
Jon Hall65844a32015-03-09 19:09:37 -0700105
adminbae64d82013-08-01 10:50:15 -0700106 self.driversList = list(set(self.driversList)) # Removing duplicates.
107 # Checking the test_target option set for the component or not
108 if type(self.componentDictionary) == dict:
109 for component in self.componentDictionary.keys():
110 if 'test_target' in self.componentDictionary[component].keys():
111 self.test_target = component
Jon Hall65844a32015-03-09 19:09:37 -0700112
Jon Halld61331b2015-02-17 16:35:47 -0800113 # Checking for the openspeak file and test script
adminbae64d82013-08-01 10:50:15 -0700114 self.logger.initlog(self)
115
116 # Creating Drivers Handles
117 initString = "\n"+"*" * 30+"\n CASE INIT \n"+"*" * 30+"\n"
118 self.log.exact(initString)
119 self.driverObject = {}
120 self.random_order = 111 # Random order id to connect the components
121 components_connect_order = {}
122 #component_list.append()
123 if type(self.componentDictionary) == dict:
124 for component in self.componentDictionary.keys():
125 self.componentDictionary[component]['connect_order'] = self.componentDictionary[component]['connect_order'] if ('connect_order' in self.componentDictionary[component].keys()) else str(self.get_random())
126 components_connect_order[component] = eval(self.componentDictionary[component]['connect_order'])
127 #Ordering components based on the connect order.
128 ordered_component_list =sorted(components_connect_order, key=lambda key: components_connect_order[key])
129 print ordered_component_list
130
131 for component in ordered_component_list:
132 self.componentInit(component)
133
134 def configparser(self):
135 '''
136 It will parse the config file (teston.cfg) and return as dictionary
137 '''
138 matchFileName = re.match(r'(.*)\.cfg', self.configFile, re.M | re.I)
139 if matchFileName:
140 xml = open(self.configFile).read()
141 try :
142 self.configDict = xmldict.xml_to_dict(xml)
143 return self.configDict
Jon Hallfebb1c72015-03-05 13:30:09 -0800144 except Exception:
adminbae64d82013-08-01 10:50:15 -0700145 print "There is no such file to parse " + self.configFile
146
147 def componentInit(self,component):
148 '''
149 This method will initialize specified component
150 '''
151 global driver_options
152 self.log.info("Creating component Handle: "+component)
Jon Halld61331b2015-02-17 16:35:47 -0800153 driver_options = {}
adminbae64d82013-08-01 10:50:15 -0700154 if 'COMPONENTS' in self.componentDictionary[component].keys():
155 driver_options =dict(self.componentDictionary[component]['COMPONENTS'])
156
157 driver_options['name']=component
158 driverName = self.componentDictionary[component]['type']
159 driver_options ['type'] = driverName
160
161 classPath = self.getDriverPath(driverName.lower())
Jon Hall30b82fa2015-03-04 17:15:43 -0800162 driverModule = importlib.import_module(classPath)
adminbae64d82013-08-01 10:50:15 -0700163 driverClass = getattr(driverModule, driverName)
164 driverObject = driverClass()
165
166 connect_result = driverObject.connect(user_name = self.componentDictionary[component]['user'] if ('user' in self.componentDictionary[component].keys()) else getpass.getuser(),
167 ip_address= self.componentDictionary[component]['host'] if ('host' in self.componentDictionary[component].keys()) else 'localhost',
168 pwd = self.componentDictionary[component]['password'] if ('password' in self.componentDictionary[component].keys()) else 'changeme',
169 port = self.componentDictionary[component]['port'] if ('port' in self.componentDictionary[component].keys()) else None,
170 options = driver_options)
171 if not connect_result:
172 self.log.error("Exiting form the test execution because the connecting to the "+component+" component failed.")
Jon Halld61331b2015-02-17 16:35:47 -0800173 self.exit()
adminbae64d82013-08-01 10:50:15 -0700174
175 vars(self)[component] = driverObject
176
177 def run(self):
178 '''
179 The Execution of the test script's cases listed in the Test params file will be done here.
180 And Update each test case result.
181 This method will return TRUE if it executed all the test cases successfully,
182 else will retun FALSE
183 '''
184
185 self.testCaseResult = {}
Jon Halla1185982014-09-15 14:55:10 -0700186 self.TOTAL_TC = 0
adminbae64d82013-08-01 10:50:15 -0700187 self.TOTAL_TC_RUN = 0
Jon Halld61331b2015-02-17 16:35:47 -0800188 self.TOTAL_TC_PLANNED = 0
adminbae64d82013-08-01 10:50:15 -0700189 self.TOTAL_TC_NORESULT = 0
190 self.TOTAL_TC_FAIL = 0
191 self.TOTAL_TC_PASS = 0
Jon Halla1185982014-09-15 14:55:10 -0700192 self.TEST_ITERATION = 0
adminbae64d82013-08-01 10:50:15 -0700193 self.stepCount = 0
194 self.CASERESULT = self.TRUE
195
Jon Halld61331b2015-02-17 16:35:47 -0800196 import testparser
adminbae64d82013-08-01 10:50:15 -0700197 testFile = self.tests_path + "/"+self.TEST + "/"+self.TEST + ".py"
198 test = testparser.TestParser(testFile)
199 self.testscript = test.testscript
200 self.code = test.getStepCode()
Jon Hallfebb1c72015-03-05 13:30:09 -0800201 repeat= int(self.params['repeat']) if ('repeat' in self.params) else 1
202 self.TOTAL_TC_PLANNED = len(self.testcases_list)*repeat
adminbae64d82013-08-01 10:50:15 -0700203
204 result = self.TRUE
Jon Hallfebb1c72015-03-05 13:30:09 -0800205 while(repeat):
Jon Halla1185982014-09-15 14:55:10 -0700206 for self.CurrentTestCaseNumber in self.testcases_list:
Jon Halld61331b2015-02-17 16:35:47 -0800207 result = self.runCase(self.CurrentTestCaseNumber)
Jon Hallfebb1c72015-03-05 13:30:09 -0800208 repeat-=1
adminbae64d82013-08-01 10:50:15 -0700209 return result
210
211 def runCase(self,testCaseNumber):
212 self.CurrentTestCaseNumber = testCaseNumber
213 result = self.TRUE
214 self.stepCount = 0
215 self.EXPERIMENTAL_MODE = self.FALSE
216 self.addCaseHeader()
217 self.testCaseNumber = str(testCaseNumber)
218 stopped = False
219 try :
220 self.stepList = self.code[self.testCaseNumber].keys()
Jon Halld61331b2015-02-17 16:35:47 -0800221 except KeyError:
Jon Hallfebb1c72015-03-05 13:30:09 -0800222 self.log.error("There is no Test-Case "+ self.testCaseNumber)
223 return self.FALSE
adminbae64d82013-08-01 10:50:15 -0700224
225 self.stepCount = 0
226 while self.stepCount < len(self.code[self.testCaseNumber].keys()):
227 result = self.runStep(self.stepList,self.code,self.testCaseNumber)
Jon Hallfebb1c72015-03-05 13:30:09 -0800228 if result == self.FALSE:
adminbae64d82013-08-01 10:50:15 -0700229 break
Jon Hallfebb1c72015-03-05 13:30:09 -0800230 elif result == self.TRUE:
adminbae64d82013-08-01 10:50:15 -0700231 continue
232
233 if not stopped :
234 self.testCaseResult[str(self.CurrentTestCaseNumber)] = self.CASERESULT
235 self.logger.updateCaseResults(self)
236 return result
237
238 def runStep(self,stepList,code,testCaseNumber):
239 if not cli.pause:
240 try :
241 step = stepList[self.stepCount]
242 exec code[testCaseNumber][step] in module.__dict__
243 self.stepCount = self.stepCount + 1
244 except TypeError,e:
Jon Hall63604932015-02-26 17:09:50 -0800245 print "Exception in the following section of code: Test Step " +\
246 str(testCaseNumber) + "." + str(step) + " ):"
247 #print code[testCaseNumber][step]
adminbae64d82013-08-01 10:50:15 -0700248 self.stepCount = self.stepCount + 1
Jon Hall30b82fa2015-03-04 17:15:43 -0800249 self.log.exception(e)
shahshreya957feaa2015-03-23 16:08:29 -0700250 self.cleanup()
Jon Hall00539b12015-04-03 13:55:46 -0700251 self.exit()
adminbae64d82013-08-01 10:50:15 -0700252 return main.TRUE
253
254 if cli.stop:
255 cli.stop = False
256 stopped = True
257 self.TOTAL_TC_NORESULT = self.TOTAL_TC_NORESULT + 1
258 self.testCaseResult[str(self.CurrentTestCaseNumber)] = "Stopped"
259 self.logger.updateCaseResults(self)
260 result = self.cleanup()
261 return main.FALSE
262
263 def addCaseHeader(self):
264 caseHeader = "\n"+"*" * 30+"\n Result summary for Testcase"+str(self.CurrentTestCaseNumber)+"\n"+"*" * 30+"\n"
Jon Halld61331b2015-02-17 16:35:47 -0800265 self.log.exact(caseHeader)
266 caseHeader = "\n"+"*" * 40 +"\nStart of Test Case"+str(self.CurrentTestCaseNumber)+" : "
adminbae64d82013-08-01 10:50:15 -0700267 for driver in self.componentDictionary.keys():
268 vars(self)[driver+'log'].info(caseHeader)
269
270 def addCaseFooter(self):
271 if self.stepCount-1 > 0 :
272 previousStep = " "+str(self.CurrentTestCaseNumber)+"."+str(self.stepCount-1)+": "+ str(self.stepName) + ""
273 stepHeader = "\n"+"*" * 40+"\nEnd of Step "+previousStep+"\n"+"*" * 40+"\n"
274
275 caseFooter = "\n"+"*" * 40+"\nEnd of Test case "+str(self.CurrentTestCaseNumber)+"\n"+"*" * 40+"\n"
276
277 for driver in self.driversList:
278 vars(self)[driver].write(stepHeader+"\n"+caseFooter)
279
280 def cleanup(self):
281 '''
282 Release all the component handles and the close opened file handles.
283 This will return TRUE if all the component handles and log handles closed properly,
284 else return FALSE
285
286 '''
287 result = self.TRUE
288 self.logger.testSummary(self)
Jon Halld61331b2015-02-17 16:35:47 -0800289
adminbae64d82013-08-01 10:50:15 -0700290 #self.reportFile.close()
Jon Halld61331b2015-02-17 16:35:47 -0800291
adminbae64d82013-08-01 10:50:15 -0700292
admin2c7034f2013-08-02 15:09:17 -0700293 #utilities.send_mail()
Jon Hall00539b12015-04-03 13:55:46 -0700294 for component in self.componentDictionary.keys():
295 try :
Jon Halld61331b2015-02-17 16:35:47 -0800296 tempObject = vars(self)[component]
Jon Hall1a77a1e2015-04-06 10:41:13 -0700297 print "Disconnecting from " + str(tempObject.name) + ": " + \
298 str(tempObject)
adminbae64d82013-08-01 10:50:15 -0700299 tempObject.disconnect()
Jon Halld61331b2015-02-17 16:35:47 -0800300 #tempObject.execute(cmd="exit",prompt="(.*)",timeout=120)
adminbae64d82013-08-01 10:50:15 -0700301
Jon Hall00539b12015-04-03 13:55:46 -0700302 except (Exception):
303 self.log.exception( "Exception while disconnecting from " +
304 str( component ) )
305 result = self.FALSE
adminbae64d82013-08-01 10:50:15 -0700306 # Closing all the driver's session files
307 for driver in self.componentDictionary.keys():
308 vars(self)[driver].close_log_handles()
Jon Halld61331b2015-02-17 16:35:47 -0800309
adminbae64d82013-08-01 10:50:15 -0700310 return result
Jon Halld61331b2015-02-17 16:35:47 -0800311
adminbae64d82013-08-01 10:50:15 -0700312 def pause(self):
313 '''
314 This function will pause the test's execution, and will continue after user provide 'resume' command.
315 '''
316 __builtin__.testthread.pause()
317
318 def onfail(self,*components):
319 '''
320 When test step failed, calling all the components onfail.
321 '''
322
323 if not components:
324 try :
325 for component in self.componentDictionary.keys():
326 tempObject = vars(self)[component]
327 result = tempObject.onfail()
328 except(Exception),e:
329 print str(e)
330 result = self.FALSE
331
332 else:
333 try :
334 for component in components:
335 tempObject = vars(self)[component]
336 result = tempObject.onfail()
337 except(Exception),e:
338 print str(e)
339 result = self.FALSE
340
341
342 def getDriverPath(self,driverName):
343 '''
344 Based on the component 'type' specified in the params , this method will find the absolute path ,
345 by recursively searching the name of the component.
346 '''
347 import commands
348
349 cmd = "find "+drivers_path+" -name "+driverName+".py"
350 result = commands.getoutput(cmd)
351
352 result_array = str(result).split('\n')
353 result_count = 0
354
355 for drivers_list in result_array:
356 result_count = result_count+1
357 if result_count > 1 :
358 print "found "+driverName+" "+ str(result_count) + " times"+str(result_array)
359 self.exit()
360
361 result = re.sub("(.*)drivers","",result)
362 result = re.sub("\.py","",result)
363 result = re.sub("\.pyc","",result)
364 result = re.sub("\/",".",result)
365 result = "drivers"+result
366 return result
367
368
369 def step(self,stepDesc):
370 '''
371 The step information of the test-case will append to the logs.
372 '''
373 previousStep = " "+str(self.CurrentTestCaseNumber)+"."+str(self.stepCount-1)+": "+ str(self.stepName) + ""
374 self.stepName = stepDesc
375
376 stepName = " "+str(self.CurrentTestCaseNumber)+"."+str(self.stepCount)+": "+ str(stepDesc) + ""
377 try :
378 if self.stepCount == 0:
379 stepName = " INIT : Initializing the test case :"+self.CurrentTestCase
380 except AttributeError:
381 stepName = " INIT : Initializing the test case :"+str(self.CurrentTestCaseNumber)
382
383 self.log.step(stepName)
384 stepHeader = ""
385 if self.stepCount > 1 :
386 stepHeader = "\n"+"-"*45+"\nEnd of Step "+previousStep+"\n"+"-"*45+"\n"
387
Jon Halld61331b2015-02-17 16:35:47 -0800388 stepHeader += "\n"+"-"*45+"\nStart of Step"+stepName+"\n"+"-"*45+"\n"
adminbae64d82013-08-01 10:50:15 -0700389 for driver in self.componentDictionary.keys():
390 vars(self)[driver+'log'].info(stepHeader)
391
392 def case(self,testCaseName):
393 '''
394 Test's each test-case information will append to the logs.
395 '''
Jon Halld61331b2015-02-17 16:35:47 -0800396 self.CurrentTestCase = testCaseName
adminbae64d82013-08-01 10:50:15 -0700397 testCaseName = " " + str(testCaseName) + ""
398 self.log.case(testCaseName)
Jon Halld61331b2015-02-17 16:35:47 -0800399 caseHeader = testCaseName+"\n"+"*" * 40+"\n"
adminbae64d82013-08-01 10:50:15 -0700400 for driver in self.componentDictionary.keys():
401 vars(self)[driver+'log'].info(caseHeader)
402
403 def testDesc(self,description):
404 '''
405 Test description will append to the logs.
406 '''
407 description = "Test Description : " + str (description) + ""
408 self.log.info(description)
409
410 def _getTest(self):
411 '''
412 This method will parse the test script to find required test information.
413 '''
414 testFile = self.tests_path + "/"+self.TEST + "/"+self.TEST + ".py"
415 testFileHandler = open(testFile, 'r')
416 testFileList = testFileHandler.readlines()
417 testFileHandler.close()
418 #self.TOTAL_TC_PLANNED = 0
419 counter = 0
420 for index in range(len(testFileList)):
421 lineMatch = re.match('\s+def CASE(\d+)(.*):',testFileList[index],0)
422 if lineMatch:
423 counter = counter + 1
Jon Halla1185982014-09-15 14:55:10 -0700424 self.TC_PLANNED = len(self.testcases_list)
425
adminbae64d82013-08-01 10:50:15 -0700426
427 def response_parser(self,response, return_format):
428 ''' It will load the default response parser '''
429 response_dict = {}
430 response_dict = self.response_to_dict(response, return_format)
Jon Halld61331b2015-02-17 16:35:47 -0800431 return_format_string = self.dict_to_return_format(response,return_format,response_dict)
adminbae64d82013-08-01 10:50:15 -0700432 return return_format_string
433
434 def response_to_dict(self,response,return_format):
435
436 response_dict = {}
437 json_match = re.search('^\s*{', response)
438 xml_match = re.search('^\s*\<', response)
439 ini_match = re.search('^\s*\[', response)
440 if json_match :
Jon Hallfebb1c72015-03-05 13:30:09 -0800441 self.log.info(" Response is in 'JSON' format and Converting to '"+return_format+"' format")
Jon Halld61331b2015-02-17 16:35:47 -0800442 # Formatting the json string
adminbae64d82013-08-01 10:50:15 -0700443
444 response = re.sub(r"{\s*'?(\w)", r'{"\1', response)
445 response = re.sub(r",\s*'?(\w)", r',"\1', response)
446 response = re.sub(r"(\w)'?\s*:", r'\1":', response)
447 response = re.sub(r":\s*'(\w)'\s*([,}])", r':"\1"\2', response)
448
449 try :
450 import json
451 response_dict = json.loads(response)
Jon Hall30b82fa2015-03-04 17:15:43 -0800452 except Exception, e:
Jon Hallfebb1c72015-03-05 13:30:09 -0800453 self.log.exception( e )
454 self.log.error("Json Parser is unable to parse the string")
adminbae64d82013-08-01 10:50:15 -0700455 return response_dict
456
457 elif ini_match :
Jon Hallfebb1c72015-03-05 13:30:09 -0800458 self.log.info(" Response is in 'INI' format and Converting to '"+return_format+"' format")
adminbae64d82013-08-01 10:50:15 -0700459 from configobj import ConfigObj
460 response_file = open("respnse_file.temp",'w')
461 response_file.write(response)
Jon Halld61331b2015-02-17 16:35:47 -0800462 response_file.close()
adminbae64d82013-08-01 10:50:15 -0700463 response_dict = ConfigObj("respnse_file.temp")
464 return response_dict
465
466 elif xml_match :
Jon Hallfebb1c72015-03-05 13:30:09 -0800467 self.log.info(" Response is in 'XML' format and Converting to '"+return_format+"' format")
adminbae64d82013-08-01 10:50:15 -0700468 try :
adminbae64d82013-08-01 10:50:15 -0700469 response_dict = xmldict.xml_to_dict("<response> "+str(response)+" </response>")
470 except Exception, e:
Jon Hallfebb1c72015-03-05 13:30:09 -0800471 self.log.exception( e )
adminbae64d82013-08-01 10:50:15 -0700472 return response_dict
473
474 def dict_to_return_format(self,response,return_format,response_dict):
475
476 if return_format =='table' :
477 ''' Will return in table format'''
478 to_do = "Call the table output formatter"
479 global response_table
480 response_table = '\n'
481 response_table = response_table +'\t'.join(response_dict)+"\n"
482
483 def get_table(value_to_convert):
484 ''' This will parse the dictionary recusrsively and print as table format'''
485 table_data = ""
486 if type(value_to_convert) == dict :
487 table_data = table_data +'\t'.join(value_to_convert)+"\n"
488 for temp_val in value_to_convert.values() :
489 table_data = table_data + get_table(temp_val)
490 else :
491 table_data = table_data + str(value_to_convert) +"\t"
Jon Halld61331b2015-02-17 16:35:47 -0800492 return table_data
adminbae64d82013-08-01 10:50:15 -0700493
494 for value in response_dict.values() :
495 response_table = response_table + get_table(value)
496
497
498
Jon Hall88e498c2015-03-06 09:54:35 -0800499 # response_table = response_table + '\t'.join(response_dict.values())
adminbae64d82013-08-01 10:50:15 -0700500
501 return response_table
502
503 elif return_format =='config':
504 ''' Will return in config format'''
505 to_do = 'Call dict to config coverter'
506 response_string = str(response_dict)
507 print response_string
508 response_config = re.sub(",", "\n\t", response_string)
509 response_config = re.sub("u\'", "\'", response_config)
510 response_config = re.sub("{", "", response_config)
511 response_config = re.sub("}", "\n", response_config)
512 response_config = re.sub(":", " =", response_config)
513 return "[response]\n\t "+response_config
514
515 elif return_format == 'xml':
516 ''' Will return in xml format'''
adminbae64d82013-08-01 10:50:15 -0700517 response_xml = xmldict.dict_to_xml(response_dict)
518 response_xml = re.sub(">\s*<", ">\n<", response_xml)
519 return "\n"+response_xml
520
521 elif return_format == 'json':
522 ''' Will return in json format'''
523 to_do = 'Call dict to xml coverter'
524 import json
525 response_json = json.dumps(response_dict)
526 return response_json
527
528 def get_random(self):
529 self.random_order = self.random_order + 1
530 return self.random_order
531
532 def exit(self):
533 __builtin__.testthread = None
534 sys.exit()
535
536def verifyOptions(options):
537 '''
538 This will verify the command line options and set to default values, if any option not given in command line.
539 '''
540 import pprint
541 pp = pprint.PrettyPrinter(indent=4)
542
Jon Hall88e498c2015-03-06 09:54:35 -0800543 # pp.pprint(options)
adminbae64d82013-08-01 10:50:15 -0700544 verifyTest(options)
545 verifyExample(options)
546 verifyTestScript(options)
547 verifyParams()
548 verifyLogdir(options)
549 verifyMail(options)
550 verifyTestCases(options)
551
552def verifyTest(options):
553 if options.testname:
554 main.TEST = options.testname
555 main.classPath = "tests."+main.TEST+"."+main.TEST
556 main.tests_path = tests_path
557 elif options.example :
558 main.TEST = options.example
559 main.tests_path = path+"/examples/"
560 main.classPath = "examples."+main.TEST+"."+main.TEST
561 else :
562 print "Test or Example not specified please specify the --test <test name > or --example <example name>"
563 self.exit()
564
565def verifyExample(options):
566 if options.example:
567 main.testDir = path+'/examples/'
568 main.tests_path = path+"/examples/"
569 main.classPath = "examples."+main.TEST+"."+main.TEST
570
571def verifyLogdir(options):
Jon Hall88e498c2015-03-06 09:54:35 -0800572 # Verifying Log directory option
adminbae64d82013-08-01 10:50:15 -0700573 if options.logdir:
574 main.logdir = options.logdir
575 else :
Jon Halld61331b2015-02-17 16:35:47 -0800576 main.logdir = main.FALSE
adminbae64d82013-08-01 10:50:15 -0700577
578def verifyMail(options):
Jon Halld61331b2015-02-17 16:35:47 -0800579 # Checking the mailing list
adminbae64d82013-08-01 10:50:15 -0700580 if options.mail:
581 main.mail = options.mail
582 elif main.params.has_key('mail'):
583 main.mail = main.params['mail']
584 else :
585 main.mail = 'paxweb@paxterrasolutions.com'
586
587def verifyTestCases(options):
Jon Hall88e498c2015-03-06 09:54:35 -0800588 # Getting Test cases list
adminbae64d82013-08-01 10:50:15 -0700589 if options.testcases:
Jon Hallfebb1c72015-03-05 13:30:09 -0800590 testcases_list = options.testcases
Jon Hall88e498c2015-03-06 09:54:35 -0800591 # sys.exit()
adminbae64d82013-08-01 10:50:15 -0700592 testcases_list = re.sub("(\[|\])", "", options.testcases)
593 main.testcases_list = eval(testcases_list+",")
594 else :
595 if 'testcases' in main.params.keys():
Jon Halla1185982014-09-15 14:55:10 -0700596 temp = eval(main.params['testcases']+",")
597 list1=[]
598 if type(temp[0])==list:
Jon Hallfebb1c72015-03-05 13:30:09 -0800599 for test in temp:
600 for testcase in test:
601 if type(testcase)==int:
602 testcase=[testcase]
603 list1.extend(testcase)
604 else :
605 temp=list(temp)
606 for testcase in temp:
607 if type(testcase)==int:
608 testcase=[testcase]
609 list1.extend(testcase)
610 main.testcases_list=list1
adminbae64d82013-08-01 10:50:15 -0700611 else :
612 print "testcases not specifed in params, please provide in params file or 'testcases' commandline argument"
Jon Halld61331b2015-02-17 16:35:47 -0800613 sys.exit()
adminbae64d82013-08-01 10:50:15 -0700614
615def verifyTestScript(options):
616 '''
617 Verifyies test script.
618 '''
Jon Halld61331b2015-02-17 16:35:47 -0800619 main.openspeak = openspeak.OpenSpeak()
adminbae64d82013-08-01 10:50:15 -0700620 openspeakfile = main.testDir+"/" + main.TEST + "/" + main.TEST + ".ospk"
621 testfile = main.testDir+"/" + main.TEST + "/" + main.TEST + ".py"
622 if os.path.exists(openspeakfile) :
623 main.openspeak.compiler(openspeakfile=openspeakfile,writetofile=1)
624 elif os.path.exists(testfile):
625 print ''
626 else:
627 print "\nThere is no :\""+main.TEST+"\" test, Please Provide OpenSpeak Script/ test script"
628 __builtin__.testthread = None
629 main.exit()
630
631 try :
adminbae64d82013-08-01 10:50:15 -0700632 testModule = __import__(main.classPath, globals(), locals(), [main.TEST], -1)
633 except(ImportError):
Jon Hallf8ecf732014-12-02 21:14:16 -0500634 print "There was an import error, it might mean that there is no test like "+main.TEST
Jon Halld61331b2015-02-17 16:35:47 -0800635 main.exit()
adminbae64d82013-08-01 10:50:15 -0700636
637 testClass = getattr(testModule, main.TEST)
638 main.testObject = testClass()
639 load_parser()
Jon Halld61331b2015-02-17 16:35:47 -0800640 main.params = main.parser.parseParams(main.classPath)
641 main.topology = main.parser.parseTopology(main.classPath)
adminbae64d82013-08-01 10:50:15 -0700642
643def verifyParams():
644 try :
645 main.params = main.params['PARAMS']
646 except(KeyError):
647 print "Error with the params file: Either the file not specified or the format is not correct"
Jon Halld61331b2015-02-17 16:35:47 -0800648 main.exit()
adminbae64d82013-08-01 10:50:15 -0700649
650 try :
651 main.topology = main.topology['TOPOLOGY']
652 except(KeyError):
653 print "Error with the Topology file: Either the file not specified or the format is not correct"
654 main.exit()
655
656def load_parser() :
657 '''
658 It facilitates the loading customised parser for topology and params file.
659 It loads parser mentioned in tab named parser of teston.cfg file.
660 It also loads default xmlparser if no parser have specified in teston.cfg file.
661
662 '''
663 confighash = main.configDict
664 if 'file' in confighash['config']['parser'] and 'class' in confighash['config']['parser']:
665 if confighash['config']['parser']['file'] != None or confighash['config']['parser']['class']!= None :
666 if os.path.exists(confighash['config']['parser']['file']) :
667 module = re.sub(r".py\s*$","",confighash['config']['parser']['file'])
668 moduleList = module.split("/")
669 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
670 try :
671 parsingClass = confighash['config']['parser']['class']
672 parsingModule = __import__(newModule, globals(), locals(), [parsingClass], -1)
673 parsingClass = getattr(parsingModule, parsingClass)
674 main.parser = parsingClass()
675 #hashobj = main.parser.parseParams(main.classPath)
676 if hasattr(main.parser,"parseParams") and hasattr(main.parser,"parseTopology") and hasattr(main.parser,"parse") :
677
678 pass
679 else:
680 main.exit()
681
682 except ImportError:
683 print sys.exc_info()[1]
684 main.exit()
685 else :
686 print "No Such File Exists !!"+ confighash['config']['parser']['file'] +"using default parser"
Jon Halld61331b2015-02-17 16:35:47 -0800687 load_defaultParser()
688 elif confighash['config']['parser']['file'] == None or confighash['config']['parser']['class'] == None :
689 load_defaultParser()
adminbae64d82013-08-01 10:50:15 -0700690 else:
691 load_defaultParser()
692
693def load_defaultParser():
694 '''
695 It will load the default parser which is xml parser to parse the params and topology file.
696 '''
697 moduleList = main.parserPath.split("/")
698 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
699 try :
Jon Halld61331b2015-02-17 16:35:47 -0800700 parsingClass = main.parsingClass
adminbae64d82013-08-01 10:50:15 -0700701 parsingModule = __import__(newModule, globals(), locals(), [parsingClass], -1)
702 parsingClass = getattr(parsingModule, parsingClass)
703 main.parser = parsingClass()
704 if hasattr(main.parser,"parseParams") and hasattr(main.parser,"parseTopology") and hasattr(main.parser,"parse") :
705 pass
706 else:
707 main.exit()
708
709 except ImportError:
710 print sys.exc_info()[1]
711
712
713def load_logger() :
714 '''
715 It facilitates the loading customised parser for topology and params file.
716 It loads parser mentioned in tab named parser of teston.cfg file.
717 It also loads default xmlparser if no parser have specified in teston.cfg file.
718
719 '''
720 confighash = main.configDict
721 if 'file' in confighash['config']['logger'] and 'class' in confighash['config']['logger']:
722 if confighash['config']['logger']['file'] != None or confighash['config']['logger']['class']!= None :
723 if os.path.exists(confighash['config']['logger']['file']) :
724 module = re.sub(r".py\s*$","",confighash['config']['logger']['file'])
725 moduleList = module.split("/")
726 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
727 try :
728 loggerClass = confighash['config']['logger']['class']
729 loggerModule = __import__(newModule, globals(), locals(), [loggerClass], -1)
730 loggerClass = getattr(loggerModule, loggerClass)
731 main.logger = loggerClass()
732 #hashobj = main.parser.parseParams(main.classPath)
733
734 except ImportError:
735 print sys.exc_info()[1]
736 else :
737 print "No Such File Exists !!"+confighash['config']['logger']['file']+ "Using default logger"
738 load_defaultlogger()
Jon Halld61331b2015-02-17 16:35:47 -0800739 elif confighash['config']['parser']['file'] == None or confighash['config']['parser']['class'] == None :
740 load_defaultlogger()
adminbae64d82013-08-01 10:50:15 -0700741 else:
742 load_defaultlogger()
743
744def load_defaultlogger():
745 '''
746 It will load the default parser which is xml parser to parse the params and topology file.
747 '''
748 moduleList = main.loggerPath.split("/")
749 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
750 try :
Jon Halld61331b2015-02-17 16:35:47 -0800751 loggerClass = main.loggerClass
adminbae64d82013-08-01 10:50:15 -0700752 loggerModule = __import__(newModule, globals(), locals(), [loggerClass], -1)
753 loggerClass = getattr(loggerModule, loggerClass)
754 main.logger = loggerClass()
755
756 except ImportError:
757 print sys.exc_info()[1]
Jon Halld61331b2015-02-17 16:35:47 -0800758 main.exit()
adminbae64d82013-08-01 10:50:15 -0700759
760def load_defaultlogger():
761 '''
762 It will load the default parser which is xml parser to parse the params and topology file.
763 '''
764 moduleList = main.loggerPath.split("/")
765 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
766 try :
Jon Halld61331b2015-02-17 16:35:47 -0800767 loggerClass = main.loggerClass
adminbae64d82013-08-01 10:50:15 -0700768 loggerModule = __import__(newModule, globals(), locals(), [loggerClass], -1)
769 loggerClass = getattr(loggerModule, loggerClass)
770 main.logger = loggerClass()
771
772 except ImportError:
773 print sys.exc_info()[1]
774 main.exit()
775
776
777
778
779def _echo(self):
780 print "THIS IS ECHO"