ddt.py源码中的mk_test_name函数是用来生成测试用例名字的python
参数:name、value、indexapi
name为单元测试中,测试用例的名字。即test_apiapp
value为测试数据。ddt是处理一组测试数据。而这个value就是这一组数据中的每个测试数据ide
对value的值是有限制的:要么就是单值变量,要么就是元组或者列表而且要求元组和列表中的数据都是单值变量。如("name","port") 、["name","port"]函数
index:用例数量单元测试
ddt源码中针对index设置了最大值index_len,默认为5,若是用例数大于5,须要修改该值测试
mk_test_name函数源码:spa
def mk_test_name(name, value, index=0): """ 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. """ # Add zeros before index to keep order index = "{0:0{1}}".format(index + 1, index_len) 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)
修改后():scala
def mk_test_name(name, value, index=0): """ 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. """ # Add zeros before index to keep order index = "{0:0{1}}".format(index + 1, index_len) if not is_trivial(value): # 若是不符合value的要求,则直接返回用例名称_下标做为最终测试用例名字。 return "{0}_{1}".format(name, index) # 若是数据是list,则获取字典当中第一个数据做为测试用例名称 if type(value) is list: try: value = value[0] except: 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)
修改后执行结果:code