ddt 是第三方模块,需安装, pip install ddt
DDT包含类的装饰器ddt和两个方法装饰器data(直接输入测试数据)
通常情况下,data中的数据按照一个参数传递给测试用例,如果data中含有多个数据,以元组,列表,字典等数据,需要自行在脚本中对数据进行分解或者使用unpack分解数据。
@data(a,b)
那么a和b各运行一次用例
@data([a,d],[c,d])
如果没有@unpack,那么[a,b]当成一个参数传入用例运行
如果有@unpack,那么[a,b]被分解开,按照用例中的两个参数传递
具体看下面的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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 ) |
结果分析:
1. test_1的测试结果是ok的, 因为 [1,2,3] 作为一个整体传给value,所有value 打印的值是[1,2,3]
1
2
3
|
test_1_1__1__2__3_ (__main__.MyTesting) ... ok test_compare_1__2__3_ (__main__.MyTesting) ... ERROR [ 1 , 2 , 3 ] |
2. test_minus的测试结果也是ok的,由于在@data(...)下加了@unpack, 代表会把数据分解,得到3组测试数据,分别为:
1
2
3
4
5
6
|
1. [ 3 , 2 , 1 ] 2. [ 5 , 3 , 2 ] 3. [ 10 , 4 , 6 ] test_minus_1__3__2__1_ (__main__.MyTesting) ... ok test_minus_2__5__3__2_ (__main__.MyTesting) ... ok test_minus_3__10__4__6_ (__main__.MyTesting) ... ok |
3. test_compare的测试结果是fail的,由于没有加@unpack, 虽然还是会被理解成2组测试数据,但是[2,3]作为一个整体被传给了a, 因为b就没有值传入了,所以一执行后报了 TypeError: test_compare() missing 1 required positional argument: 'b' 这句错。
1
2
|
test_compare_1__2__3_ (__main__.MyTesting) ... ERROR test_compare_2__4__5_ (__main__.MyTesting) ... ERROR |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
this is the setUp ERROR: test_compare_1__2__3_ (__main__.MyTesting) this is tearDown - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Traceback (most recent call last): return func( self , * args, * * kwargs) TypeError: test_compare() missing 1 required positional argument: 'b' = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ERROR: test_compare_2__4__5_ (__main__.MyTesting) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Traceback (most recent call last): File "D:\python\lib\site-packages\ddt.py" , line 139 , in wrapper return func( self , * args, * * kwargs) TypeError: test_compare() missing 1 required positional argument: 'b' |
以上就是ddt 的学习总结,ddt 还有file_data(可以从json或者yaml中获取测试数据)的驱动方式,下篇继续啦。
原文链接:https://www.cnblogs.com/nancyzhu/p/8563884.html