關於ddt模塊的一些心得,主要是看官網的例子,加上一點自己的理解,官網地址:http://ddt.readthedocs.io/en/latest/example.html
ddt(data driven tests)可以讓你給一個測試用例傳入不同的參數,每個運行一遍,就像是運行了多個測試用例一樣。
ddt模塊包含了一個類的裝飾器ddt和兩個方法的裝飾器:
data:包含多個你想要傳給測試用例的參數;
file_data:會從json或yaml中加載數據;
通常data中包含的每一個值都會作為一個單獨的參數傳給測試方法,如果這些值是用元組或者列表傳進來的,可以用unpack方法將其自動分解成多個參數。
ddt模塊常用的就是這些方法,下面給一些例子和解釋。例子里面是和unittest模塊一起使用的,后續也會寫一些unittest模塊的介紹。
下面例子里所有的方法都是包含在class FooTestCase里的。
import unittest from ddt import ddt, data,file_data,unpack @ddt class FooTestCase(unittest.TestCase): @data(1, 2) def test_show_value(self, value): print('value is %s' % value) print('case is over.\n')
運行結果:
value is 1 case is over. value is 2 case is over.
###@data(1,2)里面的參數被單獨的傳給test_show_value()方法,使其運行兩次。
使用unpack方法將列表/元組分解的例子:
@data((1, 2), (3, 4)) @unpack def test_show_value(self, value1,value2): print('value is %s and %s' % (value1,value2)) print('case is over.\n')
運行結果:
value is 1 and 2 case is over. value is 3 and 4 case is over.
###@data((1, 2), (3, 4))中傳入的元組(1,2)和(3,4)被unpack方法分解,可以在函數中直接按照兩個變量傳入。列表也是一樣的。
使用unpack將字典分解的例子:
@unpack @data({'first':1,'second':2}, {'first':3,'second':4}) def test_show_value(self, second, first): print ('value is %s and %s'%(first,second)) print('case is over.\n')
運行結果:
value is 1 and 2 case is over. value is 3 and 4 case is over.
###@data({'first':1,'second':2},{'first':3,'second':4})傳入的字典被unpack分解成了多個獨立的key-value參數;test_show_value()方法里面使用的
###參數名字必須和字典的key值一致,否則會報unexpected keyword argument異常。
ddt模塊常用的就是這幾個方法,更多的API細節可以到鏈接的網頁查看。