python3-接口自动化用例编号排序和名称展示问题处理,修改paramunittest.py

log:
最近在处理接口自动化的时候发现excel用例执行顺序问题,经过一番排查对paramunittest.py文件进行了修改
   1.实现用例按excel排的顺序执行
   2.实现用例报告用例编号排序


paramunittest是unittest实现参数化的一个专门的模块,可以传入多组参数,自动生成多个用例
用ddt可以解决多组数据传入,自动生成多个测试用例。本篇介绍一下参数化的框架paramunittest,从excel获取用例名称以及用例序号

testcase_xls获取的excel用例数据
@paramunittest.parametrized(*testcase_xls)

paramunittest.py源码调整

import copy
import unittest
import collections
import importlib
from unittest.util import strclass

__all__ = [
    'parametrized',
    'ParametrizedTestCase',
]

def _process_parameters(parameters_seq):
    processed_parameters_seq = []
    for parameters in parameters_seq:
        if isinstance(parameters, collections.Mapping):
            processed_parameters_seq.append((tuple(),
                                             dict(parameters)))
        elif (len(parameters) == 2
              and isinstance(parameters[0], collections.Sequence)
              and isinstance(parameters[1], collections.Mapping)):
            processed_parameters_seq.append((tuple(parameters[0]),
                                             dict(parameters[1])))
        else:
            processed_parameters_seq.append((tuple(parameters),
                                             dict()))
    return processed_parameters_seq

# 给用例编号
def _build_name(name, index):
    if index < 9:
        index = '00' + str(index)
    elif index >=9 and index <100:
        index = '0' +str(index)
    return '%s_%s' % (name, index)
# 新增获取序号
def num(index):
    if index < 9:
        index = '00' + str(index)
    elif index >=9 and index <100:
        index = '0' +str(index)
    return '%s' % (index)


class ParametrizedTestCase(unittest.TestCase):
    def setParameters(self, *args, **kwargs):
        raise NotImplementedError(
            ('setParameters must be implemented '
             'because it receives the parameters.'))

    def getParameters(self):
        """
        Return the parameters with which this test case was instantiated.
        """
        raise NotImplementedError(
            'getParameters should have been patched by parametrized.')

    def getFullParametersSequence(self):
        raise NotImplementedError(
            'getFullParametersSequence should have been patched by parametrized.')

    def getTestCaseIndex(self):
        """
        Return the index of the current test case according to the list of
        parametes passed to parametrized.
        """
        raise NotImplementedError(
            'getTestCaseIndex should have been patched by parametrized.')

    def getFullParametersSequence(self):
        """
        Return the full normalized list of parameters passed to parametrized.
        """
        raise NotImplementedError(
            'getFullParametersSequence should have been patched by parametrized.')

    def __str__(self):
        return "%s[%d](%s) (%s)" % (self._testMethodName,
                                    self.getTestCaseIndex(),
                                    self.getParameters(),
                                    strclass(self.__class__))

    def __repr__(self):
        return "<%s[%d](%s) testMethod=%s>" % (strclass(self.__class__),
                                               self.getTestCaseIndex(),
                                               self.getParameters(),
                                               self._testMethodName)


def parametrized(*parameters_seq):
    parameters_seq = _process_parameters(parameters_seq)
    # print(parameters_seq)
    def magic_module_set_test_case(cls):
        if not hasattr(cls, 'setParameters'):
            raise TypeError('%s does not have a setParameters method.' % (
                cls.__name__, ))
        module = importlib.import_module(cls.__module__)
        for index, parameters in enumerate(parameters_seq):
            # print(parameters)
            # parameters[0][1]获取用例的name
            name_index = _build_name(parameters[0][1], int(parameters[0][0]))
            name = str(num(int(parameters[0][0])))+name_index
            # print(name)
            def closing_over(parameters=parameters, index=index):
                def setUp(self):
                    self.setParameters(*parameters[0], **parameters[1])
                    cls.setUp(self)
                def getParameters(self):
                    """
                    Return the parameters with which this test case was instantiated.
                    """
                    return parameters
                def getTestCaseIndex(self):
                    """
                    Return the index of the current test case according to the list of
                    parametes passed to parametrized.
                    """
                    return index
                def getFullParametersSequence(self):
                    """
                    Return the full normalized list of parameters passed to parametrized.
                    """
                    return copy.copy(parameters_seq)
                return setUp, getParameters, getTestCaseIndex, getFullParametersSequence
            (set_up, get_parameters,
             get_test_case_index,
             get_full_parameters_sequence) = closing_over()
            new_class = type(name, (cls, ),
                             {'setUp': set_up,
                              'getParameters': get_parameters,
                              'getTestCaseIndex': get_test_case_index,
                              'getFullParametersSequence': get_full_parameters_sequence})
            print(name,"=============")
            setattr(module, name, new_class)
        return None # this is explicit!
    return magic_module_set_test_case

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值