unittest(9)- 使用ddt给测试用例传参

时间:2022-04-05 04:43:15
# 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_data4.py

from openpyxl import load_workbook

class DoExcel:
    def __init__(self, file, sheet):
        self.file = file
        self.sheet = sheet

    def get_data(self):
        wb = load_workbook(self.file)
        sheet = wb[self.sheet]
        case_data = []
        for i in range(1, sheet.max_row+1):
            sub_data = {}
            sub_data["url"] = sheet.cell(i, 1).value
            sub_data["method"] = sheet.cell(i, 2).value
            sub_data["data"] = eval(sheet.cell(i, 3).value)
            sub_data["expected"] = sheet.cell(i, 4).value
            case_data.append(sub_data)
        return case_data

if __name__ == "__main__":
    case_data = DoExcel("data_7.xlsx", "sh2").get_data()
    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.learn_ddt.get_data4 import DoExcel

case_data = DoExcel("data_7.xlsx", "sh2").get_data()

@ddt
class TestLogin(unittest.TestCase):
    @data(*case_data)
    @unpack
    def test_api(self, 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.learn_ddt.class_test_ddt import TestLogin
import HTMLTestRunner

suite = unittest.TestSuite()
loader = unittest.TestLoader()
suite.addTest(loader.loadTestsFromTestCase(TestLogin))

with open("login7.html", "wb") as file:
    runner = HTMLTestRunner.HTMLTestRunner(stream=file,
                                           verbosity=2,
                                           title="登录4测试报告",
                                           description="管住心情,就是胜利")
    runner.run(suite)
# runner = unittest.TextTestRunner(verbosity=2)
# runner.run(suite)