1.装饰器
#装饰器的官方定义: 装饰器本质上是一个Python函数(其实就是闭包),它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。装饰器用于有以下场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。
2.ddt
import unittest #引入ddt库 from ddt import ddt,data,unpack test_data = [{"name":"张三"},2] @ddt#装饰测试类 class DemoCase(unittest.TestCase): @data(test_data)#装饰函数 def test_jia(self,item): print(item) def test_jian(self): pass if __name__ == '__main__': unittest.main()
运行结果:
plugins: html-3.2.0, metadata-2.0.4collected 2 items demo.py .[{'name': '张三'}, 2] . [100%] ============================== 2 passed in 0.04s ============================== Process finished with exit code 0
3.ddt脱外套
import unittest #引入ddt库 from ddt import ddt,data,unpack test_data = [{"name":"张三"},2] @ddt#装饰测试类 class DemoCase(unittest.TestCase): @data(*test_data)#装饰函数,*test_data脱外套,根据脱外套后的数据执行次数 def test_jia(self,item): print(item) if __name__ == '__main__': unittest.main()
运行结果: plugins: html-3.2.0, metadata-2.0.4collected 2 items demo.py .{'name': '张三'} .2 [100%] ============================== 2 passed in 0.04s ============================== Process finished with exit code 0
4.ddt中的@unpack
import unittest #引入ddt库 from ddt import ddt,data,unpack test_data = [[2,6],[9,1000]] @ddt#装饰测试类 class DemoCase(unittest.TestCase): @data(*test_data)#装饰函数,*test_data脱外套,根据脱外套后的数据执行次数 @unpack def test_jia(self,a,b): print("a: ",a) print("b: ",b) if __name__ == '__main__': unittest.main()
运行结果: plugins: html-3.2.0, metadata-2.0.4collected 2 items demo.py .a: 2 b: 6 .a: 9 b: 1000 [100%] ============================== 2 passed in 0.04s ==============================
5.ddt+openpyxl参数化实现
import unittest #引入ddt库 from ddt import ddt,data,unpack from test01.doexcel import DoExcel
DoExcel类代码
test_data = DoExcel("C:\\Users\\Administrator\\Desktop\\testdemo.xlsx","s1").return_excel_value()#[{},{},{}] @ddt#装饰测试类 class DemoCase(unittest.TestCase): @data(*test_data)#装饰函数,*test_data脱外套,根据脱外套后的数据执行次数 def test_jia(self,item): print(item["method"],item["url"],item["data"],item["expect"]) if __name__ == '__main__': unittest.main()
执行结果: plugins: html-3.2.0, metadata-2.0.4collected 2 items demo.py .post http://www.qabujiaban.com/user/login {'username': 'uuuu222都44', 'password': 'WJHasb124*1'} 0000 .get http://www.qabujiaban.com/user/login {'username': 'uuuu222都44', 'password': 'WJHasb124*1'} 0000 [100%] ============================== 2 passed in 0.31s ============================== Process finished with exit code 0