当前位置: 首页> 技术文章> 自动化测试之 ddt 数据驱动

自动化测试之 ddt 数据驱动

一、安装 ddt

  • pip install ddt

、ddt 模块组成

  • ddt.ddt:装饰类,也就是继承 TestCase 的类。

  • ddt.data:装饰测试方法,参数是一系列的值

  • ddt.file_data:装饰测试方法,参数是文件名。文件可以是 json 或者 yaml 类型。

    • 注意:如果文件是以 “.yml”或者".yaml" 结尾,ddt 会作为 yaml 类型处理,其他文件都会作为 json 文件处理。  

    • 如果文件是列表,列表的值会作为测试用例参数,同时,会作为测试用例方法名后缀显示。  

    • 如果文件是字典,字典的 key 会作为测试用例方法的后缀显示,字典的 value 会作为测试用例参数。  

  • ddt.unpack:用来拆解 data 的数据。传递的是复杂的数据结构时使用,比如使用列表或者元组,添加 unpack 后,ddt 会自动把元组或者列表对应到多个参数上

三、示例

  • 使用 data 传参数给测试用例

    • 如下示例,可以看出 data 分别传参数 2 和 4 给测试用例,然后测试用例执行了两遍

from ddt import ddt, data
import unittest

@ddt
class MyTestDdt(unittest.TestCase):
    def setUp(self):        
        print('start')

    @data(2, 4)  # 使用 data 传参数给测试用例
    def test_one(self,value):    
        print('the @data number is {}'.format(value))  
          
    def tearDown(self):    
        print('end')
        
if __name__ == '__main__':
    unittest.main()
    
# 结果如下:

start
the @data number is :2end
start
the @data number is :4end
  • 使用 unpack 分解 list 或者 tuple

    • 可以看出 data 分别传元组参数(1,2)和(4,5)给测试用例,然后测试用例执行了两遍  

from ddt import ddt, data, unpack
import unittest

@ddt
class MyTestDdt(unittest.TestCase):
    def setUp(self):    
        print('start')

    @data((1, 2), (4, 5))  # 元组
    @unpack  # 二次分解元组
    def test_one(self, value1, value2):    
        print('the @data number is {} and {}'.format(value1, value2))    
        
    def tearDown(self):    
        print('end')
        
if __name__ == '__main__':
    unittest.main()
    
# 结果如下

start
the @data number is 1 and 2end
start
the @data number is 4 and 5end
  •  用 unpack 分解字典

from ddt import ddt, data, unpack
import unittest

@ddt
class MyTestDdt(unittest.TestCase):
    def setUp(self):    
        print('start')

    @data({'value1': 1, 'value2': 2}, {'value1': 3, 'value2': 4})  # 字典    
    @unpack    
    def test_one(self, value1, value2):    
        print('the @data number is {} and {}'.format(value1, value2))    
    
    def tearDown(self):    
        print('end')
        
if __name__ == '__main__':
    unittest.main()
    
# 结果如下

start
the @data number is 1 and 2end
start
the @data number is 3 and 4end


上一篇: html常用头部标签

下一篇: 软件测试之手工测试人员如何转测试开发?

QQ技术交流群

多测师官方学习交流
556733550

加入群聊