多组数据的测试用例,可以用数据驱动设计模式,一组数据对应一个测试用例,用例自动加载生成
采用数据驱动方式,把数据写在excel表格中,代码做封装,用数据驱动测试,两部分相互独立。python中用ddt模块来做数据驱动,代码简单好维护,调试也方便。
一、安装
1.安装ddt模块,打开cmd输入pip install ddt在线安装
>>pip install ddt
选择国内源安装pip install -i https://mirrors.aliyun.com/pypi/simple
二、数据驱动原理
1.测试数据为多个字典的list类型
2.测试类上加上@ddt.ddt
3.需要进行数据驱动的方法加上@ddt.data(*测试数据)
4.测试用例方法用参数接收def test_login(self,test_info)
5.运行后用例会自动加载成单独的用例
登录示例1:
import ddt import unittest test_data1 = [{"username": "zhangsan", "pwd": "zhangsan"}, {"username": "lisi", "pwd": "lisi"}, {"username": "wangwu", "pwd": "wangwu"}, ] test_data2 = [{"username": "wukong", "pwd": "wukong"}, {"username": "wuneng", "pwd": "woneng"}, {"username": "wujing", "pwd": "wujing"}, ] @ddt.ddt class Test(unittest.TestCase): def setUp(self): print("Start!") def tearDown(self): print("end!") @ddt.data(*test_data1) def test_ddt1(self, data): print(data) @ddt.data(*test_data2) def test_ddt2(self, data): print(data) if __name__ == "__main__": unittest.main() ''' 结果: Start! {'username': 'zhangsan', 'pwd': 'zhangsan'} end! Start! {'username': 'lisi', 'pwd': 'lisi'} end! Start! {'username': 'wangwu', 'pwd': 'wangwu'} end! Start! {'username': 'wukong', 'pwd': 'wukong'} end! Start! {'username': 'wuneng', 'pwd': 'woneng'} end! Start! {'username': 'wujing', 'pwd': 'wujing'} end! ...... ---------------------------------------------------------------------- Ran 6 tests in 0.000s OK '''
登录示例2:
import unittest import ddt from lenom.aa import ExcelHandler def login(username=None, password=None): """登录""" if (not username) or (not password): # 用户名或者密码为空 return {"msg": "empty"} if username == 'yuz' and password == '123456': # 正确的用户名和密码 return {"msg": "success"} return {"msg": "error"} cases = ExcelHandler('cases.xlsx').read_data('login') @ddt.ddt class TestLogin(unittest.TestCase): @ddt.data(*cases) def test_login(self,case_info): data = eval(case_info['data']) username = data["username"] password = data["password"] expected_response = case_info["expected"] actual_response = login(username, password) self.assertTrue(expected_response == actual_response['msg']) if __name__ == '__main__': unittest.main()