python之数据驱动ddt

下载ddt并安装

Pip install ddt

或者官网下载安装

http://ddt.readthedocs.io/en/latest/

https://github.com/txels/ddt

DDT的使用

DDT包含类的装饰器ddt和两个方法装饰器data(直接输入测试数据),file_data(可以从json或者yaml中获取测试数据)

只有yaml和yml结尾的文件以yaml形式上传,其他情况下默认为json

通常情况下,data中的数据按照一个参数传递给测试用例,如果data中含有多个数据,以元组,列表,字典等数据,需要自行在脚本中对数据进行分解或者使用unpack分解数据

@data(a,b)

那么a和b各运行一次用例

@data([a,d],[c,d])

如果没有unpack,那么[a,b]当成一个参数传入用例运行

如果有unpack,那么[a,b]被分解开,按照用例中的两个参数传递

@file_data(filename)

对于json的文件,每一个json元素按照一个用例运行,可以依照python分解元组,列表或者字典的方式分解传入

import unittest
from ddt import ddt,data,file_data,unpack

@ddt
class demotest(unittest.TestCase):
def setup(self):
print "this is the setup"

@data(2,3)
def testb(self,value):
print value
print "this is test b"

@data([2,3],[4,5])
def testa(self,value):
print value
print "this is test a"

@data([2, 3], [4, 5])
@unpack
def testc(self, first,second):
print first
print second
print "this is test c"

@file_data('d:/data_dic.json')
def test_dic(self,value):
print value
print 'this is dic'

@file_data('d:/data.yml')
def test_yml(self, value):
print value
print 'this is yml'

def teardown(self):
print "this is the down"

if __name__ == '__main__':
unittest.main()
#suite=unittest.TestLoader.getTestCaseNames(demotest)
#suite = unittest.TestLoader().loadTestsFromTestCase(demotest)
#unittest.TextTestRunner(verbosity=2).run(suite)

posted @   hellowcf  阅读(11763)  评论(1编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示