在get_data中定义取全部用例和取部分用例两种模式
# 1. http_request.py import requests class HttpRequest: def http_request(self, url, method, data=None, cookie=None): try: if method.upper() == "GET": res = requests.get(url, data, cookies=cookie) elif method.upper() == "POST": res = requests.post(url, data, cookies=cookie) else: print("请输入正确的参数") except Exception as e: print("请求报错了:{}".format(e)) raise e return res
# 2. get_data6.py from openpyxl import load_workbook class DoExcel: def __init__(self, file, sheet): self.file = file self.sheet = sheet def get_data(self, mode="all"): wb = load_workbook(self.file) sheet = wb[self.sheet] case_data = [] for i in range(2, sheet.max_row+1): sub_data = {} sub_data["case_id"] = sheet.cell(i, 1).value sub_data["url"] = sheet.cell(i, 2).value sub_data["method"] = sheet.cell(i, 3).value sub_data["data"] = eval(sheet.cell(i, 4).value) sub_data["expected"] = sheet.cell(i, 5).value case_data.append(sub_data) if mode == "all": final_data = case_data else: # [1, 2, 5] final_data = [] for test_data in case_data: # 遍历每一条测试数据,如果测试数据的id在传入的列表中,就把这条数据加到final_data if test_data["case_id"] in mode: final_data.append(test_data) return final_data if __name__ == "__main__": case_data = DoExcel("data_7.xlsx", "sh2").get_data([1, 2, 3]) print(case_data)
# 3.test_login.py import unittest from API_AUTO.tools.http_request import HttpRequest from ddt import ddt, data, unpack from day_20191202.config_case_data.get_data6 import DoExcel # 自定义取某几条数据执行用例 test_data = DoExcel("data_7.xlsx", "sh2").get_data([1, 2, 4]) # print(test_data) @ddt class TestLogin(unittest.TestCase): def setUp(self): print("start testing...") def tearDown(self): print("case done.") @data(*test_data) @unpack # 注意新的表格数据多了id,要用参数来接收case_id def test_api(self, case_id, url, method, data, expected): # print("url:", url) # print("method", method) # print("data_c", data) res = HttpRequest().http_request(url, method, data) r = res.json()["info"] try: self.assertEqual(r, expected) except AssertionError as e: print("there is an error in the case {}".format(e)) raise e if __name__ == '__main__': TestLogin().test_api()
# 4. run.py import unittest from day_20191202.config_case_data.test_login import TestLogin import HTMLTestRunner suite = unittest.TestSuite() loader = unittest.TestLoader() suite.addTest(loader.loadTestsFromTestCase(TestLogin)) with open("login6.html", "wb") as file: runner = HTMLTestRunner.HTMLTestRunner(stream=file, verbosity=2, title="登录6测试报告", description="管住心情,就是胜利") runner.run(suite) # runner = unittest.TextTestRunner(verbosity=2) # runner.run(suite)
测试数据如图: