未学习excel操作前,测试用例写法一般如下:
缺点:代码重复率高,每个函数只能写一条用例。
import unittest from common import login from read_xl import read_excel data = read_excel('cases.xlsx', 'Sheet1') print(data) class TestLogin(unittest.TestCase): def test_login_01(self): username = '2r' password = '' expected = {"code": "300", "msg": "用户名或密码错误"} actual = login(username, password) self.assertEqual(expexted, actual) def test_login_02(self): username = 'sda' password = '123' expected = {"code": "300", "msg": "用户名或密码错误"} actual = login(username, password) self.assertEqual(expexted, actual) def test_login_03(self): username = 'yuz' password = '123' expected = {"code": "200", "msg": "登录成功"} actual = login(username, password) self.assertEqual(expexted, actual)
学习了excel操作后,代码可优化如下:
# 两个问题: # 1.unittest 只发现了一个用例,实际上有3个测试数据 # 2.需要把excel读取的data单元格数据从字符串转为字典 # # 优化:每组测试数据单独一个用例,即参数化,使用数据驱动 def test_login(self): for row in data: params_str = row['data'] params = eval(params_str) # 脱掉外层衣服,将字符串转为字典 username = params['username'] password = params['password'] expected = eval(row['expected']) actual = login(username, password) self.assertEqual(expexted, actual)
结合数据驱动后,代码可以更加优化:
import unittest from common import login from read_xl import read_excel from unittestreport import ddt, list_data data = read_excel('cases.xlsx', 'Sheet1') """ 参数化的具体用法: 1.unittestreport,ddt,list_data 2.在测试函数当中,加入参数row,row参数是可以自己定义的 """ @ddt class TestLogin(unittest.TestCase): @list_data(data) def test_login(self, row): # row 标识每次从data这个list中取出其中一个数据,{} # 代表代码一组测试数据相当于for row in data: # 源码:会自动生成一个新的test_login_01 函数 params_str = row['data'] params = eval(params_str) # 脱掉外层衣服,将字符串转为字典 username = params['username'] password = params['password'] expected = eval(row['expected']) actual = login(username, password) self.assertEqual(expexted, actual)