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