Table of Contents
1. Data-driven introduction:
2. The difference between data-driven and key-driven:
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.
Home Backend Development Python Tutorial How to implement Python Unittest ddt data driver

How to implement Python Unittest ddt data driver

May 16, 2023 pm 09:43 PM
python unittest ddt

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'])    # 通过对象访问语法即可调用
Copy after login

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()
Copy after login

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()
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles