search
HomeBackend DevelopmentPython TutorialHow to implement Python Unittest ddt data driver

How to implement Python Unittest ddt data driver

May 16, 2023 pm 09:43 PM
pythonunittestddt

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:亿速云. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools