Python 封装从Excel拿取数据,封装业务逻辑判断,ddt 用列unittest执行
login_logic2.py
def login_check(username=None, password=None):
if username is not None and password is not None:
if username == 'nanwu' and password == "123456":
return {"code": 0, "message": "登陆成功"}
else:
return {"code": 1, "message": "账号密码不正确"}
else:
return {"code": 1, "message": "所有参数不能为空"}
handle_excel.py
from openpyxl import load_workbook
import os
class handle_excel:
def __init__(self, file_path, sheet_name):
self.wb = load_workbook(file_path)
self.sh = self.wb[sheet_name]
def read_title(self):
titles = []
for item in list(self.sh.rows)[0]:
titles.append(item.value)
return titles
def read_datas(self):
titles = self.read_title()
print(titles)
all_datas = []
for item in list(self.sh.rows)[1:]:
values = []
for val in item:
values.append(val.value)
res = dict(zip(titles, values))
all_datas.append(res)
return all_datas
if __name__ == '__main__':
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_excel.xlsx")
exc = handle_excel(file_path, 'login')
cases = exc.read_datas()
for case in cases:
print(case)
test_login_case2.py
import unittest
import ddt
import os
from excel_case.handle_excel import handle_excel
from excel_case.login_logic2 import login_check
# 测试数据
# 测试步骤
# 测试结果与预期结果比对
# datas = [
# {"name": "nanwu", "password": "123456", "res": {"code": 0, "message": "登陆成功"}},
# {"name": "nanwu", "password": "qwer123", "res": {"code": 1, "message": "账号密码不正确"}},
# {"name": "nanwu", "password": "qwer1234", "res": {"code": 1, "message": "账号密码不正确"}}
# ]
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_excel.xlsx")
exc = handle_excel(file_path, 'login')
cases = exc.read_datas()
print(cases)
@ddt.ddt
class test_login_case2(unittest.TestCase):
@ddt.data(*cases)
def test_login_ok(self, case):
res2 = login_check(case["name"], case["password"])
self.assertEqual(res2, eval(case["res"]))
# def test_login_ok(self):
# res = login_check("nanwu", "123456")
# # assert res == {"code": 0, "message": "登陆成功"}
# self.assertEqual(res, {"code": 0, "message": "登陆成功"})1
#
# def test_login_wrong_Password(self):
# res = login_check("nanwu", "qwer123")
# self.assertEqual(res, {"code": 1, "message": "账号密码不正确"})
#
# def test_login_wrong_Passwords(self):
# res = login_check("nanwu", "qwer1234")
# self.assertEqual(res, {"code": 1, "message": "账号密码不正确"})
#
# def test_login_wrong_user(self):
# res = login_check("nanwu")
# self.assertEqual(res, {"code": 1, "message": "所有参数不能为空"})
#
# def test_login_wrong_users(self):
# res = login_check("nanwu", "123456")
# self.assertEqual(res, {"code": 1, "message": "所有参数不能为空"})
# if __name__ == '__main__':
# unittest.main()