Auty自动化测试框架第三篇——添加异常处理与日志收集

[本文出自天外归云的博客园]

本次对框架进行完善,增加了日志收集功能和修饰运行功能,完善后的lib目录如下:

在Auty的log文件夹中会存放一些脚本运行时生成的日志。在运行脚本时,对脚本的异常要有捕捉,并把捕捉到的信息打到日志中去。在lib文件夹中添加write_log.py文件,内容如下:

# -*- coding: utf-8 -*-
import os
import time
 
def write_log(log):
    filePath = os.path.abspath(os.path.dirname(__file__))
    logFilePath = os.path.join(os.path.dirname(filePath),'log','log.txt')
    print logFilePath
    execTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    open(logFilePath,'a').write(execTime+' '+log+'\n')

对于执行的脚本中的方法,添加异常处理与日志收集功能。这里用到装饰器,在lib文件夹中添加exe_deco.py文件:

# -*- coding: utf-8 -*-
import traceback
from .write_log import write_log

def exe_deco(func):
    def _deco(*args, **kwargs):
        try:
            ret = func(*args, **kwargs)
        except Exception, e:
            log = 'Exception in '+func.__name__+' method: '+str(e)
            write_log(log)
        else:
            write_log('No exception in %s method.' % func.__name__)
        finally:
            return ret
    return _deco

对应的要修改之前写的execute_selection.py文件,以便对执行的脚本应用新添加的功能(异常处理与日志收集):

# -*- coding: utf-8 -*-
from .read_selection import read_selection
import os
from .exe_deco import exe_deco
from .write_log import write_log

def execute_selection():
    selection = read_selection()
    for scriptPath in selection:
        execute_script(scriptPath)

@exe_deco
def execute_script(scriptPath):
    write_log('execute_script: '+scriptPath)
    os.system('python '+scriptPath)

至此,Auty框架的异常处理与日志收集功能也已经初具模型。运行框架根目录下的start.py文件就可以看到log文件夹中生成了日志,记录了对应脚本运行时的状态。在Auty的logs文件中可以查看生产的日志文件,内容格式如下:

 

 
 
 
 
posted @ 2016-09-29 15:13  天外归云  阅读(2061)  评论(10编辑  收藏  举报