UnitTest中使用ddt时自定义测试用例名称

UnitTest中使用ddt时自定义测试用例名称

由于unittest中使用ddt作数据驱动测试时,测试用例名称会自动生成,导致无法识别该用例到底做的什么测试

image-20211117192509261

查看了ddt源码之后,发现有个函数是用来生成测试用例名字的。这个函数叫:mk_test_name

def mk_test_name(name, value, index=0, index_len=5, name_fmt=TestNameFormat.DEFAULT):
    """
    Generate a new name for a test case.

    It will take the original test name and append an ordinal index and a
    string representation of the value, and convert the result into a valid
    python identifier by replacing extraneous characters with ``_``.

    We avoid doing str(value) if dealing with non-trivial values.
    The problem is possible different names with different runs, e.g.
    different order of dictionary keys (see PYTHONHASHSEED) or dealing
    with mock objects.
    Trivial scalar values are passed as is.

    A "trivial" value is a plain scalar, or a tuple or list consisting
    only of trivial values.

    The test name format is controlled by enum ``TestNameFormat`` as well. See
    the enum documentation for further details.
    """

    # Add zeros before index to keep order
    index = "{0:0{1}}".format(index + 1, index_len)
    if name_fmt is TestNameFormat.INDEX_ONLY or not is_trivial(value):
        return "{0}_{1}".format(name, index)
    try:
        value = str(value)
    except UnicodeEncodeError:
        # fallback for python2
        value = value.encode('ascii', 'backslashreplace')
    test_name = "{0}_{1}_{2}".format(name, index, value)
    return re.sub(r'\W|^(?=\d)', '_', test_name)

它是如何来生成测试用例名字的呢?
它接受两个参数:name 和 value.
name:为单元测试中,测试用例的名字。即test_01_login.
value:为测试数据。ddt是处理一组测试数据。而这个value就是这一组数据中的每一个测试数据。
对value的值是有限制的:要么就是单值变量,要么就是元组或者列表并且要求元组和列表中的数据都是单值变量。如(“name”,“port”) 、[“name”,“port”]
如果传进来的测试数据,不符合value的要求,那么测试用例名字为:name_index。
如果传进来的测试数据,符合value的要求,那么测试用例名字为:name_index_value。如果value为列表或者元组,那么将列表/元组的每个数据依次追加在末尾。
我的接口自动化框架中,ddt处理的数据是一列表:列表当中每个数据都为字典。ddt一遍历整个列表,那传给value的值刚好是字典。

def mk_test_name(name, value, index=0, index_len=5, name_fmt=TestNameFormat.DEFAULT):
    """
    Generate a new name for a test case.

    It will take the original test name and append an ordinal index and a
    string representation of the value, and convert the result into a valid
    python identifier by replacing extraneous characters with ``_``.

    We avoid doing str(value) if dealing with non-trivial values.
    The problem is possible different names with different runs, e.g.
    different order of dictionary keys (see PYTHONHASHSEED) or dealing
    with mock objects.
    Trivial scalar values are passed as is.

    A "trivial" value is a plain scalar, or a tuple or list consisting
    only of trivial values.

    The test name format is controlled by enum ``TestNameFormat`` as well. See
    the enum documentation for further details.
    """

    # Add zeros before index to keep order
    index = "{0:0{1}}".format(index + 1, index_len)
    if type(value) is dict: # 判断执行的数据流是否为字典,是则去“case_name”的value
        try:
            value = value['case_name']
        except:
            return "{0}_{1}".format(name, index)
    if not is_trivial(value):
        return "{0}_{1}".format(name, index)
    try:
        value = str(value)
    except UnicodeEncodeError:
        # fallback for python2
        value = value.encode('ascii', 'backslashreplace')
    test_name = "{0}_{1}_{2}".format(name, index, value)
    return re.sub(r'\W|^(?=\d)', '_', test_name)

yaml数据驱动中每个测试用例数据中添加一个case_name字段

login:
  -
    case_name: 正常登录
    url: /auth/oauth/token?randomStr=blockPuzzle&code=&grant_type=password
    data:
      username: admin
      password: JFat0Zdc
    res:
      code: 200
      check: access_token

同时html中用例描述可以这样设置

@ddt
class TestLoginApi(TestBase):
    @data(*get_yaml_data(yaml_path)["login"])
    def test_01_login(self, kwargs):
        """登录接口,获取token接口
        @param kwargs:
        @return:
        """
        self._testMethodDoc = kwargs['case_name']

执行用例结果

image-20211119111012300

HTML报告中结果

image-20211119111045024

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mrlijie00

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值