简介:Data Driven Testing,数据驱动,简单来说就是测试数据的参数化
安装
pip3 install ddt
基本使用
@data(a,b)
那么a和b各运行一次用例
@data([a,d],[c,d])
如果没有@unpack,那么[a,b]当成一个参数传入用例运行
如果有@unpack,那么[a,b]被分解开,按照用例中的两个参数传递
案例:
import unittest
from ddt import ddt,data,unpack
@ddt
class MyTesting(unittest.TestCase):
def setUp(self):
print('this is the setUp')
@data([1,2,3])
def test_1(self,value):
print(value)
@data([3,2,1],[5,3,2],[10,4,6])
@unpack
def test_minus(self,a,b,expected):
actual = int(a) - int(b)
expected = int(expected)
self.assertEqual(actual, expected)
@data([2,3],[4,5])
def test_compare(self,a,b):
self.assertEqual(a,b)
def tearDown(self):
print('this is tearDown')
if __name__ == '__main__':
unittest.main(verbosity=2)
结果分析:
test_1_1__1__2__3_ (__main__.MyTesting) ... this is the setUp
[1, 2, 3]
this is tearDown
ok
test_compare_1__2__3_ (__main__.MyTesting) ... this is the setUp
this is tearDown
ERROR
test_compare_2__4__5_ (__main__.MyTesting) ... this is the setUp
this is tearDown
ERROR
test_minus_1__3__2__1_ (__main__.MyTesting) ... this is the setUp
this is tearDown
ok
test_minus_2__5__3__2_ (__main__.MyTesting) ... this is the setUp
this is tearDown
ok
test_minus_3__10__4__6_ (__main__.MyTesting) ... this is the setUp
this is tearDown
ok
- test_1的测试结果是ok的, 因为 [1,2,3] 作为一个整体传给value,所有value 打印的值是[1,2,3]
- test_minus的测试结果也是ok的,由于在@data(...)下加了@unpack, 代表会把数据分解,得到3组测试数据
- test_compare的测试结果是fail的,由于没有加@unpack, 虽然还是会被理解成2组测试数据,但是[2,3]作为一个整体被传给了a, 因为b就没有值传入了,所以一执行后报了 TypeError: test_compare() missing 1 required positional argument: 'b' 这句错。
网友评论