blob: 869cab7b9f2c160aa77b3291a5466e56fbfd0f61 [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
admin530b4c92013-08-14 16:54:35 -070028import pprint
adminbae64d82013-08-01 10:50:15 -070029import getpass
30import os
31import re
32import __builtin__
33import new
34import xmldict
35module = 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
50
51import logging
52import datetime
53from optparse import OptionParser
54
55class TestON:
56 '''
57
58 TestON will initiate the specified test.
59 The main tasks are :
60 * Initiate the required Component handles for the test.
61 * Create Log file Handles.
62
63 '''
64 def __init__(self,options):
65 '''
66 Initialise the component handles specified in the topology file of the specified test.
67
68 '''
69 # Initialization of the variables.
70 __builtin__.main = self
admin530b4c92013-08-14 16:54:35 -070071 pprint.pprint(sys.path)
adminbae64d82013-08-01 10:50:15 -070072 __builtin__.path = path
73 __builtin__.utilities = Utilities()
74 self.TRUE = 1
75 self.FALSE = 0
76 self.ERROR = -1
77 self.FAIL = False
78 self.PASS = True
79 self.CASERESULT = self.TRUE
80 self.init_result = self.TRUE
81 self.testResult = "Summary"
82 self.stepName =""
83 self.EXPERIMENTAL_MODE = False
84 self.test_target = None
85 self.lastcommand = None
86 self.testDir = tests_path
87 self.configFile = config_path + "teston.cfg"
88 self.parsingClass = "xmlparser"
89 self.parserPath = core_path + "/xmlparser"
90 self.loggerPath = core_path + "/logger"
91 self.loggerClass = "Logger"
92 self.logs_path = logs_path
93 self.driver = ''
94
95 self.configparser()
96 verifyOptions(options)
97 load_logger()
98 self.componentDictionary = {}
99 self.componentDictionary = self.topology ['COMPONENT']
100 self.driversList=[]
101 if type(self.componentDictionary) == str :
102 self.componentDictionary = dict(self.componentDictionary)
103
104 for component in self.componentDictionary :
105 self.driversList.append(self.componentDictionary[component]['type'])
106
107 self.driversList = list(set(self.driversList)) # Removing duplicates.
108 # Checking the test_target option set for the component or not
109 if type(self.componentDictionary) == dict:
110 for component in self.componentDictionary.keys():
111 if 'test_target' in self.componentDictionary[component].keys():
112 self.test_target = component
113
114 # Checking for the openspeak file and test script
115 self.logger.initlog(self)
116
117 # Creating Drivers Handles
118 initString = "\n"+"*" * 30+"\n CASE INIT \n"+"*" * 30+"\n"
119 self.log.exact(initString)
120 self.driverObject = {}
121 self.random_order = 111 # Random order id to connect the components
122 components_connect_order = {}
123 #component_list.append()
124 if type(self.componentDictionary) == dict:
125 for component in self.componentDictionary.keys():
126 self.componentDictionary[component]['connect_order'] = self.componentDictionary[component]['connect_order'] if ('connect_order' in self.componentDictionary[component].keys()) else str(self.get_random())
127 components_connect_order[component] = eval(self.componentDictionary[component]['connect_order'])
128 #Ordering components based on the connect order.
129 ordered_component_list =sorted(components_connect_order, key=lambda key: components_connect_order[key])
130 print ordered_component_list
131
132 for component in ordered_component_list:
133 self.componentInit(component)
134
135 def configparser(self):
136 '''
137 It will parse the config file (teston.cfg) and return as dictionary
138 '''
139 matchFileName = re.match(r'(.*)\.cfg', self.configFile, re.M | re.I)
140 if matchFileName:
141 xml = open(self.configFile).read()
142 try :
143 self.configDict = xmldict.xml_to_dict(xml)
144 return self.configDict
145 except :
146 print "There is no such file to parse " + self.configFile
147
148 def componentInit(self,component):
149 '''
150 This method will initialize specified component
151 '''
152 global driver_options
153 self.log.info("Creating component Handle: "+component)
154 driver_options = {}
155 if 'COMPONENTS' in self.componentDictionary[component].keys():
156 driver_options =dict(self.componentDictionary[component]['COMPONENTS'])
157
158 driver_options['name']=component
159 driverName = self.componentDictionary[component]['type']
160 driver_options ['type'] = driverName
161
162 classPath = self.getDriverPath(driverName.lower())
163 driverModule = __import__(classPath, globals(), locals(), [driverName.lower()], -1)
164 driverClass = getattr(driverModule, driverName)
165 driverObject = driverClass()
166
167 connect_result = driverObject.connect(user_name = self.componentDictionary[component]['user'] if ('user' in self.componentDictionary[component].keys()) else getpass.getuser(),
168 ip_address= self.componentDictionary[component]['host'] if ('host' in self.componentDictionary[component].keys()) else 'localhost',
169 pwd = self.componentDictionary[component]['password'] if ('password' in self.componentDictionary[component].keys()) else 'changeme',
170 port = self.componentDictionary[component]['port'] if ('port' in self.componentDictionary[component].keys()) else None,
171 options = driver_options)
172 if not connect_result:
173 self.log.error("Exiting form the test execution because the connecting to the "+component+" component failed.")
174 self.exit()
175
176 vars(self)[component] = driverObject
177
178 def run(self):
179 '''
180 The Execution of the test script's cases listed in the Test params file will be done here.
181 And Update each test case result.
182 This method will return TRUE if it executed all the test cases successfully,
183 else will retun FALSE
184 '''
185
186 self.testCaseResult = {}
187 self.TOTAL_TC_RUN = 0
188 self.TOTAL_TC_NORESULT = 0
189 self.TOTAL_TC_FAIL = 0
190 self.TOTAL_TC_PASS = 0
191 self.stepCount = 0
192 self.CASERESULT = self.TRUE
193
194 import testparser
195 testFile = self.tests_path + "/"+self.TEST + "/"+self.TEST + ".py"
196 test = testparser.TestParser(testFile)
197 self.testscript = test.testscript
198 self.code = test.getStepCode()
199
200 result = self.TRUE
201 for self.CurrentTestCaseNumber in self.testcases_list:
202 result = self.runCase(self.CurrentTestCaseNumber)
203 return result
204
205 def runCase(self,testCaseNumber):
206 self.CurrentTestCaseNumber = testCaseNumber
207 result = self.TRUE
208 self.stepCount = 0
209 self.EXPERIMENTAL_MODE = self.FALSE
210 self.addCaseHeader()
211 self.testCaseNumber = str(testCaseNumber)
212 stopped = False
213 try :
214 self.stepList = self.code[self.testCaseNumber].keys()
215 except KeyError,e:
216 main.log.error("There is no Test-Case "+ self.testCaseNumber)
217 return main.FALSE
218
219 self.stepCount = 0
220 while self.stepCount < len(self.code[self.testCaseNumber].keys()):
221 result = self.runStep(self.stepList,self.code,self.testCaseNumber)
222 if result == main.FALSE:
223 break
224 elif result == main.TRUE :
225 continue
226
227 if not stopped :
228 self.testCaseResult[str(self.CurrentTestCaseNumber)] = self.CASERESULT
229 self.logger.updateCaseResults(self)
230 return result
231
232 def runStep(self,stepList,code,testCaseNumber):
233 if not cli.pause:
234 try :
235 step = stepList[self.stepCount]
236 exec code[testCaseNumber][step] in module.__dict__
237 self.stepCount = self.stepCount + 1
238 except TypeError,e:
239 self.stepCount = self.stepCount + 1
240 self.log.error(e)
241 return main.TRUE
242
243 if cli.stop:
244 cli.stop = False
245 stopped = True
246 self.TOTAL_TC_NORESULT = self.TOTAL_TC_NORESULT + 1
247 self.testCaseResult[str(self.CurrentTestCaseNumber)] = "Stopped"
248 self.logger.updateCaseResults(self)
249 result = self.cleanup()
250 return main.FALSE
251
252 def addCaseHeader(self):
253 caseHeader = "\n"+"*" * 30+"\n Result summary for Testcase"+str(self.CurrentTestCaseNumber)+"\n"+"*" * 30+"\n"
254 self.log.exact(caseHeader)
255 caseHeader = "\n"+"*" * 40 +"\nStart of Test Case"+str(self.CurrentTestCaseNumber)+" : "
256 for driver in self.componentDictionary.keys():
257 vars(self)[driver+'log'].info(caseHeader)
258
259 def addCaseFooter(self):
260 if self.stepCount-1 > 0 :
261 previousStep = " "+str(self.CurrentTestCaseNumber)+"."+str(self.stepCount-1)+": "+ str(self.stepName) + ""
262 stepHeader = "\n"+"*" * 40+"\nEnd of Step "+previousStep+"\n"+"*" * 40+"\n"
263
264 caseFooter = "\n"+"*" * 40+"\nEnd of Test case "+str(self.CurrentTestCaseNumber)+"\n"+"*" * 40+"\n"
265
266 for driver in self.driversList:
267 vars(self)[driver].write(stepHeader+"\n"+caseFooter)
268
269 def cleanup(self):
270 '''
271 Release all the component handles and the close opened file handles.
272 This will return TRUE if all the component handles and log handles closed properly,
273 else return FALSE
274
275 '''
276 result = self.TRUE
277 self.logger.testSummary(self)
278
279 #self.reportFile.close()
280
281
admin2c7034f2013-08-02 15:09:17 -0700282 #utilities.send_mail()
adminbae64d82013-08-01 10:50:15 -0700283 try :
284 for component in self.componentDictionary.keys():
285 tempObject = vars(self)[component]
286 print "Disconnecting "+str(tempObject)
287
288 tempObject.disconnect()
289 #tempObject.execute(cmd="exit",prompt="(.*)",timeout=120)
290
291 except(Exception):
admin2c7034f2013-08-02 15:09:17 -0700292 print " There is an error with closing hanldes"
adminbae64d82013-08-01 10:50:15 -0700293 result = self.FALSE
294 # Closing all the driver's session files
295 for driver in self.componentDictionary.keys():
296 vars(self)[driver].close_log_handles()
297
298 print( "CLEAN!" )
299 return result
300
301 def pause(self):
302 '''
303 This function will pause the test's execution, and will continue after user provide 'resume' command.
304 '''
305 __builtin__.testthread.pause()
306
307 def onfail(self,*components):
308 '''
309 When test step failed, calling all the components onfail.
310 '''
311
312 if not components:
313 try :
314 for component in self.componentDictionary.keys():
315 tempObject = vars(self)[component]
316 result = tempObject.onfail()
317 except(Exception),e:
318 print str(e)
319 result = self.FALSE
320
321 else:
322 try :
323 for component in components:
324 tempObject = vars(self)[component]
325 result = tempObject.onfail()
326 except(Exception),e:
327 print str(e)
328 result = self.FALSE
329
330
331 def getDriverPath(self,driverName):
332 '''
333 Based on the component 'type' specified in the params , this method will find the absolute path ,
334 by recursively searching the name of the component.
335 '''
336 import commands
337
338 cmd = "find "+drivers_path+" -name "+driverName+".py"
339 result = commands.getoutput(cmd)
340
341 result_array = str(result).split('\n')
342 result_count = 0
343
344 for drivers_list in result_array:
345 result_count = result_count+1
346 if result_count > 1 :
347 print "found "+driverName+" "+ str(result_count) + " times"+str(result_array)
348 self.exit()
349
350 result = re.sub("(.*)drivers","",result)
351 result = re.sub("\.py","",result)
352 result = re.sub("\.pyc","",result)
353 result = re.sub("\/",".",result)
354 result = "drivers"+result
355 return result
356
357
358 def step(self,stepDesc):
359 '''
360 The step information of the test-case will append to the logs.
361 '''
362 previousStep = " "+str(self.CurrentTestCaseNumber)+"."+str(self.stepCount-1)+": "+ str(self.stepName) + ""
363 self.stepName = stepDesc
364
365 stepName = " "+str(self.CurrentTestCaseNumber)+"."+str(self.stepCount)+": "+ str(stepDesc) + ""
366 try :
367 if self.stepCount == 0:
368 stepName = " INIT : Initializing the test case :"+self.CurrentTestCase
369 except AttributeError:
370 stepName = " INIT : Initializing the test case :"+str(self.CurrentTestCaseNumber)
371
372 self.log.step(stepName)
373 stepHeader = ""
374 if self.stepCount > 1 :
375 stepHeader = "\n"+"-"*45+"\nEnd of Step "+previousStep+"\n"+"-"*45+"\n"
376
377 stepHeader += "\n"+"-"*45+"\nStart of Step"+stepName+"\n"+"-"*45+"\n"
378 for driver in self.componentDictionary.keys():
379 vars(self)[driver+'log'].info(stepHeader)
380
381 def case(self,testCaseName):
382 '''
383 Test's each test-case information will append to the logs.
384 '''
385 self.CurrentTestCase = testCaseName
386 testCaseName = " " + str(testCaseName) + ""
387 self.log.case(testCaseName)
388 caseHeader = testCaseName+"\n"+"*" * 40+"\n"
389 for driver in self.componentDictionary.keys():
390 vars(self)[driver+'log'].info(caseHeader)
391
392 def testDesc(self,description):
393 '''
394 Test description will append to the logs.
395 '''
396 description = "Test Description : " + str (description) + ""
397 self.log.info(description)
398
399 def _getTest(self):
400 '''
401 This method will parse the test script to find required test information.
402 '''
403 testFile = self.tests_path + "/"+self.TEST + "/"+self.TEST + ".py"
404 testFileHandler = open(testFile, 'r')
405 testFileList = testFileHandler.readlines()
406 testFileHandler.close()
407 #self.TOTAL_TC_PLANNED = 0
408 counter = 0
409 for index in range(len(testFileList)):
410 lineMatch = re.match('\s+def CASE(\d+)(.*):',testFileList[index],0)
411 if lineMatch:
412 counter = counter + 1
413 self.TOTAL_TC_PLANNED = counter
414
415 def response_parser(self,response, return_format):
416 ''' It will load the default response parser '''
417 response_dict = {}
418 response_dict = self.response_to_dict(response, return_format)
419 return_format_string = self.dict_to_return_format(response,return_format,response_dict)
420 return return_format_string
421
422 def response_to_dict(self,response,return_format):
423
424 response_dict = {}
425 json_match = re.search('^\s*{', response)
426 xml_match = re.search('^\s*\<', response)
427 ini_match = re.search('^\s*\[', response)
428 if json_match :
429 main.log.info(" Response is in 'JSON' format and Converting to '"+return_format+"' format")
430 # Formatting the json string
431
432 response = re.sub(r"{\s*'?(\w)", r'{"\1', response)
433 response = re.sub(r",\s*'?(\w)", r',"\1', response)
434 response = re.sub(r"(\w)'?\s*:", r'\1":', response)
435 response = re.sub(r":\s*'(\w)'\s*([,}])", r':"\1"\2', response)
436
437 try :
438 import json
439 response_dict = json.loads(response)
440 except Exception , e :
441 print e
442 main.log.error("Json Parser is unable to parse the string")
443 return response_dict
444
445 elif ini_match :
446 main.log.info(" Response is in 'INI' format and Converting to '"+return_format+"' format")
447 from configobj import ConfigObj
448 response_file = open("respnse_file.temp",'w')
449 response_file.write(response)
450 response_file.close()
451 response_dict = ConfigObj("respnse_file.temp")
452 return response_dict
453
454 elif xml_match :
455 main.log.info(" Response is in 'XML' format and Converting to '"+return_format+"' format")
456 try :
457 from core import dicttoobject
458 response_dict = xmldict.xml_to_dict("<response> "+str(response)+" </response>")
459 except Exception, e:
460 main.log.error(e)
461 return response_dict
462
463 def dict_to_return_format(self,response,return_format,response_dict):
464
465 if return_format =='table' :
466 ''' Will return in table format'''
467 to_do = "Call the table output formatter"
468 global response_table
469 response_table = '\n'
470 response_table = response_table +'\t'.join(response_dict)+"\n"
471
472 def get_table(value_to_convert):
473 ''' This will parse the dictionary recusrsively and print as table format'''
474 table_data = ""
475 if type(value_to_convert) == dict :
476 table_data = table_data +'\t'.join(value_to_convert)+"\n"
477 for temp_val in value_to_convert.values() :
478 table_data = table_data + get_table(temp_val)
479 else :
480 table_data = table_data + str(value_to_convert) +"\t"
481 return table_data
482
483 for value in response_dict.values() :
484 response_table = response_table + get_table(value)
485
486
487
488 #response_table = response_table + '\t'.join(response_dict.values())
489
490 return response_table
491
492 elif return_format =='config':
493 ''' Will return in config format'''
494 to_do = 'Call dict to config coverter'
495 response_string = str(response_dict)
496 print response_string
497 response_config = re.sub(",", "\n\t", response_string)
498 response_config = re.sub("u\'", "\'", response_config)
499 response_config = re.sub("{", "", response_config)
500 response_config = re.sub("}", "\n", response_config)
501 response_config = re.sub(":", " =", response_config)
502 return "[response]\n\t "+response_config
503
504 elif return_format == 'xml':
505 ''' Will return in xml format'''
506 from core import dicttoobject
507 response_xml = xmldict.dict_to_xml(response_dict)
508 response_xml = re.sub(">\s*<", ">\n<", response_xml)
509 return "\n"+response_xml
510
511 elif return_format == 'json':
512 ''' Will return in json format'''
513 to_do = 'Call dict to xml coverter'
514 import json
515 response_json = json.dumps(response_dict)
516 return response_json
517
518 def get_random(self):
519 self.random_order = self.random_order + 1
520 return self.random_order
521
522 def exit(self):
523 __builtin__.testthread = None
524 sys.exit()
525
526def verifyOptions(options):
527 '''
528 This will verify the command line options and set to default values, if any option not given in command line.
529 '''
530 import pprint
531 pp = pprint.PrettyPrinter(indent=4)
532
533 #pp.pprint(options)
534 verifyTest(options)
535 verifyExample(options)
536 verifyTestScript(options)
537 verifyParams()
538 verifyLogdir(options)
539 verifyMail(options)
540 verifyTestCases(options)
541
542def verifyTest(options):
543 if options.testname:
544 main.TEST = options.testname
545 main.classPath = "tests."+main.TEST+"."+main.TEST
546 main.tests_path = tests_path
547 elif options.example :
548 main.TEST = options.example
549 main.tests_path = path+"/examples/"
550 main.classPath = "examples."+main.TEST+"."+main.TEST
551 else :
552 print "Test or Example not specified please specify the --test <test name > or --example <example name>"
553 self.exit()
554
555def verifyExample(options):
556 if options.example:
557 main.testDir = path+'/examples/'
558 main.tests_path = path+"/examples/"
559 main.classPath = "examples."+main.TEST+"."+main.TEST
560
561def verifyLogdir(options):
562 #Verifying Log directory option
563 if options.logdir:
564 main.logdir = options.logdir
565 else :
566 main.logdir = main.FALSE
567
568def verifyMail(options):
569 # Checking the mailing list
570 if options.mail:
571 main.mail = options.mail
572 elif main.params.has_key('mail'):
573 main.mail = main.params['mail']
574 else :
575 main.mail = 'paxweb@paxterrasolutions.com'
576
577def verifyTestCases(options):
578 #Getting Test cases list
579 if options.testcases:
580 testcases_list = re.sub("(\[|\])", "", options.testcases)
581 main.testcases_list = eval(testcases_list+",")
582 else :
583 if 'testcases' in main.params.keys():
584 main.params['testcases'] = re.sub("(\[|\])", "", main.params['testcases'])
585 if re.search('\d+', main.params['testcases'], 0):
586 main.testcases_list = eval(main.params['testcases']+",")
587 else :
588 print "Please provide the testcases list in Params file"
589 sys.exit()
590 else :
591 print "testcases not specifed in params, please provide in params file or 'testcases' commandline argument"
592 sys.exit()
593
594def verifyTestScript(options):
595 '''
596 Verifyies test script.
597 '''
598 main.openspeak = openspeak.OpenSpeak()
599 openspeakfile = main.testDir+"/" + main.TEST + "/" + main.TEST + ".ospk"
600 testfile = main.testDir+"/" + main.TEST + "/" + main.TEST + ".py"
601 if os.path.exists(openspeakfile) :
602 main.openspeak.compiler(openspeakfile=openspeakfile,writetofile=1)
603 elif os.path.exists(testfile):
604 print ''
605 else:
606 print "\nThere is no :\""+main.TEST+"\" test, Please Provide OpenSpeak Script/ test script"
607 __builtin__.testthread = None
608 main.exit()
609
610 try :
admin530b4c92013-08-14 16:54:35 -0700611 print main.classPath
adminbae64d82013-08-01 10:50:15 -0700612 testModule = __import__(main.classPath, globals(), locals(), [main.TEST], -1)
613 except(ImportError):
614 print "There is no test like "+main.TEST
615 main.exit()
616
617 testClass = getattr(testModule, main.TEST)
618 main.testObject = testClass()
619 load_parser()
620 main.params = main.parser.parseParams(main.classPath)
621 main.topology = main.parser.parseTopology(main.classPath)
622
623def verifyParams():
624 try :
625 main.params = main.params['PARAMS']
626 except(KeyError):
627 print "Error with the params file: Either the file not specified or the format is not correct"
628 main.exit()
629
630 try :
631 main.topology = main.topology['TOPOLOGY']
632 except(KeyError):
633 print "Error with the Topology file: Either the file not specified or the format is not correct"
634 main.exit()
635
636def load_parser() :
637 '''
638 It facilitates the loading customised parser for topology and params file.
639 It loads parser mentioned in tab named parser of teston.cfg file.
640 It also loads default xmlparser if no parser have specified in teston.cfg file.
641
642 '''
643 confighash = main.configDict
644 if 'file' in confighash['config']['parser'] and 'class' in confighash['config']['parser']:
645 if confighash['config']['parser']['file'] != None or confighash['config']['parser']['class']!= None :
646 if os.path.exists(confighash['config']['parser']['file']) :
647 module = re.sub(r".py\s*$","",confighash['config']['parser']['file'])
648 moduleList = module.split("/")
649 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
650 try :
651 parsingClass = confighash['config']['parser']['class']
652 parsingModule = __import__(newModule, globals(), locals(), [parsingClass], -1)
653 parsingClass = getattr(parsingModule, parsingClass)
654 main.parser = parsingClass()
655 #hashobj = main.parser.parseParams(main.classPath)
656 if hasattr(main.parser,"parseParams") and hasattr(main.parser,"parseTopology") and hasattr(main.parser,"parse") :
657
658 pass
659 else:
660 main.exit()
661
662 except ImportError:
663 print sys.exc_info()[1]
664 main.exit()
665 else :
666 print "No Such File Exists !!"+ confighash['config']['parser']['file'] +"using default parser"
667 load_defaultParser()
668 elif confighash['config']['parser']['file'] == None or confighash['config']['parser']['class'] == None :
669 load_defaultParser()
670 else:
671 load_defaultParser()
672
673def load_defaultParser():
674 '''
675 It will load the default parser which is xml parser to parse the params and topology file.
676 '''
677 moduleList = main.parserPath.split("/")
678 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
679 try :
680 parsingClass = main.parsingClass
681 parsingModule = __import__(newModule, globals(), locals(), [parsingClass], -1)
682 parsingClass = getattr(parsingModule, parsingClass)
683 main.parser = parsingClass()
684 if hasattr(main.parser,"parseParams") and hasattr(main.parser,"parseTopology") and hasattr(main.parser,"parse") :
685 pass
686 else:
687 main.exit()
688
689 except ImportError:
690 print sys.exc_info()[1]
691
692
693def load_logger() :
694 '''
695 It facilitates the loading customised parser for topology and params file.
696 It loads parser mentioned in tab named parser of teston.cfg file.
697 It also loads default xmlparser if no parser have specified in teston.cfg file.
698
699 '''
700 confighash = main.configDict
701 if 'file' in confighash['config']['logger'] and 'class' in confighash['config']['logger']:
702 if confighash['config']['logger']['file'] != None or confighash['config']['logger']['class']!= None :
703 if os.path.exists(confighash['config']['logger']['file']) :
704 module = re.sub(r".py\s*$","",confighash['config']['logger']['file'])
705 moduleList = module.split("/")
706 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
707 try :
708 loggerClass = confighash['config']['logger']['class']
709 loggerModule = __import__(newModule, globals(), locals(), [loggerClass], -1)
710 loggerClass = getattr(loggerModule, loggerClass)
711 main.logger = loggerClass()
712 #hashobj = main.parser.parseParams(main.classPath)
713
714 except ImportError:
715 print sys.exc_info()[1]
716 else :
717 print "No Such File Exists !!"+confighash['config']['logger']['file']+ "Using default logger"
718 load_defaultlogger()
719 elif confighash['config']['parser']['file'] == None or confighash['config']['parser']['class'] == None :
720 load_defaultlogger()
721 else:
722 load_defaultlogger()
723
724def load_defaultlogger():
725 '''
726 It will load the default parser which is xml parser to parse the params and topology file.
727 '''
728 moduleList = main.loggerPath.split("/")
729 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
730 try :
731 loggerClass = main.loggerClass
732 loggerModule = __import__(newModule, globals(), locals(), [loggerClass], -1)
733 loggerClass = getattr(loggerModule, loggerClass)
734 main.logger = loggerClass()
735
736 except ImportError:
737 print sys.exc_info()[1]
738 main.exit()
739
740def load_defaultlogger():
741 '''
742 It will load the default parser which is xml parser to parse the params and topology file.
743 '''
744 moduleList = main.loggerPath.split("/")
745 newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
746 try :
747 loggerClass = main.loggerClass
748 loggerModule = __import__(newModule, globals(), locals(), [loggerClass], -1)
749 loggerClass = getattr(loggerModule, loggerClass)
750 main.logger = loggerClass()
751
752 except ImportError:
753 print sys.exc_info()[1]
754 main.exit()
755
756
757
758
759def _echo(self):
760 print "THIS IS ECHO"