python+requests接口自动化框架的实现

框架概述

一个完整的接口自动化测试框架应包括以下几部分:

  • 配置管理:管理测试环境、API基本信息等配置。
  • 请求封装:封装HTTP请求,使其易于调用和维护。
  • 数据驱动:通过外部数据文件驱动测试。
  • 日志记录:记录测试过程中的请求和响应,便于追踪和调试。
  • 测试报告:生成可视化的测试报告,展示测试结果。

环境准备

在开始构建框架之前,确保你的开发环境已经安装了Python和相关依赖库。

pip install requests pytest pytest-html
 
 

项目结构

设计合理的项目结构有助于提高代码的可维护性和扩展性。推荐的项目结构如下:

api_test_framework/
├── config/
│   └── config.yaml
├── data/
│   └── test_data.json
├── logs/
│   └── test.log
├── reports/
│   └── report.html
├── tests/
│   └── test_example.py
├── utils/
│   ├── request_handler.py
│   ├── config_reader.py
│   └── logger.py
└── main.py
​
 
 

基础组件

配置管理

使用YAML文件管理配置,可以方便地修改测试环境和API信息。

config/config.yaml

base_url: "https://api.example.com"
timeout: 30
headers:
  Content-Type: "application/json"
 
 

utils/config_reader.py

import yaml

class ConfigReader:
    def __init__(self, config_file='config/config.yaml'):
        with open(config_file, 'r') as file:
            self.config = yaml.safe_load(file)

    def get(self, key, default=None):
        return self.config.get(key, default)
​
 
 

请求封装

封装Requests库的请求方法,便于后续调用和维护。

utils/request_handler.py

import requests
from utils.config_reader import ConfigReader

class RequestHandler:
    def __init__(self):
        self.config = ConfigReader()
        self.base_url = self.config.get('base_url')
        self.headers = self.config.get('headers')
        self.timeout = self.config.get('timeout')

    def get(self, endpoint, params=None):
        url = f"{self.base_url}{endpoint}"
        response = requests.get(url, headers=self.headers, params=params, timeout=self.timeout)
        return response

    def post(self, endpoint, data=None):
        url = f"{self.base_url}{endpoint}"
        response = requests.post(url, headers=self.headers, json=data, timeout=self.timeout)
        return response
​
 
 

日志记录

使用Python的logging模块记录测试过程中的请求和响应。

utils/logger.py

import logging

def setup_logger(log_file='logs/test.log'):
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    fh = logging.FileHandler(log_file)
    fh.setLevel(logging.DEBUG)

    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    logger.addHandler(fh)
    logger.addHandler(ch)
    return logger

logger = setup_logger()
​
 
 

测试用例编写

编写测试用例,并使用pytest进行管理和执行。

tests/test_example.py

import pytest
from utils.request_handler import RequestHandler
from utils.logger import logger

request_handler = RequestHandler()

def test_get_example():
    logger.info("Starting test_get_example")
    response = request_handler.get('/example')
    assert response.status_code == 200
    assert response.json().get('key') == 'value'
    logger.info("Finished test_get_example")

def test_post_example():
    logger.info("Starting test_post_example")
    payload = {"key": "value"}
    response = request_handler.post('/example', data=payload)
    assert response.status_code == 201
    assert response.json().get('key') == 'value'
    logger.info("Finished test_post_example")
​
 
 

运行与报告

使用pytest运行测试并生成HTML格式的测试报告。

main.py

import pytest

if __name__ == "__main__":
    pytest.main(["-v", "--html=reports/report.html", "--self-contained-html"])
​
 
 

实践应用

接口自动化测试框架的应用不仅限于基本的请求和响应验证。我们可以根据实际需求扩展以下功能:

  • 数据驱动测试:使用CSV、JSON或Excel文件驱动测试用例。
  • 异常处理:处理超时、连接失败等异常情况,提高测试的健壮性。
  • 并发测试:使用多线程或异步请求实现高并发测试。
posted @   utwoB  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示