29. 自动化测试开发框架拓展之接口测试实现详解
一、HTTP客户端类核心实现
1.1 类结构定义
import requestsclass 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’} | 否 |
timeout | 5.0 | 否 |
json/data | {‘key’: ‘value’} | 视请求类型 |
三、实战测试示例
3.1 GET请求验证
client = HTTPClient()
response = client.request('GET', r'http://httpbin.org/get?name=test')
print(f"状态码: {response.status_code}")
print(f"响应体: {response.text}")
3.2 POST请求验证
test_data = {"user": "tester","env": "production"
}
response = client.request('POST','http://httpbin.org/post',json=test_data)print(f"状态码: {response.status_code}")
print(f"响应JSON: {response.json()}")
四、企业级优化建议
4.1 现存问题清单
问题描述 | 风险等级 | 改进方案 |
---|
缺乏异常处理机制 | 高 | 添加try/except块 |
未实现请求重试功能 | 中 | 集成retrying库 |
没有性能监控指标 | 中 | 添加请求耗时统计 |
会话对象拼写错误 | 低 | 修正_sycn_session为_sync_session |
4.2 增强型客户端实现
from retrying import retry
import timeclass 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 responseexcept requests.exceptions.RequestException as e:print(f"请求失败: {str(e)}")raise
4.3 大厂最佳实践
某头部互联网企业接口测试规范:
- 所有请求必须添加唯一追踪ID(X-Request-ID)
- 敏感参数必须进行加密处理
- 实施分级超时配置(读取5s/连接10s)
- 每个请求记录详细日志(含耗时/响应大小)
- 每日自动生成接口可用性报告
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 == 200client.request('DELETE', f'/users/{user_id}')
test_user_api()
六、完整代码
"""
Python :3.13.3
Selenium: 4.31.0interface.py
"""import requestsclass 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
client = HTTPClient()
response = client.request('GET',r'http://localhost:8080/test')
print(response.status_code, response.text)
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)
「小贴士」:点击头像→【关注】按钮,获取更多软件测试的晋升认知不迷路! 🚀