作为测试工程师,如果你还在手动点接口,那真的OUT了!今天手把手教你用Python+Requests打造高可用接口自动化测试框架,覆盖数据驱动、关联封装、Allure报告等核心技能,学完薪资直接涨3K!
Python+Requests接口自动化测试,从入门到持续集成,学完拿高薪!
🚀 一、自动化测试的三个层次(金字塔模型)
1️⃣ 单元测试:测试单个函数/类(开发者主导)
2️⃣ 接口测试:验证API逻辑(测试工程师主战场)
3️⃣ UI测试:模拟用户操作(成本高,占比最小)
💡 核心思想:
✔️ 接口测试性价比最高!
✔️ Requests库就是接口测试的"屠龙刀"!
💻 二、Requests库深度实战
1. 基础请求封装(GET/POST)
python
import requests def send_request(method, url, **kwargs): resp = requests.request(method, url, **kwargs) resp.raise_for_status() # 自动抛异常 return resp.json() # 返回JSON数据 # 使用示例 data = send_request("GET", "https://api.demo.com/user", params={"id": 1})
2. 底层方法调用逻辑
✅ Session对象:复用TCP连接,提升性能
python
session = requests.Session() session.get("https://api.demo.com/login") # 保持cookies
✅ 超时控制:避免死等
python
requests.get(url, timeout=(3, 10)) # 连接3s,读取10s
🔗 三、接口关联实战(正则+JsonPath)
1. 正则提取数据
python
import re # 从HTML提取token html = resp.text token = re.search(r'name="csrf_token" value="(.+?)"', html).group(1)
2. JsonPath定位数据
python
from jsonpath import jsonpath data = {"user": {"id": 1001, "name": "Alice"}} user_id = jsonpath(data, "$.user.id")[0] # 输出1001
🏗️ 四、框架封装核心技巧
1. 统一请求封装(重点!)
python
class ApiClient: def __init__(self, base_url): self.session = requests.Session() self.base_url = base_url def request(self, method, endpoint, **kwargs): url = f"{self.base_url}{endpoint}" return self.session.request(method, url, **kwargs) # 使用示例 client = ApiClient("https://api.demo.com") client.request("POST", "/login", json={"user": "admin"})
2. 接口关联封装
python
class UserApi(ApiClient): def login(self, username, password): resp = self.request("POST", "/login", json={"username": username, "password": password}) self.token = resp["token"] # 保存token def get_profile(self): return self.request("GET", "/profile", headers={"Authorization": self.token})
📊 五、Pytest测试框架集成
1. 用例管理
python
# test_user.py class TestUser: def test_login(self, api_client): resp = api_client.login("admin", "123456") assert resp["code"] == 200
2. Fixture实现前后置
python
import pytest @pytest.fixture def api_client(): client = ApiClient("https://api.demo.com") yield client # 测试前初始化 client.session.close() # 测试后清理
🎨 六、数据驱动实战
1. YAML测试用例
yaml
# testcases/login.yml - name: "管理员登录" request: method: POST url: "/login" data: username: "admin" password: "123456" expect: code: 200
2. 数据分离实现
python
import yaml with open("testcases/login.yml") as f: cases = yaml.safe_load(f) @pytest.mark.parametrize("case", cases) def test_login(api_client, case): resp = api_client.request(case["request"]["method"], case["request"]["url"], json=case["request"]["data"]) assert resp["code"] == case["expect"]["code"]
📈 七、Allure炫酷报告
1. 生成测试报告
bash
# 运行测试并生成报告 pytest --alluredir=./report allure serve ./report
https://example.com/allure-report.png
2. 添加用例描述
python
import allure @allure.title("测试用户登录功能") @allure.story("用户认证模块") def test_login(): ...
💼 八、企业级框架目录结构
text
api_framework/ ├── core/ # 核心封装 │ ├── client.py # ApiClient ├── testcases/ # YAML用例 ├── conftest.py # Fixture └── reports/ # Allure报告
Python+Requests接口自动化测试,从入门到持续集成,学完拿高薪!