python的unittest測试框架的扩展浅谈

非常多时候測试框架须要依据測试数据来自己主动生成測试用例脚本,比方接口測试,通过不同參数构建组合去请求接口,然后验证返回结果。假设这样能通过配置excel数据来驱动測试。而不用去写一大堆的測试用例脚本代码,减轻了维护自己主动化測试脚本的时间和成本,大概有一个思路能够实现以上想法,先写一个通过的unittest測试基类,然后用过python的内置type去生成自己定义的功能模块类,再在生成的自己定义类里以setattr方法来生成每个功能模块类下的用例方法。这样到时收集測试报告的时候,能够比較清晰的分类展示。

例如以下面函数是依据excel生成測试类和类下的測试用例方法,当然假设接入平台里測试,到最后測试完要去销毁之前生成的类和方法

def generateTestCases(log,arglists):

    '''动态生成測试用例类及其方法'''
    class_list=[]
    for args in arglists:
        custom_class = type(args['inter'], (myEwsCase,), {"__doc__":args['cases'][0]['description']})
        for a in args['cases']:
            setattr(custom_class,'test_%s'%a['testcasename'],myEwsCase.getTestFunc(log,a))
        class_list.append(custom_class)

    return class_list

def destroyTestCases(log,custom_class,arglists):
   '''销毁全部自己主动生成用例方法'''
    n=0
    for args in arglists:
        for a in args['cases']:
            delattr(custom_class[n],'test_%s'%a['testcasename'])
        n +=1


原文地址:https://www.cnblogs.com/zsychanpin/p/6882575.html