博客
关于我
python + requests实现的接口自动化测试(超详细~)
阅读量:799 次
发布时间:2023-03-05

本文共 3180 字,大约阅读时间需要 10 分钟。

接口自动化测试框架

随着公司测试方向的转型,由原来的功能测试转变为接口测试,我决定使用Python编写一个接口自动化测试框架。以下是框架的搭建过程和总结。

思路概述

正常的接口测试流程包括:

  • 确定测试接口的工具
  • 配置接口参数
  • 执行测试
  • 检查测试结果(可能需要数据库辅助)
  • 生成测试报告
  • 为了实现灵活性,我将业务和数据分离,设计了一个模块化的框架。

    目录结构

    框架目录结构如下:

    common/├── Log.py          # 日志处理├── configHttp.py  # 接口配置├── ReadConfig.py   # 配置文件读取├── ConfigDB.py     # 数据库配置├── ConfigEmail.py  # 邮件配置└── common.py       # 通用方法

    result/├── *.log # 测试日志└── test.zip # 测试报告存档

    testCase/├── test_case.py # 测试用例└── test_case.txt # 用例列表

    testFile/├── SQL.xml # SQL语句存放└── test.xlsx # 测试用例存放

    config.ini # 配置文件

    caselist.txt # 需要执行的用例列表

    配置文件与读取配置

    配置文件config.ini内容包括:

    [DATABASE]host=50.23.190.57username=xxxxxxxpassword=******port=3306database=databasename[HTTP]baseurl=http://xx.xxxx.xxport=8080timeout=1.0[EMAIL]mail_host=smtp.163.commail_user=xxxx@163.commail_pass=*********mail_port=25sender=xxx@163.comreceiver=xxxx@qq.com/xxxx@qq.comsubject=pythoncontent=...on_off=1

    ReadConfig.py用于读取配置文件:

    import osimport codecsimport configparserclass ReadConfig:    def __init__(self):        self.cf = configparser.ConfigParser()        self.cf.read(os.path.join(os.path.dirname(__file__), "config.ini"))

    日志处理

    Log.py实现了日志记录功能,并支持多线程操作:

    import loggingfrom datetime import datetimeimport threadingclass Log:    def __init__(self):        global logPath, resultPath, proDir        self.logger = logging.getLogger()        self.logger.setLevel(logging.INFO)        self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')        handler = logging.FileHandler(os.path.join(self.resultPath, 'output.log'))        handler.setFormatter(self.formatter)        self.logger.addHandler(handler)

    HTTP 请求方法

    configHttp.py实现了HTTP接口的get和post方法:

    import requestsfrom ReadConfig import ReadConfigfrom common.Log import Logclass ConfigHttp:    def __init__(self):        self.log = Log.get_log()        self.logger = self.log.get_logger()        self.headers = {}        self.params = {}        self.data = {}        self.url = None        self.timeout = 0.5

    数据库操作

    ConfigDB.py实现了数据库连接与操作:

    import pymysqlfrom ReadConfig import ReadConfigfrom common.Log import Logclass MyDB:    def __init__(self):        self.log = Log.get_log()        self.logger = self.log.get_logger()        self.db = None        self.cursor = None

    邮件配置

    ConfigEmail.py实现了邮件发送功能,支持附件和压缩文件:

    import osimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom datetime import datetimeimport threadingimport zipfileimport globclass Email:    def __init__(self):        self.value = readConfig.get_email("receiver")        self.sender = readConfig.get_email("sender")        self.subject = readConfig.get_email("subject") + " " + datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    测试运行

    runAll.py执行测试并生成报告:

    import unittestfrom HTMLTestRunner import HTMLTestRunnerimport osclass RunAll(unittest.TestCase):    def set_case_list(self):        with open(self.caseListFile) as fb:            for value in fb.readlines():                data = str(value).strip()                if data and not data.startswith("#"):                    self.caseList.append(data)

    总结

    通过以上步骤,我们完成了一个完整的接口自动化测试框架。框架支持灵活配置接口参数,自动化处理数据库和邮件发送,并生成HTML格式的测试报告。后续工作中,可以继续扩展支持更多接口类型和测试用例管理功能。

    转载地址:http://biafk.baihongyu.com/

    你可能感兴趣的文章
    Pytest参数详解 — 基于命令行模式
    查看>>
    pytorch cv2 plt transforms pause waitforbuttonpress一个完整的图片处理程序
    查看>>
    pytest学习和使用 - Pytest用例执行结果有哪几种状态?
    查看>>
    pytest实战技巧之参数化应用!
    查看>>
    Pytest实践:Python测试技术基础知识!
    查看>>
    Pytest接口自动化测试实战演练
    查看>>
    Pytest插件pytest-selenium-让自动化测试更简洁
    查看>>
    Pytest数据驱动怎么玩?实战教程来了!
    查看>>
    Pytest数据驱动怎么玩?实战教程来了!
    查看>>
    pytest文档25-conftest.py作用范围
    查看>>
    Pytest框架 之【用例执行顺序】
    查看>>
    Pytest框架中的测试用例执行方式!
    查看>>
    pytest框架快速入门-pytest运行时参数说明,pytest详解,pytest.ini详解
    查看>>
    Pytest框架环境切换实战教程!赶快收藏
    查看>>
    Pytest测试实战|Conftest.py详解
    查看>>
    Pytest测试框架快速搭建
    查看>>
    pytest测试框架:最强大的自动化测试工具,让测试变得轻松有趣
    查看>>
    pytest简介及jenkins集成
    查看>>
    Pytest自动化框架运行全局配置文件pytest.ini
    查看>>
    pytest自动化测试-Git中的测试用例运行
    查看>>