使用python中的unittest、requests、openpyxl、HTMLTestRunner、logging做接口自动化

一、实现逻辑:

1.1测试用例
1.2.读取用例中的参数进行发送请求,并断言结果是否符合预期
1.3.结果写入表格,同时记录日志

二、具体内容

2.1、接口用例(使用openpyxl进行读和写的操作)

使用python中的unittest、requests、openpyxl、HTMLTestRunner、logging做接口自动化

2.2代码实现

2.2.1代码结构

使用python中的unittest、requests、openpyxl、HTMLTestRunner、logging做接口自动化

1.其中case为用例
2.lib为封装的一些数据
3.report为测试结果
4.runner.py为主程序

2.2.2. 读写表格内容

from functions.lib import get_token
import ast
import requests
import json
from openpyxl.styles import Alignment, Font  # 设置单元格、字体样式
import time
import logging

wb = load_workbook(r C:UsersAdministratorDesktop我的测试文档接口测试用例接口测试用例.xlsx )
sheet = wb[ Sheet1 ]

def data(row):
    get_title = sheet.cell(row, 2).value  # 获取测试接口名称
    get_content = sheet.cell(row, 3).value  # 获取测试内容
    get_url = sheet.cell(row, 4).value  # 获取url
    get_method = sheet.cell(row, 5).value  # 获取请求方法
    get_params = ast.literal_eval(sheet.cell(row, 6).value)  # 获取参数内容 并转换为字典类型
    get_params[ token ] = get_token.token  # 替换token
    get_assert = sheet.cell(row, 7).value  # 获取断言
    print(get_assert)

    if get_method ==  GET :
        r = requests.request(method= get_method, url= get_url, params= get_params)  # 发送请求
    else:
        r = requests.request(method= get_method, url= get_url, data= get_params)  # 发送请求

    msg = str(json.dumps(r.json(), indent=True, ensure_ascii=False))  # 获取响应文本并美化json格式

    """定义写入字体和单元格样式"""
    font_pass = Font(size=20, color= 76EE00 )  # 成功的字体样式和大小
    font_false = Font(size=20, color= FF0000 )  # 失败字体的样式和大小
    alignment = Alignment(horizontal= center , vertical= center )  # 垂直居中
    sheet.cell(row, 9).alignment = alignment  # 对I列使用定义的单元格样式
    sheet.cell(row, 10).alignment = alignment  # 对J列使用定义的单元格样式

    """结果写入"""
    sheet.cell(row, 8, value=msg)  # 响应文本写入

    if get_assert in msg:
        sheet.cell(row, 9, value= Pass ).font = font_pass
    else:
        sheet.cell(row, 9, value= Fail ).font = font_false

    sheet.cell(row, 10, value=time.strftime( %Y.%m.%d %H:%M:%S ))  # 写入执行时间

    logging.info(  # 记录日志
        f"case:{get_title +  ,  + get_content}
请求地址:{r.url}	请求方式:{r.request.method}
请求正文:{r.request.body}
响应头:{r.headers}
响应正文:{msg}
")

    wb.save(r C:UsersAdministratorDesktop我的测试文档接口测试用例接口测试用例.xlsx )

    return msg

wb.close()

2.2.3写入excel对应的测试用例

import unittest
from functions.lib import home_data as data

# @unittest.skip( 强制性跳过 )

class Test(unittest.TestCase):
    """ 描述"""
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_00(self):
        """ 描述-成功"""
        msg = data.data(2)
        self.assertIn( 断言成功 , msg)

    def test_02(self):
        """描述成功"""
        msg = data.data(3)
        self.assertIn( 断言成功 , msg)

    def test_03(self):
        """描述成功"""
        msg = data.data(4)
        self.assertIn( 断言成功 , msg)

    def test_04(self):
        """描述成功"""
        msg = data.data(5)
        self.assertIn( 断言成功 , msg)

    def test_05(self):
        """描述成功"""
        msg = data.data(6)
        self.assertIn( 断言成功 , msg)

2.2.4主程序执行

import unittest
from HTMLTestRunner import HTMLTestReport
import os
import logging

def run_case():
    # 用例读取路径
    case_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "case")
    suite = unittest.TestLoader().discover(case_path)

    # 测试报告存放路径
    report_path = os.path.join(os.path.dirname(os.path.realpath(__file__)) + "/report/result_report.html")
    """记录日志"""
    log_path = r"C:UsersAdministratorPycharmProjectsuntitled2functions
eportlog.txt"
    logging.basicConfig(filename=log_path, filemode= w , level=logging.INFO,
                        format= %(asctime)s - %(name)s - %(levelname)s - %(message)s )  # filename 日志文件路径 level 日志的级别 format 格式


    with open(report_path, "wb") as f:
        runner = HTMLTestReport(stream=f,
                                images=False,
                                title="测试报告",
                                description="首页接口和教师创建课程流程接口",
                                tester= 我是测试 ,
                                verbosity=2

                                )
        runner.run(suite)

run_case()

三、测试报告(使用HTMLTestRunner)

使用python中的unittest、requests、openpyxl、HTMLTestRunner、logging做接口自动化

四、日志记录(使用logging)

使用python中的unittest、requests、openpyxl、HTMLTestRunner、logging做接口自动化

五、相关文章推荐

5.1unittest学习推荐
https://blog.csdn.net/qq_26800889/article/details/104943000
5.2.openpyxl对单元个和字体的设置
https://blog.csdn.net/qq_42819930/article/details/89463202
5.3HTMLTestRunner介绍
https://mp.weixin.qq.com/s/2nTg7aC-rksSyjy_duMg0Q
下载地址
https://github.com/hongweifuture/HwTestReport

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容