python3 应用 nose_parameterized 实现unittest 参数化
生活随笔
收集整理的這篇文章主要介紹了
python3 应用 nose_parameterized 实现unittest 参数化
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、讀取變量的值,實現unittest 參數化
import nose_parameterized,unittestdef calc(a:int,b:int):return a+b case_data =[[10,20,30],[12,21,33],[15,21,36] ] class MyClass(unittest.TestCase):@nose_parameterized.parameterized.expand(case_data)def test_compare(self,a,b,expect):actual = calc(int(a),int(b))self.assertEqual(actual,expect) if __name__ == '__main__':unittest.main()定義了一個二維數組case_data,用來存值,使用時直接在test方法上方加
@nose_parameterized.parameterized.expand(case_data)最后可以得到以下測試結果,說明測試成功。
同樣,也可以將case_date定義為下面的形式,也可以實現unittest參數化。 case_data =[(10,20,30),(12,21,33),(15,21,36) ]
二、讀取文件的方式,實現unittest 參數化
@nose_parameterized.parameterized.expand(case_date) 這句中的case_data,只要寫個函數,從文件格式讀取的每一行放到一個list里,生成一個二維數組,,將這個二維數組賦給case_data就可以了。
如下所示,調用類DataToParam中的text方法,從?case_data.txt 生成一個二維數組。
@nose_parameterized.parameterized.expand(DataToParam.text('case_data.txt'))下面是讀取txt文件的函數封裝在類DataToParam 里, 要讀取excel的話,可以在DataToParam里再加一個讀取excel的函數,然后把判斷文件單獨拎出來,放一個函數里,這樣可以公用。
class DataToParam(object):@staticmethod
def text(filename,seq=','):
if os.path.isfile(filename):
with open(filename,encoding='utf-8') as f:
res = []
for line in f:
res.append(line.strip().split(seq))
return res
else:
raise Exception('參數化文件不存在!') #主動拋出異常
print(DataToParam.text('case_data.txt'))
?
轉載于:https://www.cnblogs.com/nancyzhu/p/8551389.html
總結
以上是生活随笔為你收集整理的python3 应用 nose_parameterized 实现unittest 参数化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU 2089 不要62
- 下一篇: 不会Python开发的运维终将被淘汰?