30. 自动化测试开发框架拓展之接口测试

自动化测试开发框架拓展之接口测试实现详解

一、HTTP客户端类核心实现

1.1 类结构定义

import requests

class HTTPClient:
    def __init__(self):
        self._sycn_session = requests.Session()  # 🛠️ 创建持久会话对象
        
    def request(self, *args, **kwargs):
        with self._sycn_session.request(*args, **kwargs) as rep:
            rep.encoding = 'utf-8'  # 🌐 强制设置响应编码
        return rep
关键组件说明表
组件作用描述技术优势
requests.Session()保持TCP连接复用提升50%以上请求速度
with语句自动管理会话资源避免资源泄漏
UTF-8编码强制设置统一响应数据处理解决中文乱码问题

二、请求方法深度解析

2.1 request方法参数说明

def request(self, *args, **kwargs):
    """
    :param args: 请求参数(方法、URL)
    :param kwargs: 请求配置(headers/timeout等)
    :return: Response对象
    """
参数支持列表
参数类型示例值必填项
method‘GET’/‘POST’/‘PUT’
url‘http://api.example.com’
headers{‘Content-Type’: ‘application/json’}
timeout5.0
json/data{‘key’: ‘value’}视请求类型

三、实战测试示例

3.1 GET请求验证

# 实例化客户端
client = HTTPClient()

# 执行GET请求
response = client.request('GET', 
                         r'http://httpbin.org/get?name=test')
print(f"状态码: {response.status_code}")
print(f"响应体: {response.text}")

# 示例输出:
# 状态码: 200
# 响应体: {
#   "args": {"name": "test"}, 
#   "headers": {...},
#   "url": "http://httpbin.org/get"
# }

3.2 POST请求验证

# 准备测试数据
test_data = {
    "user": "tester",
    "env": "production"
}

# 执行POST请求
response = client.request('POST',
                         'http://httpbin.org/post',
                         json=test_data)

print(f"状态码: {response.status_code}")
print(f"响应JSON: {response.json()}")

# 示例输出:
# 状态码: 200
# 响应JSON: {
#   "data": "{\"user\": \"tester\", \"env\": \"production\"}",
#   "json": {"env": "production", "user": "tester"},
#   ...
# }

四、企业级优化建议

4.1 现存问题清单

问题描述风险等级改进方案
缺乏异常处理机制添加try/except块
未实现请求重试功能集成retrying库
没有性能监控指标添加请求耗时统计
会话对象拼写错误修正_sycn_session为_sync_session

4.2 增强型客户端实现

from retrying import retry
import time

class EnhancedHTTPClient(HTTPClient):
    @retry(stop_max_attempt_number=3, wait_fixed=2000)
    def request(self, *args, **kwargs):
        start = time.time()
        try:
            response = super().request(*args, **kwargs)
            response.elapsed = time.time() - start  # ⏱️ 记录请求耗时
            return response
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {str(e)}")
            raise

4.3 大厂最佳实践

某头部互联网企业接口测试规范

  1. 所有请求必须添加唯一追踪ID(X-Request-ID)
  2. 敏感参数必须进行加密处理
  3. 实施分级超时配置(读取5s/连接10s)
  4. 每个请求记录详细日志(含耗时/响应大小)
  5. 每日自动生成接口可用性报告
# 符合企业规范的请求示例
headers = {
    "X-Request-ID": "req_123456",
    "X-Signature": gen_signature(data)
}

response = client.request(
    'POST',
    'https://api.example.com/v1/data',
    json=encrypt_data(test_data),
    headers=headers,
    timeout=(5, 10)
)

五、扩展应用场景

5.1 接口自动化测试流程

def test_user_api():
    # 创建测试用户
    create_res = client.request('POST', '/users', json={'name': 'test'})
    user_id = create_res.json()['id']
    
    # 验证用户信息
    get_res = client.request('GET', f'/users/{user_id}')
    assert get_res.status_code == 200
    
    # 清理测试数据
    client.request('DELETE', f'/users/{user_id}')

# 执行测试
test_user_api()

六、完整代码

"""
Python :3.13.3
Selenium: 4.31.0

interface.py
"""

import requests


class HTTPClient:

    def __init__(self):
        self._sycn_session = requests.Session()

    def request(self, *args, **kwargs):
        with self._sycn_session.request(*args, **kwargs) as rep:
            rep.encoding = 'utf-8'
        return rep

# 验证get接口数据------------------------------------
client = HTTPClient()
response = client.request('GET',
                          r'http://localhost:8080/test')
print(response.status_code, response.text)

# 使用JSON数据输入验证post接口-------------------------------------
from json import load
with open(r'E:\Py3Sel3Ifram\chap7\demo.json',
          'r',
          encoding='utf-8') as f:
    json_data = load(f)
response2 = client.request('POST',
               r'http://localhost:8080/api/db',
               json=json_data)
print(response2.status_code, response2.text)

「小贴士」:点击头像→【关注】按钮,获取更多软件测试的晋升认知不迷路! 🚀

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值