下面给你一套 基于 CrewAI + Python + Pytest + Allure 的接口自动化测试框架设计方案,适合用于:
- 接口自动化测试
- 测试用例自动生成
- 接口文档解析
- 测试报告生成
- AI 辅助分析失败原因
- CI/CD 集成
一、技术栈
| Python | 核心开发语言 |
| Pytest | 测试执行框架 |
| Requests / httpx | 接口请求 |
| Allure | 测试报告 |
| PyYAML | YAML 测试数据管理 |
| Pydantic | 数据校验 |
| CrewAI | AI Agent 编排 |
| OpenAI / 本地大模型 | 用例生成、失败分析 |
| Jenkins / GitLab CI | 持续集成 |
二、项目目录结构
api-auto-test/
│
├── agents/ # CrewAI Agent 相关
│ ├── __init__.py
│ ├── api_case_agent.py # 接口用例生成 Agent
│ ├── api_analysis_agent.py # 失败原因分析 Agent
│ └── crew_runner.py # CrewAI 执行入口
│
├── common/ # 公共能力
│ ├── __init__.py
│ ├── logger.py # 日志封装
│ ├── yaml_util.py # YAML 读取工具
│ ├── assert_util.py # 断言封装
│ └── allure_util.py # Allure 附件封装
│
├── config/
│ ├── config.yaml # 环境配置
│ └── env.py # 环境变量读取
│
├── data/ # 测试数据
│ ├── login.yaml
│ └── user.yaml
│
├── reports/ # Allure 报告目录
│ ├── allure-results/
│ └── allure-report/
│
├── testcases/ # 测试用例
│ ├── __init__.py
│ ├── test_login.py
│ └── test_user.py
│
├── utils/
│ ├── __init__.py
│ └── request_util.py # 请求封装
│
├── conftest.py # pytest fixture
├── pytest.ini # pytest 配置
├── requirements.txt # 依赖
└── README.md
三、安装依赖
requirements.txt
pytest==8.2.2
requests==2.32.3
PyYAML==6.0.2
allure-pytest==2.13.5
crewai==0.51.1
crewai-tools==0.8.3
python-dotenv==1.0.1
pydantic==2.8.2
安装:
pip install -r requirements.txt
四、环境配置
config/config.yaml
env: test
test:
base_url: "https://jsonplaceholder.typicode.com"
timeout: 10
dev:
base_url: "https://dev.example.com"
timeout: 10
prod:
base_url: "https://api.example.com"
timeout: 10
config/env.py
import yaml
from pathlib import Path
class EnvConfig:
def __init__(self):
config_path = Path(__file__).parent / "config.yaml"
with open(config_path, "r", encoding="utf-8") as f:
self.config = yaml.safe_load(f)
self.env = self.config.get("env", "test")
self.env_config = self.config[self.env]
@property
def base_url(self):
return self.env_config["base_url"]
@property
def timeout(self):
return self.env_config.get("timeout", 10)
env_config = EnvConfig()
五、请求封装
utils/request_util.py
import requests
import allure
from config.env import env_config
class RequestUtil:
def __init__(self):
self.base_url = env_config.base_url
self.timeout = env_config.timeout
self.session = requests.Session()
def send_request(
self,
method,
url,
params=None,
json=None,
data=None,
headers=None,
**kwargs
):
full_url = self.base_url + url
with allure.step(f"请求接口:{method.upper()} {full_url}"):
response = self.session.request(
method=method,
url=full_url,
params=params,
json=json,
data=data,
headers=headers,
timeout=self.timeout,
**kwargs
)
allure.attach(
str({
"method": method,
"url": full_url,
"params": params,
"json": json,
"data": data,
"headers": headers
}),
name="请求信息",
attachment_type=allure.attachment_type.JSON
)
allure.attach(
response.text,
name="响应信息",
attachment_type=allure.attachment_type.JSON
)
return response
六、YAML 测试数据管理
common/yaml_util.py
import yaml
from pathlib import Path
def read_yaml(file_name):
file_path = Path(__file__).parent.parent / "data" / file_name
with open(file_path, "r", encoding="utf-8") as f:
return yaml.safe_load(f)
七、断言封装
common/assert_util.py
import jsonpath
def assert_status_code(response, expected_code):
assert response.status_code == expected_code, (
f"状态码断言失败,预期:{expected_code},实际:{response.status_code}"
)
def assert_json_value(response_json, json_path, expected_value):
actual_value = jsonpath.jsonpath(response_json, json_path)
assert actual_value, f"JSONPath 未匹配到数据:{json_path}"
assert actual_value[0] == expected_value, (
f"字段断言失败,JSONPath:{json_path},"
f"预期:{expected_value},实际:{actual_value[0]}"
)
如果使用上面的 jsonpath,需要增加依赖:
jsonpath==0.82.2
八、测试数据示例
data/user.yaml
– case_name: 获取用户详情成功
method: get
url: /users/1
expected:
status_code: 200
json:
– path: $.id
value: 1
– path: $.username
value: Bret
– case_name: 获取不存在用户
method: get
url: /users/999999
expected:
status_code: 404
九、Pytest 测试用例
testcases/test_user.py
import pytest
import allure
from utils.request_util import RequestUtil
from common.yaml_util import read_yaml
from common.assert_util import assert_status_code, assert_json_value
@allure.epic("接口自动化测试")
@allure.feature("用户模块")
class TestUserApi:
@pytest.mark.parametrize("case", read_yaml("user.yaml"))
def test_user_api(self, case):
allure.dynamic.title(case["case_name"])
request = RequestUtil()
response = request.send_request(
method=case["method"],
url=case["url"],
params=case.get("params"),
json=case.get("json"),
data=case.get("data"),
headers=case.get("headers")
)
expected = case["expected"]
assert_status_code(response, expected["status_code"])
if "json" in expected:
response_json = response.json()
for item in expected["json"]:
assert_json_value(
response_json,
item["path"],
item["value"]
)
十、Pytest 配置
pytest.ini
[pytest]
addopts = -s -v –alluredir=reports/allure-results
testpaths = testcases
python_files = test_*.py
python_classes = Test*
python_functions = test_*
markers =
smoke: 冒烟测试
regression: 回归测试
十一、conftest.py
import pytest
from utils.request_util import RequestUtil
@pytest.fixture(scope="session")
def api_client():
return RequestUtil()
测试用例中也可以改成:
def test_user_api(self, case, api_client):
response = api_client.send_request(...)
十二、CrewAI 接入思路
CrewAI 在这个框架中的作用不是替代 pytest,而是作为 AI 测试助手,主要负责:
十三、CrewAI Agent 示例
agents/api_case_agent.py
from crewai import Agent
api_case_agent = Agent(
role="接口自动化测试用例设计专家",
goal="根据接口文档自动生成高质量接口测试用例",
backstory="""
你是一名资深接口自动化测试专家,擅长根据接口文档、Swagger、OpenAPI、
Postman Collection 设计接口测试用例。
你需要覆盖正常场景、异常场景、边界值场景、鉴权场景和参数校验场景。
""",
verbose=True,
allow_delegation=False
)
agents/api_analysis_agent.py
from crewai import Agent
api_analysis_agent = Agent(
role="接口测试失败分析专家",
goal="根据 pytest 日志和接口响应内容分析接口测试失败原因",
backstory="""
你是一名资深测试架构师,擅长分析接口自动化测试失败原因。
你需要判断失败是由环境问题、数据问题、接口缺陷、断言错误还是自动化脚本问题导致。
""",
verbose=True,
allow_delegation=False
)
十四、CrewAI 任务编排
agents/crew_runner.py
from crewai import Crew, Task
from agents.api_case_agent import api_case_agent
from agents.api_analysis_agent import api_analysis_agent
def generate_api_cases(api_doc: str):
task = Task(
description=f"""
请根据以下接口文档生成接口自动化测试 YAML 数据。
要求:
1. 输出 YAML 格式
2. 字段包括:
– case_name
– method
– url
– headers
– params
– json
– expected
3. expected 中必须包含 status_code
4. 尽量覆盖正常、异常、边界值、鉴权失败场景
接口文档如下:
{api_doc}
""",
expected_output="符合 pytest 数据驱动格式的 YAML 测试数据",
agent=api_case_agent
)
crew = Crew(
agents=[api_case_agent],
tasks=[task],
verbose=True
)
return crew.kickoff()
def analyze_failed_case(log_text: str):
task = Task(
description=f"""
请分析以下接口自动化测试失败日志。
要求:
1. 判断失败原因类型
2. 给出失败接口
3. 给出失败断言
4. 给出可能原因
5. 给出修复建议
失败日志如下:
{log_text}
""",
expected_output="接口自动化失败分析报告",
agent=api_analysis_agent
)
crew = Crew(
agents=[api_analysis_agent],
tasks=[task],
verbose=True
)
return crew.kickoff()
十五、CrewAI 生成 YAML 用例示例
scripts/generate_cases.py
from agents.crew_runner import generate_api_cases
api_doc = """
接口名称:用户登录
请求方法:POST
请求地址:/api/login
请求头:
Content-Type: application/json
请求参数:
username string 必填 用户名
password string 必填 密码
成功响应:
{
"code": 0,
"message": "success",
"data": {
"token": "xxx"
}
}
失败响应:
{
"code": 1001,
"message": "用户名或密码错误"
}
"""
if __name__ == "__main__":
result = generate_api_cases(api_doc)
print(result)
十六、运行测试
执行 pytest
pytest
或:
pytest testcases/test_user.py
生成 Allure 报告
allure generate reports/allure-results -o reports/allure-report –clean
打开 Allure 报告
allure open reports/allure-report
十七、结合 CrewAI 分析失败日志
可以先执行:
pytest > pytest.log
然后新增脚本:
scripts/analyze_failed.py
from agents.crew_runner import analyze_failed_case
if __name__ == "__main__":
with open("pytest.log", "r", encoding="utf-8") as f:
log_text = f.read()
result = analyze_failed_case(log_text)
print(result)
运行:
python scripts/analyze_failed.py
十八、推荐执行流程
接口文档 / Swagger / OpenAPI
↓
CrewAI 生成测试场景
↓
生成 YAML 测试数据
↓
Pytest 数据驱动执行接口测试
↓
Allure 生成测试报告
↓
CrewAI 分析失败用例
↓
输出修复建议
十九、CI/CD 示例
GitLab CI 示例
stages:
– api–test
api-test:
stage: api–test
image: python:3.11
script:
– pip install –r requirements.txt
– pytest ––alluredir=reports/allure–results
artifacts:
when: always
paths:
– reports/allure–results
expire_in: 7 days
二十、框架核心优势
如果你要做成企业级版本,建议继续扩展:
登录 Token 自动管理
多环境切换
数据库断言
Redis 数据校验
接口依赖参数提取
JSON Schema 校验
失败重试
接口响应时间断言
测试数据自动清理
Swagger 自动解析
Allure 报告自动发送企业微信/钉钉
这套结构可以作为一个完整的 CrewAI + Python + Pytest + Allure 接口自动化测试框架基础模板。


