blob: 3f076913d2d94e220def1925c2a83b36b05dccd6 [file] [log] [blame]
adminbae64d82013-08-01 10:50:15 -07001#!/usr/bin/env python
2'''
3Created on 22-Oct-2012
4
5@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
19 along with TestON. If not, see <http://www.gnu.org/licenses/>.
20
21
22
23teston is the main module.
24
25'''
26
27import sys
28import getpass
29import os
30import re
31import __builtin__
32import new
33import xmldict
34module = new.module("test")
35import openspeak
36global path, drivers_path, core_path, tests_path,logs_path
37path = re.sub("(core|bin)$", "", os.getcwd())
38drivers_path = path+"drivers/"
39core_path = path+"core"
40tests_path = path+"tests"
41logs_path = path+"logs/"
42config_path = path + "config/"
43sys.path.append(path)
44sys.path.append( drivers_path)
45sys.path.append(core_path )
46sys.path.append(tests_path)
47
48from core.utilities import Utilities
49
adminbae64d82013-08-01 10:50:15 -070050
51class TestON:
52 '''
53
54 TestON will initiate the specified test.
55 The main tasks are :
56 * Initiate the required Component handles for the test.
57 * Create Log file Handles.
58
59 '''
60 def __init__(self,options):
61 '''
62 Initialise the component handles specified in the topology file of the specified test.
63
64 '''
65 # Initialization of the variables.
66 __builtin__.main = self
Jon Halla1185982014-09-15 14:55:10 -070067
adminbae64d82013-08-01 10:50:15 -070068 __builtin__.path = path
69 __builtin__.utilities = Utilities()
70 self.TRUE = 1
71 self.FALSE = 0
72 self.ERROR = -1
73 self.FAIL = False
74 self.PASS = True
75 self.CASERESULT = self.TRUE
76 self.init_result = self.TRUE
77 self.testResult = "Summary"
78 self.stepName =""
Jon Halld61331b2015-02-17 16:35:47 -080079 self.EXPERIMENTAL_MODE = False
adminbae64d82013-08-01 10:50:15 -070080 self.test_target = None
81 self.lastcommand = None
Jon Halld61331b2015-02-17 16:35:47 -080082 self.testDir = tests_path
83 self.configFile = config_path + "teston.cfg"
adminbae64d82013-08-01 10:50:15 -070084 self.parsingClass = "xmlparser"
85 self.parserPath = core_path + "/xmlparser"
86 self.loggerPath = core_path + "/logger"
87 self.loggerClass = "Logger"
88 self.logs_path = logs_path
89 self.driver = ''
Jon Halla1185982014-09-15 14:55:10 -070090
adminbae64d82013-08-01 10:50:15 -070091
92 self.configparser()
93 verifyOptions(options)
94 load_logger()
95 self.componentDictionary = {}
96 self.componentDictionary = self.topology ['COMPONENT']
97 self.driversList=[]
98 if type(self.componentDictionary) == str :
99 self.componentDictionary = dict(self.componentDictionary)
100
101 for component in self.componentDictionary :
102 self.driversList.append(self.componentDictionary[component]['type'])
103
104 self.driversList = list(set(self.driversList)) # Removing duplicates.
105 # Checking the test_target option set for the component or not
106 if type(self.componentDictionary) == dict:
107 for component in self.componentDictionary.keys():
108 if 'test_target' in self.componentDictionary[component].keys():
109 self.test_target = component
110
Jon Halld61331b2015-02-17 16:35:47 -0800111 # Checking for the openspeak file and test script
adminbae64d82013-08-01 10:50:15 -0700112 self.logger.initlog(self)
113
114 # Creating Drivers Handles
115 initString = "\n"+"*" * 30+"\n CASE INIT \n"+"*" * 30+"\n"
116 self.log.exact(initString)
117 self.driverObject = {}
118 self.random_order = 111 # Random order id to connect the components
119 components_connect_order = {}
120 #component_list.append()
121 if type(self.componentDictionary) == dict:
122 for component in self.componentDictionary.keys():
123 self.componentDictionary[component]['connect_order'] = self.componentDictionary[component]['connect_order'] if ('connect_order' in self.componentDictionary[component].keys()) else str(self.get_random())
124 components_connect_order[component] = eval(self.componentDictionary[component]['connect_order'])
125 #Ordering components based on the connect order.
126 ordered_component_list =sorted(components_connect_order, key=lambda key: components_connect_order[key])
127 print ordered_component_list
128
129 for component in ordered_component_list:
130 self.componentInit(component)
131
132 def configparser(self):
133 '''
134 It will parse the config file (teston.cfg) and return as dictionary
135 '''
136 matchFileName = re.match(r'(.*)\.cfg', self.configFile, re.M | re.I)
137 if matchFileName:
138 xml = open(self.configFile).read()
139 try :
140 self.configDict = xmldict.xml_to_dict(xml)
141 return self.configDict
142 except :
143 print "There is no such file to parse " + self.configFile
144
145 def componentInit(self,component):
146 '''
147 This method will initialize specified component
148 '''
149 global driver_options
150 self.log.info("Creating component Handle: "+component)
Jon Halld61331b2015-02-17 16:35:47 -0800151 driver_options = {}
adminbae64d82013-08-01 10:50:15 -0700152 if 'COMPONENTS' in self.componentDictionary[component].keys():
153 driver_options =dict(self.componentDictionary[component]['COMPONENTS'])
154
155 driver_options['name']=component
156 driverName = self.componentDictionary[component]['type']
157 driver_options ['type'] = driverName
158
159 classPath = self.getDriverPath(driverName.lower())
160 driverModule = __import__(classPath, globals(), locals(), [driverName.lower()], -1)
161 driverClass = getattr(driverModule, driverName)
162 driverObject = driverClass()
163
164 connect_result = driverObject.connect(user_name = self.componentDictionary[component]['user'] if ('user' in self.componentDictionary[component].keys()) else getpass.getuser(),
165 ip_address= self.componentDictionary[component]['host'] if ('host' in self.componentDictionary[component].keys()) else 'localhost',
166 pwd = self.componentDictionary[component]['password'] if ('password' in self.componentDictionary[component].keys()) else 'changeme',
167 port = self.componentDictionary[component]['port'] if ('port' in self.componentDictionary[component].keys()) else None,
168 options = driver_options)
169 if not connect_result:
170 self.log.error("Exiting form the test execution because the connecting to the "+component+" component failed.")
Jon Halld61331b2015-02-17 16:35:47 -0800171 self.exit()
adminbae64d82013-08-01 10:50:15 -0700172
173 vars(self)[component] = driverObject
174
175 def run(self):
176 '''
177 The Execution of the test script's cases listed in the Test params file will be done here.
178 And Update each test case result.
179 This method will return TRUE if it executed all the test cases successfully,
180 else will retun FALSE
181 '''
182
183 self.testCaseResult = {}
Jon Halla1185982014-09-15 14:55:10 -0700184 self.TOTAL_TC = 0
adminbae64d82013-08-01 10:50:15 -0700185 self.TOTAL_TC_RUN = 0
Jon Halld61331b2015-02-17 16:35:47 -0800186 self.TOTAL_TC_PLANNED = 0
adminbae64d82013-08-01 10:50:15 -0700187 self.TOTAL_TC_NORESULT = 0
188 self.TOTAL_TC_FAIL = 0
189 self.TOTAL_TC_PASS = 0
Jon Halla1185982014-09-15 14:55:10 -0700190 self.TEST_ITERATION = 0
adminbae64d82013-08-01 10:50:15 -0700191 self.stepCount = 0
192 self.CASERESULT = self.TRUE
193
Jon Halld61331b2015-02-17 16:35:47 -0800194 import testparser
adminbae64d82013-08-01 10:50:15 -0700195 testFile = self.tests_path + "/"+self.TEST + "/"+self.TEST + ".py"
196 test = testparser.TestParser(testFile)
197 self.testscript = test.testscript
198 self.code = test.getStepCode()
Jon Halla1185982014-09-15 14:55:10 -0700199 repeat= int(self.params['repeat']) if ('repeat' in self.params) else 1
200 main.TOTAL_TC_PLANNED = len(self.testcases_list)*repeat
adminbae64d82013-08-01 10:50:15 -0700201
202 result = self.TRUE
Jon Halla1185982014-09-15 14:55:10 -0700203 while(repeat):
204 for self.CurrentTestCaseNumber in self.testcases_list:
Jon Halld61331b2015-02-17 16:35:47 -0800205 result = self.runCase(self.CurrentTestCaseNumber)
206 repeat-=1
adminbae64d82013-08-01 10:50:15 -0700207 return result
208
209 def runCase(self,testCaseNumber):
210 self.CurrentTestCaseNumber = testCaseNumber
211 result = self.TRUE
212 self.stepCount = 0
213 self.EXPERIMENTAL_MODE = self.FALSE
214 self.addCaseHeader()
215 self.testCaseNumber = str(testCaseNumber)
216 stopped = False
217 try :
218 self.stepList = self.code[self.testCaseNumber].keys()
Jon Halld61331b2015-02-17 16:35:47 -0800219 except KeyError:
adminbae64d82013-08-01 10:50:15 -0700220 main.log.error("There is no Test-Case "+ self.testCaseNumber)
221 return main.FALSE
222
223 self.stepCount = 0
224 while self.stepCount < len(self.code[self.testCaseNumber].keys()):
225 result = self.runStep(self.stepList,self.code,self.testCaseNumber)
226 if result == main.FALSE:
227 break
228 elif result == main.TRUE :
229 continue
230
231 if not stopped :
232 self.testCaseResult[str(self.CurrentTestCaseNumber)] = self.CASERESULT
233 self.logger.updateCaseResults(self)
234 return result
235
236 def runStep(self,stepList,code,testCaseNumber):
237 if not cli.pause:
238 try :
239 step = stepList[self.stepCount]
240 exec code[testCaseNumber][step] in module.__dict__
241 self.stepCount = self.stepCount + 1
242 except TypeError,e:
243 self.stepCount = self.stepCount + 1
244 self.log.error(e)
245 return main.TRUE
246
247 if cli.stop:
248 cli.stop = False
249 stopped = True
250 self.TOTAL_TC_NORESULT = self.TOTAL_TC_NORESULT + 1
251 self.testCaseResult[str(self.CurrentTestCaseNumber)] = "Stopped"
252 self.logger.updateCaseResults(self)
253 result = self.cleanup()
254 return main.FALSE
255
256 def addCaseHeader(self):
257 caseHeader = "\n"+"*" * 30+"\n Result summary for Testcase"+str(self.CurrentTestCaseNumber)+"\n"+"*" * 30+"\n"
Jon Halld61331b2015-02-17 16:35:47 -0800258 self.log.exact(caseHeader)
259 caseHeader = "\n"+"*" * 40 +"\nStart of Test Case"+str(self.CurrentTestCaseNumber)+" : "
adminbae64d82013-08-01 10:50:15 -0700260 for driver in self.componentDictionary.keys():
261 vars(self)[driver+'log'].info(caseHeader)
262
263 def addCaseFooter(self):
264 if self.stepCount-1 > 0 :
265 previousStep = " "+str(self.CurrentTestCaseNumber)+"."+str(self.stepCount-1)+": "+ str(self.stepName) + ""
266 stepHeader = "\n"+"*" * 40+"\nEnd of Step "+previousStep+"\n"+"*" * 40+"\n"
267
268 caseFooter = "\n"+"*" * 40+"\nEnd of Test case "+str(self.CurrentTestCaseNumber)+"\n"+"*" * 40+"\n"
269
270 for driver in self.driversList:
271 vars(self)[driver].write(stepHeader+"\n"+caseFooter)
272
273 def cleanup(self):
274 '''
275 Release all the component handles and the close opened file handles.
276 This will return TRUE if all the component handles and log handles closed properly,
277 else return FALSE
278
279 '''
280 result = self.TRUE
281 self.logger.testSummary(self)
Jon Halld61331b2015-02-17 16:35:47 -0800282
adminbae64d82013-08-01 10:50:15 -0700283 #self.reportFile.close()
Jon Halld61331b2015-02-17 16:35:47 -0800284
adminbae64d82013-08-01 10:50:15 -0700285
admin2c7034f2013-08-02 15:09:17 -0700286 #utilities.send_mail()
adminbae64d82013-08-01 10:50:15 -0700287 try :
288 for component in self.componentDictionary.keys():
Jon Halld61331b2015-02-17 16:35:47 -0800289 tempObject = vars(self)[component]
290 print "Disconnecting " + str(tempObject)
adminbae64d82013-08-01 10:50:15 -0700291 tempObject.disconnect()
Jon Halld61331b2015-02-17 16:35:47 -0800292 #tempObject.execute(cmd="exit",prompt="(.*)",timeout=120)
adminbae64d82013-08-01 10:50:15 -0700293
294 except(Exception):
Jon Halld61331b2015-02-17 16:35:47 -0800295 self.log.exception( "Exception while disconnecting from " +
296 str( component ) )
Jon Halla1185982014-09-15 14:55:10 -0700297 #print " There is an error with closing hanldes"
adminbae64d82013-08-01 10:50:15 -0700298 result = self.FALSE
299 # Closing all the driver's session files
300 for driver in self.componentDictionary.keys():
301 vars(self)[driver].close_log_handles()
Jon Halld61331b2015-02-17 16:35:47 -0800302
adminbae64d82013-08-01 10:50:15 -0700303 return result
Jon Halld61331b2015-02-17 16:35:47 -0800304
adminbae64d82013-08-01 10:50:15 -0700305 def pause(self):
306 '''
307 This function will pause the test's execution, and will continue after user provide 'resume' command.
308 '''
309 __builtin__.testthread.pause()
310
311 def onfail(self,*components):
312 '''
313 When test step failed, calling all the components onfail.
314 '''
315
316 if not components:
317 try :
318 for component in self.componentDictionary.keys():
319 tempObject = vars(self)[component]
320 result = tempObject.onfail()
321 except(Exception),e:
322 print str(e)
323 result = self.FALSE
324
325 else:
326 try :
327 for component in components:
328 tempObject = vars(self)[component]
329 result = tempObject.onfail()
330 except(Exception),e:
331 print str(e)
332 result = self.FALSE
333
334
335 def getDriverPath(self,driverName):
336 '''
337 Based on the component 'type' specified in the params , this method will find the absolute path ,
338 by recursively searching the name of the component.
339 '''
340 import commands
341
342 cmd = "find "+drivers_path+" -name "+driverName+".py"
343 result = commands.getoutput(cmd)
344
345 result_array = str(result).split('\n')
346 result_count = 0
347
348 for drivers_list in result_array:
349 result_count = result_count+1
350 if result_count > 1 :
351 print "found "+driverName+" "+ str(result_count) + " times"+str(result_array)
352 self.exit()
353
354 result = re.sub("(.*)drivers","",result)
355 result = re.sub("\.py","",result)
356 result = re.sub("\.pyc","",result)
357 result = re.sub("\/",".",result)
358 result = "drivers"+result
359 return result
360
361
362 def step(self,stepDesc):
363 '''
364 The step information of the test-case will append to the logs.
365 '''
366 previousStep = " "+str(self.CurrentTestCaseNumber)+"."+str(self.stepCount-1)+": "+ str(self.stepName) + ""
367 self.stepName = stepDesc
368
369 stepName = " "+str(self.CurrentTestCaseNumber)+"."+str(self.stepCount)+": "+ str(stepDesc) + ""
370 try :
371 if self.stepCount == 0:
372 stepName = " INIT : Initializing the test case :"+self.CurrentTestCase
373 except AttributeError:
374 stepName = " INIT : Initializing the test case :"+str(self.CurrentTestCaseNumber)
375
376 self.log.step(stepName)
377 stepHeader = ""
378 if self.stepCount > 1 :
379 stepHeader = "\n"+"-"*45+"\nEnd of Step "+previousStep+"\n"+"-"*45+"\n"
380
Jon Halld61331b2015-02-17 16:35:47 -0800381 stepHeader += "\n"+"-"*45+"\nStart of Step"+stepName+"\n"+"-"*45+"\n"
adminbae64d82013-08-01 10:50:15 -0700382 for driver in self.componentDictionary.keys():
383 vars(self)[driver+'log'].info(stepHeader)
384
385 def case(self,testCaseName):
386 '''
387 Test's each test-case information will append to the logs.
388 '''
Jon Halld61331b2015-02-17 16:35:47 -0800389 self.CurrentTestCase = testCaseName
adminbae64d82013-08-01 10:50:15 -0700390 testCaseName = " " + str(testCaseName) + ""
391 self.log.case(testCaseName)
Jon Halld61331b2015-02-17 16:35:47 -0800392 caseHeader = testCaseName+"\n"+"*" * 40+"\n"
adminbae64d82013-08-01 10:50:15 -0700393 for driver in self.componentDictionary.keys():
394 vars(self)[driver+'log'].info(caseHeader)
395
396 def testDesc(self,description):
397 '''
398 Test description will append to the logs.
399 '''
400 description = "Test Description : " + str (description) + ""
401 self.log.info(description)
402
403 def _getTest(self):
404 '''
405 This method will parse the test script to find required test information.
406 '''
407 testFile = self.tests_path + "/"+self.TEST + "/"+self.TEST + ".py"
408 testFileHandler = open(testFile, 'r')
409 testFileList = testFileHandler.readlines()
410 testFileHandler.close()
411 #self.TOTAL_TC_PLANNED = 0
412 counter = 0
413 for index in range(len(testFileList)):
414 lineMatch = re.match('\s+def CASE(\d+)(.*):',testFileList[index],0)
415 if lineMatch:
416 counter = counter + 1
Jon Halla1185982014-09-15 14:55:10 -0700417 self.TC_PLANNED = len(self.testcases_list)
418
adminbae64d82013-08-01 10:50:15 -0700419
420 def response_parser(self,response, return_format):
421 ''' It will load the default response parser '''
422 response_dict = {}
423 response_dict = self.response_to_dict(response, return_format)
Jon Halld61331b2015-02-17 16:35:47 -0800424 return_format_string = self.dict_to_return_format(response,return_format,response_dict)
adminbae64d82013-08-01 10:50:15 -0700425 return return_format_string
426
427 def response_to_dict(self,response,return_format):
428
429 response_dict = {}
430 json_match = re.search('^\s*{', response)
431 xml_match = re.search('^\s*\<', response)
432 ini_match = re.search('^\s*\[', response)
433 if json_match :
434 main.log.info(" Response is in 'JSON' format and Converting to '"+return_format+"' format")
Jon Halld61331b2015-02-17 16:35:47 -0800435 # Formatting the json string
adminbae64d82013-08-01 10:50:15 -0700436
437 response = re.sub(r"{\s*'?(\w)", r'{"\1', response)
438 response = re.sub(r",\s*'?(\w)", r',"\1', response)
439 response = re.sub(r"(\w)'?\s*:", r'\1":', response)
440 response = re.sub(r":\s*'(\w)'\s*([,}])", r':"\1"\2', response)
441
442 try :
443 import json
444 response_dict = json.loads(response)
445 except Exception , e :
446 print e
447 main.log.error("Json Parser is unable to parse the string")
448 return response_dict
449
450 elif ini_match :
451 main.log.info(" Response is in 'INI' format and Converting to '"+return_format+"' format")
452 from configobj import ConfigObj
453 response_file = open("respnse_file.temp",'w')
454 response_file.write(response)
Jon Halld61331b2015-02-17 16:35:47 -0800455 response_file.close()
adminbae64d82013-08-01 10:50:15 -0700456 response_dict = ConfigObj("respnse_file.temp")
457 return response_dict
458
459 elif xml_match :
460 main.log.info(" Response is in 'XML' format and Converting to '"+return_format+"' format")
461 try :
adminbae64d82013-08-01 10:50:15 -0700462 response_dict = xmldict.xml_to_dict("<response> "+str(response)+" </response>")
463 except Exception, e:
464 main.log.error(e)
465 return response_dict
466
467 def dict_to_return_format(self,response,return_format,response_dict):
468
469 if return_format =='table' :
470 ''' Will return in table format'''
471 to_do = "Call the table output formatter"
472 global response_table
473 response_table = '\n'
474 response_table = response_table +'\t'.join(response_dict)+"\n"
475
476 def get_table(value_to_convert):
477 ''' This will parse the dictionary recusrsively and print as table format'''
478 table_data = ""
479 if type(value_to_convert) == dict :
480 table_data = table_data +'\t'.join(value_to_convert)+"\n"
481 for temp_val in value_to_convert.values() :
482 table_data = table_data + get_table(temp_val)
483 else :
484 table_data = table_data + str(value_to_convert) +"\t"
Jon Halld61331b2015-02-17 16:35:47 -0800485 return table_data
adminbae64d82013-08-01 10:50:15 -0700486
487 for value in response_dict.values() :
488 response_table = response_table + get_table(value)
489
490
491
492 #response_table = response_table + '\t'.join(response_dict.values())
493
494 return response_table
495
496 elif return_format =='config':
497 ''' Will return in config format'''
498 to_do = 'Call dict to config coverter'
499 response_string = str(response_dict)
500 print response_string
501 response_config = re.sub(",", "\n\t", response_string)
502 response_config = re.sub("u\'", "\'", response_config)
503 response_config = re.sub("{", "", response_config)
504 response_config = re.sub("}", "\n", response_config)
505 response_config = re.sub(":", " =", response_config)
506 return "[response]\n\t "+response_config
507
508 elif return_format == 'xml':
509 ''' Will return in xml format'''
adminbae64d82013-08-01 10:50:15 -0700510 response_xml = xmldict.dict_to_xml(response_dict)
511 response_xml = re.sub(">\s*<", ">\n<", response_xml)
512 return "\n"+response_xml
513
514 elif return_format == 'json':
515 ''' Will return in json format'''
516 to_do = 'Call dict to xml coverter'
517 import json
518 response_json = json.dumps(response_dict)
519 return response_json
520
521 def get_random(self):
522 self.random_order = self.random_order + 1
523 return self.random_order
524
525 def exit(self):
526 __builtin__.testthread = None
527 sys.exit()
528
529def verifyOptions(options):
530 '''
531 This will verify the command line options and set to default values, if any option not given in command line.
532 '''
533 import pprint
534 pp = pprint.PrettyPrinter(indent=4)
535
536 #pp.pprint(options)
537 verifyTest(options)
538 verifyExample(options)
539 verifyTestScript(options)
540 verifyParams()
541 verifyLogdir(options)
542 verifyMail(options)
543 verifyTestCases(options)
544
545def verifyTest(options):
546 if options.testname:
547 main.TEST = options.testname
548 main.classPath = "tests."+main.TEST+"."+main.TEST
549 main.tests_path = tests_path
550 elif options.example :
551 main.TEST = options.example
552 main.tests_path = path+"/examples/"
553 main.classPath = "examples."+main.TEST+"."+main.TEST
554 else :
555 print "Test or Example not specified please specify the --test <test name > or --example <example name>"
556 self.exit()
557
558def verifyExample(options):
559 if options.example:
560 main.testDir = path+'/examples/'
561 main.tests_path = path+"/examples/"
562 main.classPath = "examples."+main.TEST+"."+main.TEST
563
564def verifyLogdir(options):
Jon Halld61331b2015-02-17 16:35:47 -0800565 #Verifying Log directory option
adminbae64d82013-08-01 10:50:15 -0700566 if options.logdir:
567 main.logdir = options.logdir
568 else :
Jon Halld61331b2015-02-17 16:35:47 -0800569 main.logdir = main.FALSE
adminbae64d82013-08-01 10:50:15 -0700570
571def verifyMail(options):
Jon Halld61331b2015-02-17 16:35:47 -0800572 # Checking the mailing list
adminbae64d82013-08-01 10:50:15 -0700573 if options.mail:
574 main.mail = options.mail
575 elif main.params.has_key('mail'):
576 main.mail = main.params['mail']
577 else :
578 main.mail = 'paxweb@paxterrasolutions.com'
579
580def verifyTestCases(options):
Jon Halld61331b2015-02-17 16:35:47 -0800581 #Getting Test cases list
adminbae64d82013-08-01 10:50:15 -0700582 if options.testcases:
Jon Halld61331b2015-02-17 16:35:47 -0800583 testcases_list = options.testcases
584 #sys.exit()
adminbae64d82013-08-01 10:50:15 -0700585 testcases_list = re.sub("(\[|\])", "", options.testcases)
586 main.testcases_list = eval(testcases_list+",")
587 else :
588 if 'testcases' in main.params.keys():
Jon Halla1185982014-09-15 14:55:10 -0700589 temp = eval(main.params['testcases']+",")
590 list1=[]
591 if type(temp[0])==list:
592 for test in temp:
593 for testcase in test:
594 if type(testcase)==int:
595 testcase=[testcase]
596 list1.extend(testcase)
597 else :
598 temp=list(temp)
599 for testcase in temp:
600 if type(testcase)==int:
601 testcase=[testcase]
602 list1.extend(testcase)
Jon Halld61331b2015-02-17 16:35:47 -0800603 main.testcases_list=list1
adminbae64d82013-08-01 10:50:15 -0700604 else :
605 print "testcases not specifed in params, please provide in params file or 'testcases' commandline argument"
Jon Halld61331b2015-02-17 16:35:47 -0800606 sys.exit()
adminbae64d82013-08-01 10:50:15 -0700607
608def verifyTestScript(options):
609 '''
610 Verifyies test script.
611 '''
Jon Halld61331b2015-02-17 16:35:47 -0800612 main.openspeak = openspeak.OpenSpeak()
adminbae64d82013-08-01 10:50:15 -0700613 openspeakfile = main.testDir+"/" + main.TEST + "/" + main.TEST + ".ospk"
614 testfile = main.testDir+"/" + main.TEST + "/" + main.TEST + ".py"
615 if os.path.exists(openspeakfile) :
616 main.openspeak.compiler(openspeakfile=openspeakfile,writetofile=1)
617 elif os.path.exists(testfile):
618 print ''
619 else:
620 print "\nThere is no :\""+main.TEST+"\" test, Please Provide OpenSpeak Script/ test script"
621 __builtin__.testthread = None
622 main.exit()
623
624 try :
adminbae64d82013-08-01 10:50:15 -0700625 testModule = __import__(main.classPath, globals(), locals(), [main.TEST], -1)
626 except(ImportError):
Jon Hallf8ecf732014-12-02 21:14:16 -0500627 print "There was an import error, it might mean that there is no test like "+main.TEST
Jon Halld61331b2015-02-17 16:35:47 -0800628 main.exit()
adminbae64d82013-08-01 10:50:15 -0700629
630 testClass = getattr(testModule, main.TEST)
631 main.testObject = testClass()
632 load_parser()
Jon Halld61331b2015-02-17 16:35:47 -0800633 main.params = main.parser.parseParams(main.classPath)
634 main.topology = main.parser.parseTopology(main.classPath)
adminbae64d82013-08-01 10:50:15 -0700635
636def verifyParams():
637 try :
638 main.params = main.params['PARAMS']
639 except(KeyError):
640 print "Error with the params file: Either the file not specified or the format is not correct"
Jon Halld61331b2015-02-17 16:35:47 -0800641 main.exit()
adminbae64d82013-08-01 10:50:15 -0700642
643 try :
644 main.topology = main.topology['TOPOLOGY']
645 except(KeyError):
646 print "Error with the Topology file: Either the file not specified or the format is not correct"
647 main.exit()
648
649def load_parser() :
650 '''
651 It facilitates the loading customised parser for topology and params file.
652 It loads parser mentioned in tab named parser of teston.cfg file.
653 It also loads default xmlparser if no parser have specified in teston.cfg file.
654
655 '''
656 confighash = main.configDict
657 if 'file' in confighash['config']['parser'] and 'class' in confighash['config']['parser']:
658 if confighash['config']['parser']['file'] != None or confighash['config']['parser']['class']!= None :
659 if os.path.exists(confighash['config']['parser']['file']) :
660 module = re.sub(r".py\s*$","",confighash['config']['parser']['file'])
661 moduleList = module.split("/")
662 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
663 try :
664 parsingClass = confighash['config']['parser']['class']
665 parsingModule = __import__(newModule, globals(), locals(), [parsingClass], -1)
666 parsingClass = getattr(parsingModule, parsingClass)
667 main.parser = parsingClass()
668 #hashobj = main.parser.parseParams(main.classPath)
669 if hasattr(main.parser,"parseParams") and hasattr(main.parser,"parseTopology") and hasattr(main.parser,"parse") :
670
671 pass
672 else:
673 main.exit()
674
675 except ImportError:
676 print sys.exc_info()[1]
677 main.exit()
678 else :
679 print "No Such File Exists !!"+ confighash['config']['parser']['file'] +"using default parser"
Jon Halld61331b2015-02-17 16:35:47 -0800680 load_defaultParser()
681 elif confighash['config']['parser']['file'] == None or confighash['config']['parser']['class'] == None :
682 load_defaultParser()
adminbae64d82013-08-01 10:50:15 -0700683 else:
684 load_defaultParser()
685
686def load_defaultParser():
687 '''
688 It will load the default parser which is xml parser to parse the params and topology file.
689 '''
690 moduleList = main.parserPath.split("/")
691 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
692 try :
Jon Halld61331b2015-02-17 16:35:47 -0800693 parsingClass = main.parsingClass
adminbae64d82013-08-01 10:50:15 -0700694 parsingModule = __import__(newModule, globals(), locals(), [parsingClass], -1)
695 parsingClass = getattr(parsingModule, parsingClass)
696 main.parser = parsingClass()
697 if hasattr(main.parser,"parseParams") and hasattr(main.parser,"parseTopology") and hasattr(main.parser,"parse") :
698 pass
699 else:
700 main.exit()
701
702 except ImportError:
703 print sys.exc_info()[1]
704
705
706def load_logger() :
707 '''
708 It facilitates the loading customised parser for topology and params file.
709 It loads parser mentioned in tab named parser of teston.cfg file.
710 It also loads default xmlparser if no parser have specified in teston.cfg file.
711
712 '''
713 confighash = main.configDict
714 if 'file' in confighash['config']['logger'] and 'class' in confighash['config']['logger']:
715 if confighash['config']['logger']['file'] != None or confighash['config']['logger']['class']!= None :
716 if os.path.exists(confighash['config']['logger']['file']) :
717 module = re.sub(r".py\s*$","",confighash['config']['logger']['file'])
718 moduleList = module.split("/")
719 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
720 try :
721 loggerClass = confighash['config']['logger']['class']
722 loggerModule = __import__(newModule, globals(), locals(), [loggerClass], -1)
723 loggerClass = getattr(loggerModule, loggerClass)
724 main.logger = loggerClass()
725 #hashobj = main.parser.parseParams(main.classPath)
726
727 except ImportError:
728 print sys.exc_info()[1]
729 else :
730 print "No Such File Exists !!"+confighash['config']['logger']['file']+ "Using default logger"
731 load_defaultlogger()
Jon Halld61331b2015-02-17 16:35:47 -0800732 elif confighash['config']['parser']['file'] == None or confighash['config']['parser']['class'] == None :
733 load_defaultlogger()
adminbae64d82013-08-01 10:50:15 -0700734 else:
735 load_defaultlogger()
736
737def load_defaultlogger():
738 '''
739 It will load the default parser which is xml parser to parse the params and topology file.
740 '''
741 moduleList = main.loggerPath.split("/")
742 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
743 try :
Jon Halld61331b2015-02-17 16:35:47 -0800744 loggerClass = main.loggerClass
adminbae64d82013-08-01 10:50:15 -0700745 loggerModule = __import__(newModule, globals(), locals(), [loggerClass], -1)
746 loggerClass = getattr(loggerModule, loggerClass)
747 main.logger = loggerClass()
748
749 except ImportError:
750 print sys.exc_info()[1]
Jon Halld61331b2015-02-17 16:35:47 -0800751 main.exit()
adminbae64d82013-08-01 10:50:15 -0700752
753def load_defaultlogger():
754 '''
755 It will load the default parser which is xml parser to parse the params and topology file.
756 '''
757 moduleList = main.loggerPath.split("/")
758 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
759 try :
Jon Halld61331b2015-02-17 16:35:47 -0800760 loggerClass = main.loggerClass
adminbae64d82013-08-01 10:50:15 -0700761 loggerModule = __import__(newModule, globals(), locals(), [loggerClass], -1)
762 loggerClass = getattr(loggerModule, loggerClass)
763 main.logger = loggerClass()
764
765 except ImportError:
766 print sys.exc_info()[1]
767 main.exit()
768
769
770
771
772def _echo(self):
773 print "THIS IS ECHO"