python ddt+unittest+Excel数据驱动实例

1、testcase.xlsx 要读取的Excel中的内容
python ddt+unittest+Excel数据驱动实例_第1张图片
2、http_request.py 一个get/pos请求方法的类

import requests
import json

class Httprequests:
    #请求get/post方法的接口
    def http_requests(self,url,data,method):
        headers = {
     'Content-type': 'application/json'}
        if method.lower() == 'get':
            res = requests.get(url,data,headers)
        elif method.lower() == 'post':
            res = requests.post(url,data=json.dumps(data),headers=headers)
        else:
            print("只支持get,post请求方式")
        return res

3、exceldel.py 处理Excel数据的接口

from openpyxl import load_workbook

#处理Excel
class doExcel:
    def __init__(self,file_name,sheet_name):
        self.filename=file_name
        self.sheetname=sheet_name

    def get_data(self):
        wb = load_workbook(self.filename)
        sheet = wb[self.sheetname]
        test_data= []
        for row in range(2, sheet.max_row + 1):
            sub_data = {
     }
            for column in range(1, sheet.max_column + 1):
                sub_data[sheet.cell(1, column).value] = sheet.cell(row, column).value
            test_data.append(sub_data)
        return test_data

4、ddt_case1.py ddt+unittest进行数据处理,运行后用例会自动加载成4个单独的用例

import unittest
from excel_unittest_ddt.exceldel import doExcel
from excel_unittest_ddt.http_request import Httprequests
from ddt import ddt,data

test_data= doExcel("testcase.xlsx", "case1").get_data()
print(test_data)
@ddt #用来装饰测试类
class ddttest(unittest.TestCase):
    @data(*test_data)# 装饰测试方法,拿到几个数据就执行几条用例  #加上星号就是脱掉外套[1,3]变成1,3,不加星号就执行一次
    def test_case(self,testdata):
        print(testdata['data'])
        res=Httprequests().http_requests(url=testdata['url'],data=eval(testdata['data']),method=testdata['method'])
        # print(self.url)
        succ = res.json().get('success')
        msg = res.json().get('message')
        try:
            print(succ)
            self.assertEqual(True, succ, msg)
        except  AssertionError as e:
            print("出错了!断言错误{0}".format(e))
            raise e

5、testsuit_01.py 加载、执行用例、生成测试报告

import unittest
import HTMLTestRunnerNew
from excel_unittest_ddt.ddt_case1 import ddttest

class danyuanceshi:
        suit = unittest.TestSuite()
        load=unittest.TestLoader()
        suit.addTest(load.loadTestsFromTestCase(ddttest))

        with open("test_report1.html",'wb') as file:
            runner=HTMLTestRunnerNew.HTMLTestRunner(stream=file,verbosity=2,title="测试结果",description='测试报告',tester='小白')
            runner.run(suit)

python ddt+unittest+Excel数据驱动实例_第2张图片

你可能感兴趣的:(python,unittest,excel,单元测试,python)