美文网首页
Robot Framework监听日志二次开发,遇到的坑

Robot Framework监听日志二次开发,遇到的坑

作者: 带肥肉的羊肉串 | 来源:发表于2018-06-06 12:54 被阅读271次

    直接推荐吧,这两篇帖子一篇讲原理,一篇讲应用,仔细看能解决。
    http://www.cnblogs.com/kuihua/p/5400152.html
    https://blog.csdn.net/wyb199026/article/details/78730097
    本篇就分享下使用,以及一个小坑

    背景:
    python CGI + httpd, 自己写了个调用robot api的class,然后运行 robot Framework的testcase

    from robot import run
    from Demo.utils.robotframework.robotframeworkmylistener import MyListener //替换成自己的
    from Demo.utils.log.fatplogger import *

    class RobotRunner:

    def runTestcaseAndInsertToMySQL(self, testLogID, jobTestcaseFolderPath, db):
        """method to run test case and insert log to MySQL
        @param (str) test_log_id
        @param (str) jobTestcaseFolderPath
        @return projectID
        """
        try:
               run(jobTestcaseFolderPath, listener=MyListener(testLogID, db), log=None)
        except:
            mylogger.info('Exception: Run testcase failed!')
    

    from Demo.utils.db.dbinit import *
    from Demo.utils.log.fatplogger import *

    class MyListener(object):
    ROBOT_LISTENER_API_VERSION = 2

    stepCount = 0
    testLogID = None
    db = None
    ms = None
    
    def __init__(self, testLogID, db):
        self.testLogID = testLogID
        self.db = InitMySql()
        t = time.time()
        self.ms = int(round(t))
        mylogger.info('init robot framework listener...')
    
    def start_suite(self, name, args):
        self.stepCount = self.stepCount + 1
        log =  "Starting Suite : " + name + "  " + args['source']
        self.insert_log(self.testLogID, self.stepCount, log)
    
    
    def start_test(self, name, args):
        self.stepCount = self.stepCount + 1
        log = "Starting test : " + name
        self.insert_log(self.testLogID, self.stepCount, log)
    
    def end_test(self, name, args):
        self.stepCount = self.stepCount + 1
        log = "Ending Test:  " + args['longname']
        self.insert_log(self.testLogID, self.stepCount, log)
    
        self.stepCount = self.stepCount + 1
        log = "Test Result is : " + args['status']
        self.insert_log(self.testLogID, self.stepCount, log)
        if('PASS' in log):
            self.tablename = 'testcase_log'
            self.key = 'result_status = 1'
            self.where = {"test_log_id": self.testLogID}
            self.db.update(self.tablename, self.key, self.where)
    
        self.stepCount = self.stepCount + 1
        log = "Test Time is: " + str(args['elapsedtime'])
        self.insert_log(self.testLogID, self.stepCount, log)
    
    def log_message(self, message):
        mylogger.info(self.stepCount)
        self.stepCount = self.stepCount + 1
        log = message['timestamp'] + " :   " + message['level'] + " : " + message['message']
        self.insert_log(self.testLogID, self.stepCount, log)
    
    def insert_log(self, testLogID, stepCount, log):
        self.tablename = 'testcase_log_detail'
        self.key = 'test_log_id,log_step_number,log_info,createTime'
        log = str(log).replace('\'', '\\\'')
        self.keyValue = "('" + str(testLogID) + "','" + str(stepCount) + "', '"+ log  + "', '"+ str(self.ms) + "')"
        self.db.insert(self.tablename, self.key, self.keyValue)
    

    这里MyListener中,我加入了 DB的操作,获取log后直接存到数据库里面

    坑:
    本地运行都可以,一上linux 就废了,各种过不了,最后发现是 存储output.xml的那个文件夹没有权限,chmod 就搞定了

    debug的经历,
    由于要在server 中,python site-packages 里面debug,看看为什么不行,没有什么好办法,只能打log。这里如果哪位大神有好的办法,求介绍

    首先,找到robot 的位置,我的是 /usr/lib/python2.7/site-packages/robot


    image.png

    然后,先在本地debug,看看
    run(jobTestcaseFolderPath, listener=MyListener(testLogID, db), log=None)
    的大体实现。
    直接贴过程:
    step 1:
    /usr/lib/python2.7/site-packages/robot/run.py

    def main(self, datasources, **options):
        settings = RobotSettings(options)
        LOGGER.register_console_logger(**settings.console_output_config)
        LOGGER.info('Settings:\n%s' % unic(settings))
        suite = TestSuiteBuilder(settings['SuiteNames'],
                                 settings['WarnOnSkipped'],
                                 settings['Extension']).build(*datasources)
        suite.configure(**settings.suite_config)
        if settings.pre_run_modifiers:
            suite.visit(ModelModifier(settings.pre_run_modifiers,
                                      settings.run_empty_suite, LOGGER))
        with pyloggingconf.robot_handler_enabled(settings.log_level):
            result = suite.run(settings)            -------------------这一行运行测试用例
            LOGGER.info("Tests execution ended. Statistics:\n%s"
                        % result.suite.stat_message)
            if settings.log or settings.report or settings.xunit:
                writer = ResultWriter(settings.output if settings.log
                                      else result)
                writer.write_results(settings.get_rebot_settings())
        return result.return_code
    

    step 2:
    /usr/lib/python2.7/site-packages/robot/running/model.py

    def run(self, settings=None, **options):
        from .namespace import IMPORTER
        from .signalhandler import STOP_SIGNAL_MONITOR
        from .runner import Runner
    
        with LOGGER:
            if not settings:
                settings = RobotSettings(options)
                LOGGER.register_console_logger(**settings.console_output_config)
            with pyloggingconf.robot_handler_enabled(settings.log_level):
                with STOP_SIGNAL_MONITOR:
                    IMPORTER.reset()
                    output = Output(settings)     ----------------------进入这一步
                    runner = Runner(output, settings)
                    self.visit(runner)
                output.close(runner.result)
        return runner.result
    

    step 3:
    /usr/lib/python2.7/site-packages/robot/output/output.py

    def __init__(self, settings):
        AbstractLogger.__init__(self)
        self._xmllogger = XmlLogger(settings.output, settings.log_level)   ----------------------进入这一步
        self.listeners = Listeners(settings.listeners, settings.log_level)
        self.library_listeners = LibraryListeners(settings.log_level)
        self._register_loggers(DebugFile(settings.debug_file))
        self._settings = settings
    

    step 3:
    /usr/lib/python2.7/site-packages/robot/output/xmlogger.py

    def __init__(self, path, log_level='TRACE', generator='Robot'):
        self._log_message_is_logged = IsLogged(log_level)
        self._error_message_is_logged = IsLogged('WARN')
        self._writer = self._get_writer(path, generator)
        self._errors = []
    

    打log
    def init(self, path, log_level='TRACE', generator='Robot'):
    mylogger.info('Debug xmllogger 1')
    mylogger.info(path)
    mylogger.info('Debug xmllogger 2')
    mylogger.info(log_level)
    self._log_message_is_logged = IsLogged(log_level)
    mylogger.info('Debug xmllogger 3')
    self._error_message_is_logged = IsLogged('WARN')
    mylogger.info('Debug xmllogger 4')
    mylogger.info(generator)
    self._writer = self._get_writer(path, generator)
    mylogger.info('Debug xmllogger 5')
    self._errors = []

    image.png

    呵呵哒,因为之前,在server 写了个 text 去测试runTestcaseAndInsertToMySQL()这个方法,通过了,

    image.png

    所有我猜是output 或者是 report 或者是其他有个文件夹需要权限。
    到这里,就在server log 中,找到output 创建在webapps下面了,加个权限,server就过了。

    总结:

    1. 之前从来没看过 robot Framework的源码,这次对原理有了一点的认识
    2. output/report 的存放路径,默认是 python test.py 程序执行的地址
    3. 初学python, 也不知道怎么在server 上debug python site-packages,楼主是一路sudo vim 加log,才勉强debug,希望有大神可以介绍下,下次遇到问题,可以提高效率,快速定位问题。

    相关文章

      网友评论

          本文标题:Robot Framework监听日志二次开发,遇到的坑

          本文链接:https://www.haomeiwen.com/subject/glzvsftx.html