# 1. 首先安装插件 pip install ddt
"""
D:\Python\Scripts>pip install ddt
Collecting ddt
Downloading ddt-1.4.4-py2.py3-none-any.whl (6.3 kB)
Installing collected packages: ddt
Successfully installed ddt-1.4.4
"""
# 2. 导包
import unittest
from ddt import ddt, data, unpack, file_data
# ddt其实通过装饰器的方式来调用,它配合unittest测试框架去实现数据驱动
# unittest编写规范类方法必须以test开头,必须继承unittest.TestCase
# 函数
def read_file():
a = 1, 2, 3
return a
@ddt # @ddt是声明类
class Test(unittest.TestCase):
@data(1, 2, 3)
def test_01(self, value):
"""
该方法执行三遍,传入参数几个就执行几遍
"""
print(value)
@data((1, 2, 3), [1, 2, 3])
def test_02(self, value):
"""
该方法执行二遍,以列表和元组形式去传参看成一个整体
输出结果为列表或元组形式
"""
print(value)
@data((1, 2, 3), [1, 2, 3])
@unpack
def test_03(self, one, two, three):
"""
该方法执行二遍,以列表和元组形式去传参看成一个整体
unpack方法解包,注意传参的个数要保持一致
返回就是列表或者元组里面具体的值
"""
print(one, two, three)
# """
# @data({1,2,3})
# @unpack
# def test_04(self, one, two, three):
#
# # 该方法将会报错,因为unpack解包有限制要求:没有顺序的解不了包
#
# print(one, two, three)
# """
#
@data({'one': 1, 'two': 2, 'three': 3})
@unpack
def test_05(self, one, two, three):
"""
字典也可以解包,但是注意key值要一致
"""
print(one, two, three)
@data(read_file())
def test_06(self, value):
"""
该方法论证函数/方法也可以放到data里面进行传参
可以配合excel处理获取表格内所需数值
"""
print(value)
@file_data('test.json')
def test_07(self, one, two, three):
"""
{
"test01": {"one": "1","two": "2","three": "3"},
"test02": {"one": "1","two": "2","three": "3"},
"test03": {"one": "1","two": "2","three": "3"}
}
该方法是利用file_data()读取json格式文件,执行3次分别是01、02、03
此处json中类型为字典注意字典在ddt中的特点
"""
print(one, two, three)
@file_data('test.yaml')
def test_08(self, value):
"""
json:
- rigid
- better for data interchange
yaml:
- slim and flexible
- better for configuration
读取yaml格式,该方法执行2遍以列表的形式返回数据结果
"""
print(value)