Home  >  Article  >  Backend Development  >  How to implement Python Unittest ddt data driver

How to implement Python Unittest ddt data driver

王林
王林forward
2023-05-16 21:43:201493browse

1. Data-driven introduction:

  • @ddt.ddt (class decorator, declares that the current class uses the ddt framework)

  • @ ddt.data (function decorator, used to pass data to test cases), supports passing all python data types: numbers (int, long, float, compix), strings, lists, tuples, sets, writing and reading data File function, @data entry parameter plus * to read

  • @ddt.unpack (write to the decorator to unpack the transmitted data packet), generally acts on tuples and tuples List, dictionary (the name and number of parameters need to be consistent with the keys of the dictionary) (not required for arrays and strings)

  • @ddt.file_data (function decorator, can be read directly Take yaml/json file)

2. The difference between data-driven and key-driven:

Data-Driven Tests (DDT) is data-driven testing, which can implement different data Run the same test case. The essence of ddt is actually a decorator, a set of data and a scene.
Keyword driven (core: encapsulate business logic into keyword login, only need to call login.)

3. Hybrid drive mode (keyword driven data driven)

4 , In actual practice of data-driven testing: you need to use the @ddt.ddt decorator on the test class and the @ddt.data decorator on the test case.

(1) Single parameter: guide package - write a parameter (list, number, string) -----Set the @ddt.data decorator to write the parameter name----Method Write the formal parameter *data----call parameter content

(2) Multi-parameter data-driven test (one test parameter contains multiple elements): Guide package-set @ddt decoration Device - set @unpack unpacking - write parameters - formal parameter transfer - call

(3) txt file parameter transfer

(4 ) json file parameter passing

(5) yaml file parameter passing

(6) xlsx file parameter passing

Note: variable parameters are passed in Python: * represents sequential reading List type, ** represents the type of sequential reading object (dictionary), click to read the variable parameter part to learn about the related mechanism

# 1、单一参数的数据驱动
 
# 前置步骤:
# 使用语句import unittest导入测试框架
# 使用语句from ddt import ddt, data导入单一参数的数据驱动需要的包
 
# 示例会执行三次test,参数分别为'666','777','888'
import ddt
import unittest
@ddt.ddt  # 设置@ddt装饰器
class BasicTestCase(unittest.TestCase):
    @ddt.data('666', '777', '888')  # 设置@data装饰器,并将传入参数写进括号
    def test(self, *data):  # test入口设置形参
        print('数据驱动的number:', data)
# 程序会执行三次测试,入口参数分别为666、777、888
 
 
        
# 2、多参数的数据驱动
# 在单一参数包的基础上,额外导入一个unpack的包,from ddt import ddt, data, unpack
# 步骤:导包——设置@ddt装饰器——设置@unpack解包——写入参数——形参传递——调用
import ddt
import unittest
 
Testdata = [
    {"username": "admin", "password": "123456", "excepted": {'code': '200', 'msg': '登录成功'}},
    {"username": None, "password": "1234567", "excepted": {'code': '400', 'msg': '用户名或密码不能为空'}},
    {"username": "admin", "password": None, "excepted": {'code': '400', 'msg': '用户名或密码不能为空'}},
    {"username": "admin", "password": "123456789", "excepted": {'code': '404', 'msg': '用户名或密码错误'}},
]
 
@ddt.ddt
class BasicTestCase(unittest.TestCase):
    
    #方式一:直接将列表放到data
    @ddt.data(['张三', '18'], ['李四', '19'])  # 设置@data装饰器,并将同一组参数写进中括号[]
    @ddt.unpack  # 设置@unpack装饰器顺序解包,缺少解包则相当于name = ['张三', '18']
    def test(self, name, age):
        print('姓名:', name, '年龄:', age)
# 程序会执行两次测试,入口参数分别为['张三', '18'],['李四', '19']
 
        
    #方式二:写一个列表后,使用*访问列表到data
    @ddt.data(*Testdata)
    @ddt.unpack # 设置@unpack装饰器顺序解包
    def test_DataDriver(self, *Data):
        #print('DDT数据驱动实战演示:', Data)
        res = login.login_check(Testdata['username'], Testdata['password'])
        self.assertEqual(res, Testdata['excepted'])
        
 
#3、 txt文件接收参数
# 新建num文件,txt格式
    # (1)单一参数按行存储777,888,999
    # (2)多参数txt文件
        # dict文件内容(参数列表)(按行存储):
        # 张三,18
        # 李四,19
# 编辑阅读数据文件的函数
# 记住读取文件一定要设置编码方式,否则读取的汉字可能出现乱码!!!!!!
import ddt
import unittest
def read_num():
    lis = []    # 以列表形式存储数据,以便传入@data区域
    with open('num.txt', 'r', encoding='utf-8') as file:    # 以只读'r',编码方式为'utf-8'的方式,打开文件'num',并命名为file
        for line in file.readlines():   # 循环按行读取文件的每一行
            lis.append(line.strip('\n'))  #单一参数,每读完一行将此行数据加入列表元素,记得元素要删除'/n'换行符!!!
            #lis.append(line.strip('\n').split(','))  # 多参驱动,删除换行符,根据,分割后,列表为['张三,18', '李四,19', '王五,20']
        return lis    # 将列表返回,作为@data接收的内容
@ddt.ddt
class BasicTestCase(unittest.TestCase):
    @ddt.data(*read_num())  # 入口参数设定为read_num(),因为返回值是列表,所以加*表示逐个读取列表元素
    #txt表格有多少个值,设置多少个接收参数的形参
    def test(self, name,age):
        print('数据驱动的number:', name,age)
 
 
# 4、JSON文件传参:数据分离
# 多参数——json文件
# 步骤和单一参数类似,仅需加入@unpack装饰器以及多参数传参入口
# dict文件内容(参数列表)(非规范json文件格式):
# 单一参数:["666","777","888"]
# 多个参数:[["张三", "18"], ["李四", "19"], ["王五", "20"]]
# 注意json文件格式字符串用双引号
import ddt
import unittest
import json
def read_dict_json():
    return json.load(open('dict.json', 'r', encoding='utf-8'))  # 使用json包读取json文件,并作为返回值返回
@ddt.ddt
class BasicTestCase(unittest.TestCase):
    @ddt.data(*read_dict_json())
    @ddt.unpack     # 使用@unpack装饰器解包
    def test(self, name, age):    # 因为是非规范json格式,所以形参名无限制,下文会解释规范json格式
        print('姓名:', name, '年龄:', age)
    
 
# 4、JSON文件传参:数据分离
# json文件三种形式:
# (1)单一参数:["666","777","888"]
# (2)多个参数:[["张三", "18"], ["李四", "19"], ["王五", "20"]]
# (3)JSON格式读取,每一组参数以对象形式存储:
# [
#   {"name":"张三", "age":"18"},
#   {"name":"李四", "age":"19"},
#   {"name":"王五", "age":"20"}
# ]
# 单一参数时无需使用unpack,多参数需要使用unpack解包,注意json文件格式字符串用双引号
import ddt
import unittest
import json
 
#方式1:非正式json格式使用
def read_dict_json():
    return json.load(open('dict.json', 'r', encoding='utf-8'))  # 使用json包读取json文件,并作为返回值返回
 
#方式2:JSON格式读取,提取已读完后的json文件(字典形式),通过遍历获取元素,并返回
def read_dict_json():
    lis = []
    dic = json.load(open('dict.json', 'r', encoding='utf-8'))
    # 此处加上遍历获取语句,下文yaml格式有实例,方法一样
    for item in dic:
        lis.append(item)
    return lis
 
@ddt.ddt
class BasicTestCase(unittest.TestCase):
    @ddt.data(*read_dict_json())
    @ddt.unpack     # 使用@unpack装饰器解包
    def test(self, name, age):    # 因为是非规范json格式,所以形参名无限制,下文会解释规范json格式
        print('姓名:', name, '年龄:', age)
 
 
#5、多参数yaml
# 以对象形式存储yml数据(字典)
# yaml格式文件内容
# -
#   name: 张三
#   age: 18
# -
#   name: 李四
#   age: 19
# -
#   name: 王五
#   age: 20
# '-'号之后一定要打空格!!!
# ':'号之后一定要打空格!!!
 
# 入口参数与数据参数key命名统一即可导入
import ddt
import unittest
import yaml
@ddt.ddt
class BasicTestCase(unittest.TestCase):
 
    #方式1:形参入口和数据参数key命名统一
    @ddt.file_data('./data/dict.yml')
    def test(self, name, age):  # 设置入口参数名字与数据参数命名相同即可
        print('姓名是:', name, '年龄为:', age)
 
    #方式2:入口参数与数据参数命名不统一
    @ddt.file_data('./data/dict.yml')
    def test(self, **cdata):  # Python中可变参数传递的知识:**按对象顺序执行
        print('姓名是:', cdata['name'], '年龄为:', cdata['age'])    # 通过对象访问语法即可调用

Examples are as follows:

Method 1: The test data is written directly in list form, Use ddt.data(*Data) to pass the value

##2.12.2  DDT在自动化测试中的应用(传列表)
 
import ddt
import unittest
 
# 给4条测试数据
    Testdata = [
        {"username": "admin", "password": "123456", "excepted": {'code': '200', 'msg': '登录成功'}},
        {"username": None, "password": "1234567", "excepted": {'code': '400', 'msg': '用户名或密码不能为空'}},
        {"username": "admin", "password": None, "excepted": {'code': '400', 'msg': '用户名或密码不能为空'}},
        {"username": "admin", "password": "123456789", "excepted": {'code': '404', 'msg': '用户名或密码错误'}},
    ]
@ddt.ddt
class TestModules(unittest.TestCase):
    def setUp(self):
        print('testcase beaning....')
    def tearDown(self):
        print('testcase ending.....')
        
    @ddt.data(*Data)
    def test_DataDriver(self,Data):
        #print('DDT数据驱动实战演示:',Testdata)
        res = login.login_check(Testdata['username'], Testdata['password'])
        self.assertEqual(res, Testdata['excepted'])
if __name__ == '__main__':
    unittest.main()

Method 2: Write data to the method form readData(), use ddt.data(*readData()) to pass the value

import ddt
import unittest
 
# 给4条测试数据
def readData():
    Testdata = [
        {"username": "admin", "password": "123456", "excepted": {'code': '200', 'msg': '登录成功'}},
        {"username": None, "password": "1234567", "excepted": {'code': '400', 'msg': '用户名或密码不能为空'}},
        {"username": "admin", "password": None, "excepted": {'code': '400', 'msg': '用户名或密码不能为空'}},
        {"username": "admin", "password": "123456789", "excepted": {'code': '404', 'msg': '用户名或密码错误'}},
    ]
    return TestData
 
@ddt.ddt
class TestModules(unittest.TestCase):
    def setUp(self):
        print('testcase beaning....')
    def tearDown(self):
        print('testcase ending.....')
    @ddt.data(*readData())
    def test_DataDriver(self,Data):
        #print('DDT数据驱动实战演示:',Testdata)
        res = login.login_check(Testdata['username'], Testdata['password'])
        self.assertEqual(res, Testdata['excepted'])
if __name__ == '__main__':
    unittest.main()

The above is the detailed content of How to implement Python Unittest ddt data driver. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete