💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
参数化和数据驱动的概念这个肯定要知道的,参数化的思想是代码用例写好了后,不需要改代码,只需维护测试数据就可以了,并且根据不同的测试数据生成多个用例 python里面用unittest框架 ~~~ 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() ~~~ unittest框架还有一个paramunittest也可以实现 ~~~ import unittest import paramunittest import time # python3.6 # 作者:上海-悠悠 @paramunittest.parametrized( {"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"}, ) class TestDemo(unittest.TestCase): def setParameters(self, user, psw, result): '''这里注意了,user, psw, result三个参数和前面定义的字典一一对应''' self.user = user self.user = psw self.result = result def testcase(self): print("开始执行用例:--------------") time.sleep(0.5) print("输入用户名:%s" % self.user) print("输入密码:%s" % self.user) print("期望结果:%s " % self.result) time.sleep(0.5) self.assertTrue(self.result == "true") if __name__ == "__main__": unittest.main(verbosity=2) ~~~ 如果用的是pytest框架,也能实现参数化 ~~~ # content of test_canshu1.py # coding:utf-8 import pytest @pytest.mark.parametrize("test_input,expected", [ ("3+5", 8), ("2+4", 6), ("6 * 9", 42), ]) def test_eval(test_input, expected): assert eval(test_input) == expected if __name__ == "__main__": pytest.main(["-s", "test_canshu1.py"]) ~~~ pytest里面还有一个更加强大的功能,获得多个参数化参数的所有组合,可以堆叠参数化装饰器 ~~~ import pytest @pytest.mark.parametrize("x", [0, 1]) @pytest.mark.parametrize("y", [2, 3]) def test_foo(x, y): print("测试数据组合:x->%s, y->%s" % (x, y)) if __name__ == "__main__": pytest.main(["-s", "test_canshu1.py"]) ~~~