基于unittest parameterized实现参数化和ddt驱动测试
安装:pip install parameterized
实例:
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time:2022/6/14 22:24 # @Author:Lhtester # @Filename:unitest_01.py import unittest from parameterized import parameterized version=(4,0,7) def add(x,y):#功能 return x+y class Add_test(unittest.TestCase):#创建测试用例类要继承unittest.TestCase,代表是测试用例类 '''测试用例''' def setUp(self): print("setup执行。。。。") @parameterized.expand([(10,20),("a","e"),(2,20)]) def test_00(self,x,y): result = add(x,y) print(result) self.assertIn(result,[30,"ae",22,5],msg='断言失败!一般错误结果和原因') # @unittest.skipIf(version>=(3,9,7),"版本低于3.9,就不用测试test_01")#不满足这个条件就执行,满足就跳过 # def test_01(self):#测试用例方法,必须以test开头 # result = add(1,2) # # self.assertEqual(result,3,msg='断言失败!一般错误结果和原因')#判断相等 # # self.assertEqual(result,2,msg='断言失败!一般错误结果和原因')#判断相等 # # self.assertIn(result,[1,2,34,5,3],msg='断言失败!一般错误结果和原因')#判断结果是否是列表的成员 # # self.assertIn(result,[1,2,34,5],msg='断言失败!一般错误结果和原因') # def test_02(self): # res= add("a","B") # self.assertEqual(res,"aB",msg='断言失败!一般错误结果和原因') if __name__ == '__main__': unittest.main()
安装:pip install ddt
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time:2022/6/14 22:24 # @Author:Lhtester # @Filename:unitest_01.py import unittest from ddt import ddt,data version=(4,0,7) def add(x,y):#功能 return x+y #装饰类,让他进行包装和处理 @ddt class Add_test(unittest.TestCase):#创建测试用例类要继承unittest.TestCase,代表是测试用例类 '''测试用例''' def setUp(self): print("setup执行。。。。") # @data(100)#实现向方法传参 # @data({"b":1,"w":2})#实现向方法传参. # @data([1,2,453,24,97]) # 实现向方法传参. #可以进行字典,列表,元组,字符串,也可以传多个列表和字典 #多次传递 @data({"name":"alex","age":18,"class":"一班","from":"china"},{"sex":"boy"},{"school":" junior high school "}) def test_01(self,a): print(a) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time:2022/6/14 22:24 # @Author:Lhtester # @Filename:unitest_01.py import unittest from ddt import ddt,data,unpack def add(a ,b, c):#功能 return a +b +c #装饰类,让他进行包装和处理 @ddt class Add_test(unittest.TestCase):#创建测试用例类要继承unittest.TestCase,代表是测试用例类 @data((1,2,3),(2,3,4),(3,4,5),(4,5,6)) @unpack#多次传递多个数据 def test_01(self,a,b,c): result=add(a,b,c) print(result) if __name__ == '__main__': unittest.main()