至于什么是ddt这个可以参考我之前写的博客内容,使用ddt框架的时候,有个问题困扰我很久了,一直没得到解决(也有很大小伙伴问过我,没解决抱歉了!) 这个问题就是:如何使用ddt框架时,生成的html报告里面注释能对每个用例传入不同的说明?默认是固定写死的内容。 最近刚好看到关于python的docstring【python笔记30-docstring注释添加变量】(https://www.cnblogs.com/yoyoketang/p/9719147.html)相关知识,ddt源码也读了几次,也思考了很多办法去给docstring传入变量内容,甚至使用装饰器(decorator)都未能成功。一次偶然机会,代码删了一半,运行成功了,算是机缘巧合吧,然后灵光一闪打通了任督二脉!
首先说下之前使用ddt框架遗留的老问题
我们希望每个用例能动态传入一个参数到html报告里
给docstring传一个变量进去,代码很简单,但是不容易想到,格式参考:”””上海-悠悠:{0}””” 注意是三个双引号,变量用{0}表示参数内容
import unittest
import ddt
# 测试数据
datas = [ {"user": "admin", "psw": "123", "result": "true"},
{"user": "admin1", "psw": "1234", "result": "true"},
{"user": "admin2", "psw": "1234", "result": "true"},
{"user": "admin3", "psw": "1234", "result": "true"},
{"user": "admin4", "psw": "1234", "result": "true"},
{"user": "admin5", "psw": "1234", "result": "true"},
{"user": "admin6", "psw": "1234", "result": "true"},
{"user": "admin7", "psw": "1234", "result": "true"},
{"user": "admin8", "psw": "1234", "result": "true"},
{"user": "admin9", "psw": "1234", "result": "true"},
{"user": "admin10", "psw": "1234", "result": "true"},
{"user": "admin11", "psw": "1234", "result": "true"}]
@ddt.ddt
class Test(unittest.TestCase):
@ddt.data(*datas)
def test_(self, d):
"""上海-悠悠:{0}"""
print("测试数据:%s" % d)
if __name__ == "__main__":
unittest.main()
这样就能把测试数据传入过来了
上面那个案例是把测试数据放到字典里,用例里面穿一个d参数,需要的数据从字典里面去取 实际上也可以给用例传多个参数,每组数据写到一个元祖里,用装饰器@ddt.upack解析出来
import unittest
import ddt
# 测试数据
# datas = [ {"user": "admin", "psw": "123", "result": "true"},
# {"user": "admin1", "psw": "1234", "result": "true"},
# {"user": "admin2", "psw": "1234", "result": "true"},
# {"user": "admin3", "psw": "1234", "result": "true"},
# {"user": "admin4", "psw": "1234", "result": "true"},
# {"user": "admin5", "psw": "1234", "result": "true"},
# {"user": "admin6", "psw": "1234", "result": "true"},
# {"user": "admin7", "psw": "1234", "result": "true"},
# {"user": "admin8", "psw": "1234", "result": "true"},
# {"user": "admin9", "psw": "1234", "result": "true"},
# {"user": "admin10", "psw": "1234", "result": "true"},
# {"user": "admin11", "psw": "1234", "result": "true"}]
datas =[("admin", "123", "true", "用例1描述"),
("admin1", "123", "true", "用例2描述"),
("admin2", "123", "true", "用例3描述"),
("admin3", "123", "true", "用例4描述"),
("admin4", "123", "true", "用例5描述"),
("admin5", "123", "true", "用例6描述"),
]
@ddt.ddt
class Test(unittest.TestCase):
@ddt.data(*datas)
@ddt.unpack
def test_(self, d1, d2, d3, d4):
"""上海-悠悠:{3}"""
print("测试数据:%s" % d1)
print("测试数据:%s" % d2)
print("测试数据:%s" % d3)
print("测试数据:%s" % d4)
if __name__ == "__main__":
unittest.main()