news 2026/4/16 19:32:22

用Python requests库玩转接口自动化测试!测试工程师的实战秘籍

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
用Python requests库玩转接口自动化测试!测试工程师的实战秘籍

接口自动化测试是提升测试效率的关键,而Python的requests库因其简洁易用、功能强大,成为测试工程师的“瑞士军刀”。

但你是否还在用requests.get()requests.post()写重复代码?是否遇到过文件上传失败、Cookie管理混乱、响应断言复杂的问题?

本文从零到一拆解requests库的进阶用法,手把手教你打造高可用的接口自动化框架!


一、requests库的“核心六式”
1. 基础请求:GET/POST轻松上手
import requests # GET请求:查询用户列表 response = requests.get( url="https://api.example.com/users", params={"page": 1, "size": 10} # 自动拼接URL参数 ) # POST请求:创建新用户 payload = {"name": "测试君", "role": "tester"} response = requests.post( url="https://api.example.com/users", json=payload # 自动设置Content-Type为application/json ) print(response.status_code) # 状态码 print(response.json()) # 解析JSON响应
2. 会话管理:保持登录态(Session对象)

痛点:每次请求手动传Cookie/Token太麻烦!
解决:用Session对象自动保持会话!

# 登录并保持会话 with requests.Session() as s: login_data = {"username": "admin", "password": "test123"} s.post("https://api.example.com/login", data=login_data) # 后续请求自动携带Cookie profile = s.get("https://api.example.com/profile") print(profile.json())
3. 文件上传:测试文件接口必备
# 上传图片文件 files = {'file': open('test_image.jpg', 'rb')} # 二进制模式打开 response = requests.post( "https://api.example.com/upload", files=files, headers={"Authorization": "Bearer xyz123"} ) # 多文件上传(如测试批量导入) multiple_files = [ ('files', ('report1.xlsx', open('report1.xlsx', 'rb'))), ('files', ('report2.xlsx', open('report2.xlsx', 'rb'))) ] response = requests.post(url, files=multiple_files)
4. 超时与重试:提升测试稳定性​​​​​​​
# 设置超时(连接超时3秒,读取超时10秒) try: response = requests.get( "https://api.example.com/data", timeout=(3, 10) ) except requests.exceptions.Timeout: print("请求超时,请检查网络或服务状态!") # 自动重试(需安装requests-retry库) from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry retry_strategy = Retry( total=3, # 最大重试次数 status_forcelist=[500, 502, 503, 504], # 遇到这些状态码重试 backoff_factor=1 # 重试等待时间间隔 ) adapter = HTTPAdapter(max_retries=retry_strategy) session = requests.Session() session.mount("https://", adapter) response = session.get(url)
5. 响应断言:自动化测试的灵魂​​​​​​​
# 断言状态码和关键字段 assert response.status_code == 200, f"状态码异常:{response.status_code}" response_data = response.json() assert response_data["code"] == 0, "接口返回错误码" assert "user_id" in response_data["data"], "未返回用户ID" assert len(response_data["data"]["roles"]) >= 1, "用户角色至少一个" # 使用JSON Schema验证数据结构(需安装jsonschema库) schema = { "type": "object", "properties": { "code": {"type": "number"}, "data": { "type": "object", "properties": { "user_id": {"type": "string"}, "roles": {"type": "array"} }, "required": ["user_id"] } }, "required": ["code", "data"] } import jsonschema jsonschema.validate(instance=response_data, schema=schema)
6. 高级配置:代理、SSL验证与Mock​​​​​​​
# 设置代理(用于测试环境隔离或抓包调试) proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.10:1080" } requests.get("https://api.example.com", proxies=proxies) # 禁用SSL证书验证(测试环境临时使用,生产环境慎用!) response = requests.get(url, verify=False) # 结合Mock服务(如使用pytest-mock) def test_api(mocker): mock_response = mocker.Mock() mock_response.json.return_value = {"code": 0, "data": "mocked"} mocker.patch("requests.get", return_value=mock_response) result = requests.get("https://api.example.com") assert result.json()["code"] == 0
二、接口自动化框架设计实战
1. 封装工具类:拒绝重复代码​​​​​​​
class APIClient: def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() self.session.headers.update({"User-Agent": "AutoTest/1.0"}) def get(self, path, params=None): url = f"{self.base_url}{path}" return self.session.get(url, params=params) def post_json(self, path, data): url = f"{self.base_url}{path}" return self.session.post(url, json=data) # 使用示例 client = APIClient("https://api.example.com") response = client.post_json("/users", {"name": "测试员"})
2. 参数化测试:数据驱动​​​​​​​
import pytest test_data = [ ("正常登录", {"username": "admin", "password": "123456"}, 200), ("密码错误", {"username": "admin", "password": "wrong"}, 401), ("用户名为空", {"username": "", "password": "123456"}, 400) ] @pytest.mark.parametrize("case_name, data, expected_code", test_data) def test_login(case_name, data, expected_code): response = requests.post("https://api.example.com/login", json=data) assert response.status_code == expected_code, f"用例失败:{case_name}"
3. 测试报告生成:Allure集成​​​​​​​
import allure @allure.title("测试创建用户接口") def test_create_user(): with allure.step("步骤1:准备测试数据"): payload = {"name": "接口测试用户"} with allure.step("步骤2:发送POST请求"): response = requests.post(url, json=payload) with allure.step("步骤3:验证响应结果"): assert response.status_code == 201 assert response.json()["id"] is not None
三、常见坑点与解决方案
❌ 坑1:响应内容乱码
response.encoding = 'utf-8' # 或 'gbk' print(response.text)

❌ 坑2:文件上传接口报错

❌ 坑3:Cookie失效问题

四、拓展:接口性能监控小技巧​​​​​​​
import time start_time = time.time() response = requests.get("https://api.example.com/heavy-api") end_time = time.time() assert end_time - start_time < 2.0, f"接口响应超时:{end_time - start_time}秒" print(f"接口响应时间:{round(end_time - start_time, 2)}秒")

最后:下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】

​​​软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/16 9:05:02

AI人工智能-RAG方法-第十四周(小白)

一、RAG到底是什么? RAG是 Retrieval Augmengted Generation(检索增强生成)的缩写,核心逻辑特别好理解——就像我们写作文时,先查资料再动笔,而不是凭脑子硬记硬写。 简单说:AI回答问题时,不会只靠自己“记住”的知识,而是从外部文档库(或搜索引擎)里检索出和问题相…

作者头像 李华
网站建设 2026/4/16 9:08:32

深度测评!9款AI论文写作软件评测:本科生毕业论文全场景应对指南

深度测评&#xff01;9款AI论文写作软件评测&#xff1a;本科生毕业论文全场景应对指南 2026年AI论文写作工具测评&#xff1a;功能与效率的深度解析 随着人工智能技术的不断进步&#xff0c;AI论文写作工具逐渐成为本科生撰写毕业论文的重要辅助。然而&#xff0c;面对市场上…

作者头像 李华
网站建设 2026/4/16 9:08:33

经营分析师-《验证合理值》

经营分析师-《验证合理值》 前言&#xff1a; 在工作过程中&#xff0c;有一个环节的工作最常见&#xff0c;也最难做&#xff0c;那就是合理值到底应该是多少&#xff0c;怎么去判断合理值应该设置为多少&#xff0c;本次文章针对历史操作过内容进行分享&#xff0c;文末告知…

作者头像 李华
网站建设 2026/4/16 9:09:09

基于SHAP可解释性AI的支持向量机和K近邻工业轴承故障诊断特征贡献分析(Python,jupyter nootbook文件)

首先加载包含23个时域和频域特征的模拟振动数据集&#xff0c;这些特征模拟了真实轴承在健康、内圈故障、外圈故障和滚动体故障等不同状态下的振动特性。算法通过t-SNE降维技术可视化高维特征空间的数据分布&#xff0c;展示不同故障类型在二维空间的聚类情况。接着&#xff0c…

作者头像 李华