第一部分:基础篇(1-3天)
第1章:HttpRunner 4.x 核心概念
1.1 框架定位与优势
- 接口自动化测试解决方案
- 支持 HTTP/WebSocket/TCP 等多协议
- 双引擎架构(Go/Python)
- 测试即代码(TaC)理念
1.2 核心组件解析
1.3 典型工作流
录制抓包 → 转换用例 → 增强逻辑 → 执行测试 → 生成报告
第2章:环境搭建与快速开始
2.1 多平台安装指南
# Python环境(必须)
pip install httprunner==4.3.5
# hrp命令行工具(推荐)
# 下载地址:https://github.com/httprunner/httprunner/releases
2.2 创建第一个项目
hrp startproject apitest
cd apitest
tree
# 输出:
# ├── debugtalk.py
# ├── .env
# ├── reports
# ├── testcases
# └── har
2.3 执行示例测试
hrp run testcases/demo_requests.yml --html reports/first_report.html
第二部分:核心技能篇(4-10天)
第3章:YAML测试用例深度解析
3.1 测试用例结构
config:
name: "用例名称"
variables: {...}
base_url: "..."
teststeps:
- name: "步骤1"
request: {...}
extract: {...}
validate: {...}
3.2 配置模块(config)详解
- 全局变量管理
- 基础URL设置
- 超时与SSL配置
- 导出变量机制
第4章:HTTP请求与响应处理
4.1 请求定义规范
request:
url: "/api/v1/login"
method: POST
headers:
Content-Type: "application/json"
json:
username: "test"
password: "123456"
cookies:
session: "initial"
timeout: 10
4.2 文件上传实战
request:
upload:
file:
content_type: "image/png"
filename: "testdata/avatar.png"
第5章:变量管理大师
5.1 变量生命周期图谱
5.2 动态变量技巧
# debugtalk.py
import random
import datetime
def gen_order_id(prefix):
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
return f"{prefix}{timestamp}{random.randint(1000,9999)}"
第6章:断言与校验机制
6.1 基础断言类型
validate:
- eq: [status_code, 200]
- contains: [body.message, "success"]
- regex_match: [body.order_id, "^ORD\d{10}$"]
6.2 JSON Schema验证
validate:
- schema:
type: object
required: ["id", "name"]
properties:
id: {type: "integer"}
name: {type: "string", minLength: 3}
第7章:钩子函数高级应用
7.1 生命周期钩子
setup_hooks:
- ${init_test_data($user_type)}
teardown_hooks:
- ${cleanup_resources($response)}
7.2 常见场景实现
# debugtalk.py
def sign_request(request):
"""请求签名"""
import hashlib
body_str = str(request.get("json", {}))
signature = hashlib.md5(body_str.encode()).hexdigest()
request["headers"]["X-Signature"] = signature
return request
第8章:参数化数据驱动
8.1 CSV数据驱动
config:
parameters:
user-role: ${P(data/roles.csv)}
8.2 动态参数生成
parameters:
- product_id: ${get_products_from_db()}
- discount: [0.7, 0.8, 0.9, 1.0]
第9章:复杂场景设计
9.1 测试用例复用
teststeps:
- name: "用户登录"
testcase: "auth/login.yml"
export: ["auth_token"]
9.2 条件逻辑控制
- name: "支付方式检查"
if: "$payment_type == 'credit_card'"
then:
- testcase: "payment/credit_card.yml"
else:
- testcase: "payment/ewallet.yml"
第三部分:高级实战篇(11-15天)
第10章:性能测试实战
10.1 压测场景设计
hrp boom testcases/order_api.yml \
--spawn-count 100 \
--spawn-rate 10 \
--run-time 5m \
--output reports/load_test
10.2 性能监控指标
- 响应时间分布
- 吞吐量(RPS)
- 错误率
- 资源利用率
第11章:持续集成
11.1 Jenkins集成
pipeline {
stages {
stage('API Test') {
steps {
sh 'hrp run testcases/ --html reports/report.html'
publishHTML target: [
allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true,
reportDir: 'reports',
reportFiles: 'report.html',
reportName: 'API Test Report'
]
}
}
}
}
11.2 GitLab CI配置
api-test:
image: python:3.10
script:
- pip install httprunner
- hrp run testcases/ --html reports/report.html
artifacts:
paths:
- reports/
第12章:自定义扩展开发
12.1 自定义报告模板
hrp run -r --template custom_report.html
12.2 开发协议插件
// 实现 ProtocolHandler 接口
type MyProtocol struct{}
func (p *MyProtocol) Name() string {
return "my_protocol"
}
func (p *MyProtocol) Connect() error {
// 自定义连接逻辑
}
第四部分:企业级应用(16-20天)
第13章:测试框架设计
13.1 分层架构设计
project/
├── api/ # 接口定义层
│ ├── user.yml
│ └── product.yml
├── testcases/ # 测试用例层
│ ├── user/
│ └── order/
├── testsuites/ # 测试套件层
│ ├── smoke.yml
│ └── regression.yml
└── utils/ # 工具层
├── db_client.py
└── crypto.py
13.2 数据驱动工厂模式
# utils/data_factory.py
class DataFactory:
@classmethod
def create_user(cls, role="normal"):
if role == "vip":
return {"level": 3, "discount": 0.8}
else:
return {"level": 1, "discount": 1.0}
第14章:安全测试集成
14.1 OWASP ZAP集成
setup_hooks:
- ${start_zap_proxy()}
teststeps:
- name: "安全扫描"
request:
url: "/api/v1/user"
proxy: "http://localhost:8080"
teardown_hooks:
- ${generate_zap_report()}
14.2 敏感数据防护
# debugtalk.py
from cryptography.fernet import Fernet
def encrypt_data(data):
cipher = Fernet(os.getenv("ENCRYPT_KEY"))
return cipher.encrypt(data.encode()).decode()
def decrypt_data(encrypted):
cipher = Fernet(os.getenv("ENCRYPT_KEY"))
return cipher.decrypt(encrypted.encode()).decode()
第15章:最佳实践与优化
15.1 性能优化技巧
- 使用 HTTP/2 复用连接
- 启用请求缓存
- 并行执行测试套件
15.2 稳定性保障
- 自动重试机制
- 熔断器模式实现
- 环境健康检查
第五部分:扩展资源
附录A:调试技巧大全
# 调试模式运行
hrp run test.yml --log-level debug --pause-on-failure
# 生成cURL命令
hrp run test.yml --curl
# 变量追踪
teardown_hooks:
- ${log_vars()}
附录B:常见问题解决方案
问题类型 | 现象 | 解决方案 |
---|---|---|
变量未定义 | “token” not found | 检查extract路径,确认前置步骤已导出 |
环境配置错误 | SSL证书验证失败 | config中设置verify: false |
依赖缺失 | funppy模块错误 | pip install funppy==0.5.0 |
权限问题 | 无法删除报告目录 | 使用takeown/icacls获取所有权 |
附录C:学习资源推荐
- 官方文档:https://httprunner.com/
- 示例项目:https://github.com/httprunner/examples
- 社区论坛:https://community.httprunner.org/
- 实战课程:《HttpRunner 4.x企业级自动化测试实战》
学习路线建议
阶段式学习计划
阶段 | 时间 | 重点 | 产出物 |
---|---|---|---|
基础掌握 | 1周 | 环境搭建、用例编写、报告分析 | 10个基础接口测试用例 |
核心技能 | 2周 | 变量管理、数据驱动、钩子函数 | 电商下单全链路测试 |
高级实战 | 1周 | 性能测试、CI/CD集成 | Jenkins流水线配置 |
企业应用 | 1周 | 框架设计、安全测试 | 可复用测试框架 |
推荐练习项目
- 电商系统API测试
- 用户管理
- 商品服务
- 订单流程
- 支付系统
- IoT设备接口测试
- 设备注册
- 状态上报
- 指令下发
- 固件升级
- 金融系统安全测试
- 加密接口测试
- 权限验证
- 敏感数据防护
能力评估标准
级别 | 能力要求 |
---|---|
初级 | 能编写基础接口测试用例 |
中级 | 实现数据驱动和复杂场景 |
高级 | 设计测试框架并集成CI/CD |
专家 | 开发自定义插件和协议支持 |
本手册提供完整的知识体系和实操路径,建议配合官方文档和示例代码进行实践。每章结束后完成实战练习,逐步构建企业级自动化测试解决方案。