python+excel读取数据(通过load_workbook)

结构说明

class_http:实例化测试用例
do_excel:用于读取test.xlsx中存放的测试用例,并封装成列表
get_data:用于存储cookie
test.xlsx:用于存放接口测试的测试用例相关信息
test_report:生成的测试报告
test_suite:测试用例执行,并断言
test.xlsx
本次接口测试只用到了 url(路径)、data(请求参数)、method(请求方式)
在这里插入图片描述
do_excel.py
引入 load_workbook 模块读取 excel 文件中对应的"修改"表中的数据,封装为列表并返回

from openpyxl import load_workbook

class Doexcel:
    def __init__(self,file_name,sheet_name):
        self.file_name = file_name
        self.sheet_name = sheet_name

    def get_data(self):
        wb = load_workbook(self.file_name)
        sheet = wb[self.sheet_name]
        test_data = []  #数据存储为列表格式
        for i in range(1,sheet.max_row):
            sub_data = {} #数据存储为字典格式
            sub_data['url'] = sheet.cell(i+1,2).value
            sub_data['data'] = sheet.cell(i+1,3).value
            sub_data['method'] = sheet.cell(i+1,4).value

            test_data.append(sub_data)

        return test_data  #返回获取到的数据

class_http.py实例化测试用例

import unittest
from tools.http_requests import HttpRequest
from class_5_22.get_data import GetData
# from class_5_22.test_suite import test_data

class TestHttp(unittest.TestCase):
    def setUp(self):
        pass
    def __init__(self,methodName,url,data,method):  #通过初始化函数传参
        super(TestHttp,self).__init__(methodName)  #超继承,保证父类的方法不被修改
        #super(子类名,self).父类和这个子类名同名的方法(参数)
        self.url = url
        self.data = data
        self.method = method

    def test_api(self):
            res = HttpRequest().http_request(self.url,self.data,self.method,getattr(GetData,'Cookie'))
            if res.cookies:
                setattr(GetData,'Cookie',res.cookies)
            print res.json()

test_suite.py执行测试用例

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import unittest
import HTMLTestRunner
from class_5_22.class_http import TestHttp
from class_5_22.do_excel import Doexcel
suite = unittest.TestSuite()  #存储用例

test_data = Doexcel('test.xlsx','python').get_data()
for item in test_data:
    suite.addTest(TestHttp("test_api",item['url'],item['data'],item['method']))  #获取数据,执行用例

#生成html报告
with open("test_report.html","wb") as file:
    runner = HTMLTestRunner.HTMLTestRunner(
        stream = file,
        verbosity = 2,
        title = "单元测试报告",
        description = "python单元测试报告-第一次",
        tester="么么哒"
    )
    runner.run(suite)

你可能感兴趣的:(python基础)