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