# auto_project **Repository Path**: beyond_my/auto_project ## Basic Information - **Project Name**: auto_project - **Description**: No description available - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-12-27 - **Last Updated**: 2026-02-09 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # TestRunner 基于 YAML 配置驱动的自动化测试框架,支持 HTTP API、数据库、性能测试。 > 📚 **[完整功能清单和使用指南 →](FEATURES.md)** > 🎉 **[最新优化说明 →](OPTIMIZATION_SUMMARY.md)** > 📝 **[版本变更记录 →](docs/CHANGELOG.md)** > 🚀 **[执行模式详解 →](docs/EXECUTION_MODES.md)** > 📋 **[功能总结 →](docs/FINAL_SUMMARY.md)** > 🔧 **[优化报告 →](docs/OPTIMIZATION_REPORT.md)** > 🚀 **[快速查看功能 →](./show_features.sh)** > 🧹 **[项目清理指南 →](CLEANUP_GUIDE.md)** > 🐍 **[Python 兼容性 →](PYTHON_COMPATIBILITY.md)** ## ✨ 核心特性 - 📝 **YAML 配置** - 简单易懂的测试用例编写 - 🚀 **多模式** - 支持 Pytest、Locust 性能测试 - 🔧 **Hook 机制** - 全生命周期钩子,支持步骤级、成功/失败回调 - ⚡ **大规模并发** - 性能优化,支持千级并发执行 - 📦 **数据库测试** - 原生支持 SQLite/MySQL - ☁️ **云原生** - 内置阿里云 SDK 集成 - 📊 **丰富报告** - Allure 企业级测试报告 - 🔄 **数据驱动** - 支持 CSV/Excel/JSON 数据源 - 🎯 **智能断言** - Python 表达式、JSON Schema 校验 ## 🚀 快速开始 ### 安装 ```bash # 🌟 推荐:一键有母安装(自动克隆 + 安装) curl -fsSL https://gitee.com/beyond_my/auto_project/raw/master/download_and_install.sh | bash ``` 更多安装方式:[📚 QUICK_INSTALL.md](QUICK_INSTALL.md) ### 启动 Mock Server ```bash cd mock_server && python app.py ``` ### 运行测试 ```bash # 🌟 推荐:使用 pytest 直接运行 YAML 测试 pytest features/01_basic -vs # 或者:运行单个测试 testrunner run tests/01_basic/test_simple_get.yaml # 或者:直接执行 YAML 文件 python3 -m testrunner.cli_yaml_runner features/01_basic/e2e/test_02_product.yaml # 或者:使用链式构建器 python3 -c "from testrunner.http_testcase import TestCaseBuilder; (TestCaseBuilder('测试', 'http://localhost:5050').step('健康检查', 'GET', '/api/health').expect_status(200).run())" ``` ### 第一个测试用例 ```yaml config: name: "我的第一个测试" base_url: "http://localhost:5050" teststeps: - name: "检查健康状态" request: method: GET url: /api/health validate: - "$.code == 200, 状态码正确" - "$.data.status == 'ok', 服务正常" ``` 📚 **详细教程**:[5分钟快速开始](docs/QUICK_START.md) --- ## 📦 功能模块 | 模块 | 说明 | 文档 | 示例 | |-----|------|------|------| | 🎯 **基础功能** | HTTP API测试、变量提取、断言 | [查看文档](features/01_basic/README.md) | [YAML示例](features/01_basic/example_simple.yaml) | | 🎲 **智能数据生成** | 多地区、自定义模板、智能推荐 | [查看文档](features/02_smart_data_generator/README.md) | [Python示例](features/02_smart_data_generator/demo.py) | | 🤖 **测试用例生成** | 自动生成、cURL转换、HAR解析 | [查看文档](features/03_testcase_generator/README.md) | [命令示例](features/03_testcase_generator/README.md#快速开始) | | 🗄️ **数据库测试** | MySQL/SQLite支持、SQL验证 | [查看文档](features/04_database/README.md) | [YAML示例](features/04_database/) | | ⚡ **性能测试** | Locust集成、大规模并发 | [查看文档](features/05_performance/README.md) | [使用指南](features/05_performance/README.md#快速开始) | | 🔄 **增强重试** | 智能重试、指数退避 | [查看文档](features/06_enhanced_retry/README.md) | [YAML示例](features/06_enhanced_retry/) | | 🏭 **数据管理** | 数据工厂、自动清理 | [查看文档](features/07_data_management/README.md) | [YAML示例](features/07_data_management/) | | 📊 **性能监控** | 瓶颈检测、统计分析 | [查看文档](features/08_monitoring/README.md) | [YAML示例](features/08_monitoring/) | | 🔧 **HAR/OpenAPI** | HAR解析、OpenAPI导入 | [查看文档](features/09_har_openapi/README.md) | [命令示例](features/09_har_openapi/README.md#快速开始) | | 🔄 **YAML转换** | YAML转Python链式代码 | [查看文档](docs/YAML_TESTING_GUIDE.md#yaml-转-python-工具) | [示例目录](features/12_yaml_conversion_examples/) | > 💡 **提示**:每个功能模块都包含完整的文档说明、YAML配置示例和Python编程示例。 --- ### YAML 转 Python 工具 🆕🔥 将 YAML 测试用例转换为 Python 链式调用代码,支持所有高级功能。 #### 支持的功能 | 功能 | YAML 字段 | 转换支持 | |------|-----------|----------| | 基础请求 | `request` | ✅ | | 断言 | `validate` | ✅ | | 变量提取 | `extract` | ✅ | | 重试策略 | `retry` | ✅ | | 异步轮询 | `poll_until` | ✅ | | 条件执行 | `run_if` | ✅ | | 循环执行 | `run_while` | ✅ | | 并发分组 | `concurrent_group` | ✅ | | 单步骤并发 | `parallel: true` | ✅ | | 步骤依赖 | `wait_for` | ✅ | | 步骤超时 | `timeout` | ✅ | #### 转换命令 ```bash # 预览转换结果 python3 -m testrunner.yaml2builder test.yaml -p # 生成 Python 文件 python3 -m testrunner.yaml2builder test.yaml # 生成并运行 python3 -m testrunner.yaml2builder test.yaml -r # 批量转换目录 python3 tools/yaml_to_builder.py features/01_basic/e2e --batch -o generated/ ``` #### 转换对照表 | YAML 字段 | Python 链式方法 | |-----------|------------------| | `run_if: {$.code: 200}` | `.run_if({"$.code": 200})` | | `run_if.conditions[].op: eq` | `.if_eq(path, value)` | | `run_if` + `run_while` | 条件+循环组合使用 | | `run_while: {...}` | `.run_while({...})` | | `run_while.max_iterations` | `.while_max(n)` | | `run_while.updates` | `.while_update(var, expr)` | | `poll_until.condition` | `.poll_until({...})` | | `poll_until.start_condition` | `.poll_if({...})` | | `poll_until.poll_request.url` | `.poll_url("...")` | | `poll_until.poll_request.method: POST` | `.poll_method("POST")` | | `poll_until.poll_request.body` | `.poll_body({...})` | | `config.locust` | Locust 性能测试配置 | | `config.locust.distributed` | 分布式配置 (master_host, expect_workers) | | `config.locust.shape` | 负载形状 (stages, spike, ramp) | | `config.locust.report` | 报告配置 (html, csv) | | `on_start: true` | 用户启动时执行 (如登录) | | `on_stop: true` | 用户结束时执行 (如登出) | | `step.weight` | `.weight(n)` 任务权重 | | `step.tag` | 标签,支持 --tags 过滤 | **Locust 转换命令**: ```bash # 转换为 Locust 性能测试文件 python3 -m testrunner.yaml2builder test.yaml --locust # 运行 Locust (单机 headless) locust -f test_locust.py --headless -u 100 -r 10 -t 2m # 运行 Locust (分布式 Master) locust -f test_locust.py --master --expect-workers=4 ``` 📚 **完整文档**:[docs/YAML_TESTING_GUIDE.md](docs/YAML_TESTING_GUIDE.md#yaml-转-python-工具) --- ## 📊 性能监控与分析 🆕🔥 TestRunner 提供了**企业级的性能监控**,自动识别性能瓶颈和优化建议。 ### 🎯 核心特性 - ✅ **实时监控** - 自动记录每个步骤执行时间 - ✅ **瓶颈检测** - 智能识别慢步骤(固定+动态阈值) - ✅ **统计分析** - P50/P90/P95/P99分位数、平均值、成功率 - ✅ **优化建议** - 根据性能数据提供改进建议 - ✅ **Allure集成** - 性能数据自动附加到测试报告 ### 📚 快速使用 #### 零配置自动启用 ```yaml config: name: "性能测试" base_url: "http://localhost:5050" performance_threshold_ms: 1000 # 可选:自定义慢步骤阈值 teststeps: - name: "快速接口" request: method: GET url: /api/health - name: "慢速接口" request: method: POST url: /api/sleep json: delay: 1.5 ``` #### 性能报告示例 ``` 📊 Performance Summary ================================================================================ Total Duration: 2076.64ms Total Steps: 4 | Successful: 3 | Failed: 1 Avg: 518.56ms | P50: 519.24ms | P95: 1020.40ms 🐌 Performance Bottlenecks: 1. 慢速接口: avg=1021ms, p95=1021ms, count=1 💡 Monitor for consistent slow behavior 2. 中速接口: avg=1016ms, p95=1016ms, count=1 💡 Review HTTP request configuration ⏱️ Top 5 Slowest Steps: 1. 慢速接口: 1021.14ms 2. 中速接口: 1016.22ms 3. 快速接口: 22.27ms ================================================================================ ``` 📚 **完整指南**:[docs/PERFORMANCE_MONITORING.md](docs/PERFORMANCE_MONITORING.md) --- ## 🏭 测试数据管理 🆕🔥 TestRunner 提供了**强大的测试数据管理**,自动生成、清理和隔离测试数据。 ### 🎯 核心特性 - ✅ **数据工厂** - 自动生成User/Order/Product等测试数据 - ✅ **自动清理** - 测试结束后自动清理临时数据 - ✅ **数据隔离** - 按类型、标签分组管理 - ✅ **快照回滚** - 支持数据快照和恢复 - ✅ **随机值** - 自动生成真实的随机数据 ### 📚 快速使用 #### 1. 使用内置函数 ```yaml config: name: "测试数据管理" variables: # 自动生成测试数据 test_user: ${create_test_user()} test_order: ${create_test_order(user_id='user123')} test_product: ${create_test_product()} teststeps: - name: "创建用户" request: method: POST url: /api/users json: id: ${test_user['id']} username: ${test_user['username']} email: ${test_user['email']} ``` #### 2. 自动生成的数据示例 ```python # create_test_user() 生成 { "id": "test_user_a1b2c3d4", "username": "test_user_a1b2c3d4", "email": "test_user_a1b2c3d4@example.com", "phone": "13812345678", "age": 25, "status": "active" } # create_test_order(user_id='user123') 生成 { "id": "test_order_123abc456def", "order_no": "ORD17668145921234", "user_id": "user123", "amount": 199.99, "status": "pending" } # create_test_product() 生成 { "id": "test_product_x9y8z7w6", "name": "Product test_product_x9y8z7w6", "price": 99.99, "stock": 50 } ``` #### 3. 自定义字段 ```yaml variables: vip_user: ${create_test_user(username='vip_user', age=30)} large_order: ${create_test_order(amount=9999.99)} special_product: ${create_test_product(price=1.99, stock=1000)} ``` 📚 **完整指南**:[docs/TEST_DATA_MANAGEMENT.md](docs/TEST_DATA_MANAGEMENT.md) --- ## 🎯 智能断言增强 🆕🔥 TestRunner 提供了**更友好的智能断言**,自动分析错误原因并提供修复建议。 ### 🎯 核心特性 - ✅ **类型不匹配提示** - 智能检测类型差异并提供转换建议 - ✅ **值差异分析** - 详细分析字符串、数字、列表、对象的差异 - ✅ **可视化Diff** - 生成unified diff格式的对比 - ✅ **自动修复建议** - 提供可直接应用的修复方案 - ✅ **上下文信息** - 包含缺失字段、多余字段、索引差异等 ### 📚 快速使用 #### 零配置自动启用 断言失败时自动生成详细错误信息: ```yaml teststeps: - name: "测试用户信息" request: method: GET url: /api/user/1 validate: - "$.data.age == 25, '年龄检查'" ``` #### 错误提示示例 **类型不匹配**: ``` ❌ Assertion failed: $.data.age == 25 Expected: 25 (int) Actual: "25" (str) 💡 Suggestion: Type mismatch - convert string to int 🔧 Auto-fix: int(actual_value) ``` **字符串差异**: ``` ❌ Assertion failed: $.data.email == 'test@example.com' Expected: test@example.com Actual: TEST@EXAMPLE.COM 📊 Diff: - test@example.com + TEST@EXAMPLE.COM 💡 Suggestion: String case mismatch 🔧 Auto-fix: actual_value.lower() ``` **对象差异**: ``` ❌ Assertion failed: $.data == expected_user 📊 Missing fields: ['level', 'vip_status'] 📊 Extra fields: ['temp_field'] 💡 Suggestion: Object structure mismatch 🔧 Check if API response changed ``` ### 🎓 支持的断言类型 | 类型 | 功能 | 示例 | |------|------|------| | **相等断言** | 智能类型检测 | `$.data.id == 123` | | **包含断言** | 字符串/列表包含 | `'admin' in $.data.roles` | | **长度断言** | 长度不匹配分析 | `len($.data.items) == 5` | ### 💡 特色功能 1. **自动类型转换建议** - 检测到 `"25"` vs `25` → 建议 `int(value)` - 检测到 `"true"` vs `true` → 建议 `bool(value)` 2. **智能字符串比对** - 大小写差异 → 建议 `.lower()` 或 `.upper()` - 空白字符差异 → 建议 `.strip()` - 相似度分析 → 高亮具体差异位置 3. **结构化数据对比** - 自动识别缺失字段 - 自动识别多余字段 - JSON diff 可视化 📚 **代码实现**:[testrunner/core/smart_assertion.py](testrunner/core/smart_assertion.py) --- ## 📹 API录制增强 🆕🔥 TestRunner 提供了**智能的API录制器**,自动生成高质量测试用例。 ### 🎯 核心特性 - ✅ **智能过滤** - 自动过滤健康检查、静态资源等噪音请求 - ✅ **自动分组** - 按URL路径智能分组为测试场景 - ✅ **去重优化** - 智能去除重复请求 - ✅ **变量提取** - 自动提取ID、Token等可复用变量 - ✅ **自动断言** - 根据响应生成合理的断言 ### 📚 快速使用 #### 使用录制器生成测试用例 ```python from testrunner.core.recorder_enhanced import EnhancedRecorder recorder = EnhancedRecorder() # 添加录制的API请求 recorder.add_record({ 'method': 'POST', 'url': 'http://api.example.com/api/users/login', 'headers': {'Content-Type': 'application/json'}, 'body': {'username': 'test', 'password': '123456'}, 'status_code': 200, 'response_body': { 'code': 200, 'data': {'user_id': 12345, 'token': 'abc123'} } }) # 生成测试用例 testcase = recorder.generate_testcase( testcase_name="用户登录流程", output_file="test_login.yaml" ) ``` #### 生成的测试用例示例 ```yaml config: name: "用户登录流程" base_url: "http://api.example.com" variables: # 自动提取的变量 user_id: 12345 token: "abc123" teststeps: - name: "用户登录" request: method: POST url: /api/users/login headers: Content-Type: application/json json: username: "test" password: "123456" extract: # 自动生成的提取规则 - user_id: $.data.user_id - token: $.data.token validate: # 自动生成的断言 - "$.code == 200, '状态码正确'" - "$.data.user_id != null, '用户ID存在'" - "$.data.token != null, 'Token存在'" ``` ### 💡 智能特性 #### 1. 自动过滤噪音 过滤以下类型的请求: - 健康检查:`/health`, `/ping`, `/metrics` - 静态资源:`.js`, `.css`, `.png`, `.jpg` - 监控埋点:`/track`, `/analytics` #### 2. 场景智能分组 ``` 场景1: 用户管理 (/api/users/*) - POST /api/users/login - GET /api/users/{id} - PUT /api/users/{id} 场景2: 订单管理 (/api/orders/*) - POST /api/orders - GET /api/orders/{id} - PUT /api/orders/{id}/status ``` #### 3. 变量自动提取 自动识别并提取: - ID类:`user_id`, `order_id`, `product_id` - Token类:`token`, `access_token`, `session_id` - 时间戳:`timestamp`, `created_at` #### 4. 智能断言生成 根据响应自动生成: - 状态码检查:`$.code == 200` - 必填字段检查:`$.data.id != null` - 数据类型检查:`type($.data.amount) == float` ### 🎓 高级功能 #### 请求去重 ```python recorder = EnhancedRecorder() recorder.enable_deduplication = True # 相同的GET请求只保留一次 recorder.add_record({...}) # 第一次,保留 recorder.add_record({...}) # 相同请求,自动忽略 ``` #### 变量复用 ```python # 从第一个请求中提取token # 自动在后续请求中使用 ${token} recorder.auto_extract_variables = True ``` ### 📊 实际效果对比 | 特性 | 手工编写 | EnhancedRecorder | |------|----------|------------------| | 编写时间 | 30分钟 | 1分钟 | | 变量提取 | 手动识别 | ✅ 自动提取 | | 断言生成 | 手动编写 | ✅ 自动生成 | | 去重 | 手动检查 | ✅ 自动去重 | | 场景分组 | 手动组织 | ✅ 智能分组 | | 噪音过滤 | 手动删除 | ✅ 自动过滤 | ### 🚀 快速测试 ```bash # 运行录制器演示 cd tests/20_enhanced_recorder python3 demo_recorder.py # 查看生成的测试用例 cat tests/20_enhanced_recorder/generated_testcase.yaml ``` 📚 **代码实现**:[testrunner/core/recorder_enhanced.py](testrunner/core/recorder_enhanced.py) --- ## 🔍 失败分析与自愈 🆕🔥 TestRunner 提供了**智能的失败分析器**,自动识别错误原因并提供自愈策略。 ### 🎯 核心特性 - ✅ **智能分类** - 自动识别失败类型(网络、超时、服务器错误等) - ✅ **根因分析** - 自动分析失败根本原因 - ✅ **自愈策略** - 提供7种自愈策略(重试、刷新Token、清除缓存等) - ✅ **失败模式检测** - 检测频繁出现的错误模式 - ✅ **修复建议** - 提供可操作的修复建议 ### 📚 快速使用 #### 零配置自动启用 测试失败时自动分析: ```yaml config: name: "失败分析测试" base_url: "http://localhost:5050" teststeps: - name: "超时测试" request: method: POST url: /api/sleep json: delay: 5 timeout: 1 ``` #### 分析结果示例 ``` 🔍 失败分析: 请求超时 💡 建议: 请求超时。建议:增加超时时间或优化接口性能。 ✅ 系统将等待后自动重试 📊 Failure Analysis Summary ================================================================================ Total Failures: 5 📊 Failure Categories: - timeout: 1 (20.0%) - server_error: 1 (20.0%) - authentication: 1 (20.0%) - rate_limit: 1 (20.0%) - assertion: 1 (20.0%) 🔧 Self-Healing Statistics: - retry_with_backoff: 2/2 (100.0% success rate) - wait_and_retry: 1/1 (100.0% success rate) ================================================================================ ``` ### 📈 支持的失败类型 | 失败类型 | 检测模式 | 自愈策略 | |---------|---------|----------| | **网络错误** | Connection refused/reset | 指数退避重试 | | **超时** | Timeout/TimeoutError | 等待后重试 | | **服务器错误** | 500/502/503/504 | 指数退避重试 | | **认证失败** | 401/403/Token expired | 刷新Token | | **限流** | 429/Rate limit | 等待后重试 | | **客户端错误** | 400/404 | 人工介入 | | **数据错误** | JSON decode error | 清除缓存 | | **断言失败** | Assertion failed | 人工介入 | ### 💡 自愈策略 1. **自动重试** (RETRY) - 简单重试,适用于临时性错误 2. **指数退避重试** (RETRY_WITH_BACKOFF) - 重试间隔递增,适用于网络、服务器错误 3. **刷新Token** (REFRESH_TOKEN) - 自动刷新认证Token,适用于认证过期 4. **清除缓存** (CLEAR_CACHE) - 清除本地缓存,适用于数据错误 5. **等待后重试** (WAIT_AND_RETRY) - 等待一段时间后重试,适用于超时、限流 6. **跳过** (SKIP) - 跳过当前步骤,继续后续测试 7. **人工介入** (MANUAL) - 需要人工处理,不可自动修复 ### 🚀 快速测试 ```bash # 运行失败分析测试 testrunner run tests/21_failure_analysis/test_failure_analysis.yaml ``` 📚 **代码实现**:[testrunner/core/failure_analyzer.py](testrunner/core/failure_analyzer.py) --- ## 🌐 分布式追踪 🆕🔥 TestRunner 提供了**完整的分布式追踪**,支持W3C Trace Context标准。 ### 🎯 核心特性 - ✅ **W3C标准** - 支持W3C Trace Context协议 - ✅ **Trace ID传播** - 自动在请求头中注入trace ID - ✅ **Span管理** - 自动创建和管理span - ✅ **父子关系** - 自动维护span的父子关系 - ✅ **多格式导出** - 支持Jaeger、Zipkin格式导出 ### 📚 快速使用 #### 1. 配置服务名 ```yaml config: name: "分布式追踪测试" base_url: "http://localhost:5050" service_name: "test-service" # 设置服务名 ``` #### 2. 自动追踪 每个请求自动注入trace上下文: ```http GET /api/orders/123 HTTP/1.1 Host: api.example.com traceparent: 00-a58daa6817eb45cc-b6e9c87a4f3d2e1b-01 tracestate: testrunner=test-service ``` #### 3. 追踪可视化 ``` 🔍 Distributed Tracing Summary ================================================================================ Trace ID: a58daa6817eb45cc... Total Spans: 7 Total Duration: 234.56ms Success Rate: 100.0% Slowest Span: POST /api/orders (89.23ms) 📊 Span Distribution: - internal: 1 - client: 6 🔍 Trace Visualization: a58daa6817eb45cc... ================================================================================ ✅ 分布式追踪测试 [234.56ms] (internal) ✅ POST /api/login [56.75ms] (client) ✅ GET /api/user/1 [23.45ms] (client) ✅ POST /api/orders [89.23ms] (client) ✅ GET /api/orders/123 [18.92ms] (client) ✅ PUT /api/orders/123/status [21.34ms] (client) ✅ GET /api/users/1/orders [24.87ms] (client) ================================================================================ ``` ### 📋 支持的Span类型 | Span类型 | 说明 | 使用场景 | |----------|------|----------| | CLIENT | 客户端请求 | HTTP调用、gRPC请求 | | SERVER | 服务端处理 | API服务处理 | | PRODUCER | 消息生产者 | 发送MQ消息 | | CONSUMER | 消息消费者 | 接收MQ消息 | | INTERNAL | 内部处理 | 内部逻辑处理 | ### 📊 导出格式 #### 1. Jaeger格式 ```python from testrunner.core.distributed_tracer import get_tracer tracer = get_tracer() jaeger_data = tracer.export_jaeger_format(trace_id) ``` #### 2. Zipkin格式 ```python zipkin_data = tracer.export_zipkin_format(trace_id) ``` #### 3. 树形结构 ```python trace_tree = tracer.get_trace_tree(trace_id) ``` ### 🎓 最佳实践 1. **设置服务名** ```yaml config: service_name: "user-service" # 设置有意义的服务名 ``` 2. **微服务场景** - Trace ID会自动传播到下游服务 - 支持跨服务追踪 3. **性能分析** - 通过span的duration分析性能瓶颈 - 找到最慢的服务调用 4. **故障排查** - 通过trace链路定位错误位置 - 查看请求在哪个服务失败 ### 🚀 快速测试 ```bash # 运行分布式追踪测试 testrunner run tests/22_distributed_tracing/test_distributed_tracing.yaml ``` 📚 **代码实现**:[testrunner/core/distributed_tracer.py](testrunner/core/distributed_tracer.py) --- ## 🤖 AI辅助测试 🆕🔥 TestRunner 提供了**智能的AI辅助测试**,自动生成测试用例和断言建议。 ### 🎯 核心特性 - ✅ **智能分析** - 自动识别27种API类型(CRUD、认证、上传、支付等) - ✅ **断言推荐** - 基于响应结构智能推荐断言 - ✅ **用例生成** - 自动生成36+种测试场景(正常、异常、边界、安全、并发) - ✅ **结果分析** - AI分析测试结果并提供洞察 - ✅ **自动修复** - 为失败的测试提供修复建议 - ✅ **OpenAPI支持** - 从OpenAPI/Swagger规范自动生成测试 🆕 - ✅ **HAR支持** - 从浏览器录制的HAR文件生成测试 🆕 ### 📚 快速使用 #### 1. 分析API端点 ```bash # 分析GET请求 python -m testrunner.ai analyze-api --method GET --url /api/users/123 # 分析POST请求 python -m testrunner.ai analyze-api --method POST --url /api/users ``` **输出示例**: ``` 🤖 AI API Analysis: GET /api/users/123 ================================================================================ 📌 API Type: crud.read ✅ Recommended Assertions (3): 1. $.code == 200 Confidence: 90% | Category: status 💡 Common practice for crud.read APIs 2. $.data != null Confidence: 90% | Category: status 3. $.data.id != null Confidence: 90% | Category: status 📋 Generated Test Cases (3): 1. Test GET 123 - Success Priority: HIGH | Confidence: 95% 2. Test GET 123 - Unauthorized Priority: MEDIUM | Confidence: 90% 3. Test GET 123 - Not Found Priority: MEDIUM | Confidence: 85% 💡 Recommendations: ✅ Consider testing pagination for list endpoints ✅ Add tests for sorting and filtering ✅ Add performance tests for critical paths ================================================================================ ``` #### 2. 自动生成测试用例 ```bash # 生成YAML测试用例 python -m testrunner.ai generate-tests \ --method POST \ --url /api/users \ --output tests/23_ai_generated/test_users.yaml # 运行生成的测试 testrunner run tests/23_ai_generated/test_users.yaml ``` **生成的测试用例**: ```yaml config: name: "AI Generated Test Cases" base_url: "http://localhost:5050" teststeps: - name: "Test POST users - Success" request: method: POST url: /api/users validate: - "$.code == 200" - "$.data != null" - name: "Test POST users - Missing Required Fields" request: method: POST url: /api/users validate: - "$.code in [400, 422]" - "$.message != null" - name: "Test POST users - Unauthorized" request: method: POST url: /api/users validate: - "$.code in [401, 403]" ``` #### 3. 分析测试结果 ```bash # 分析测试结果 python -m testrunner.ai analyze-results --results-file results.json ``` **分析报告示例**: ``` 🤖 AI Test Analysis Summary ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Total Tests: 10 Passed: 8 (80.0%) Failed: 2 Risk Level: MEDIUM ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🔍 Issues Detected: ⚠️ 1 tests failed due to timeout - consider increasing timeout ⚠️ 1 tests failed due to authentication - verify token validity 💡 Suggestions: 🟡 Warning: Pass rate below 80% - investigate failures 💡 Focus on stabilizing failing tests 💡 Consider implementing retry strategies 📊 Coverage Gaps: ⚠️ Missing HTTP methods: DELETE, PATCH ``` ### 📊 支持的API类型识别 | API类型 | 识别模式 | 自动断言 | |---------|----------|----------| | **CRUD - Create** | POST /api/xxx | code==200/201, data.id!=null | | **CRUD - Read** | GET /api/xxx/{id} | code==200, data!=null, data.id!=null | | **CRUD - Update** | PUT/PATCH /api/xxx/{id} | code==200, message contains success | | **CRUD - Delete** | DELETE /api/xxx/{id} | code==200/204 | | **CRUD - List** | GET /api/xxx | code==200, type(data)==list | | **Auth - Login** | POST /login | code==200, data.token!=null | | **Auth - Logout** | POST /logout | code==200 | ### 🎓 断言推荐类型 1. **状态断言** - HTTP状态码检查 - 响应code字段检查 2. **数据存在性** - 字段非空检查 - 必填字段检查 3. **数据类型** - 字段类型检查 - 列表/对象结构检查 4. **数据值** - 字段值比较 - 范围检查 - 枚举值检查 5. **业务逻辑** - 时间戳检查 - 状态机检查 - 关联数据检查 ### 💡 最佳实践 1. **提供响应示例** ```bash # 保存响应到JSON文件 curl http://localhost:5050/api/users/1 > response.json # 使用响应示例生成更准确的断言 python -m testrunner.ai analyze-api \ --method GET \ --url /api/users/1 \ --response-file response.json ``` 2. **批量生成测试** - 为每个API端点生成测试用例 - 覆盖正常和异常场景 - 自动补充边界值测试 3. **持续优化** - 定期分析测试结果 - 根据AI建议优化测试 - 补充缺失的测试场景 ### 🚀 快速测试 ```bash # 1. 分析API python -m testrunner.ai analyze-api --method GET --url /api/users # 2. 生成测试用例 python -m testrunner.ai generate-tests \ --method GET \ --url /api/users \ --output tests/23_ai_generated/test_users_list.yaml # 3. 从OpenAPI生成测试 🆕 python -m testrunner.ai generate-from-openapi \ --spec-file openapi.json \ --output-dir tests/openapi_generated # 4. 从HAR文件生成测试 🆕 python -m testrunner.ai generate-from-har \ --har-file recording.har \ --output-dir tests/har_generated # 5. 运行测试 testrunner run tests/23_ai_generated/test_users_list.yaml ``` --- ### 📚 方式1:从OpenAPI/Swagger规范生成 🆕🔥 **适用场景**:API设计阶段、有完整的API文档 #### 核心优势 - ✅ **自动解析Schema** - 从规范中提取请求/响应结构 - ✅ **智能生成断言** - 根据Schema约束自动生成断言 - ✅ **自动生成测试数据** - 基于类型和格式生成合适的测试数据 - ✅ **依赖关系分析** - 自动识别接口间的依赖 - ✅ **支持OpenAPI 3.0 & Swagger 2.0** #### 快速使用 ```bash # 基础使用 python -m testrunner.ai generate-from-openapi \ --spec-file openapi.json \ --output-dir tests/api_tests # 自定义配置 python -m testrunner.ai generate-from-openapi \ --spec-file openapi.yaml \ --output-dir tests/custom \ --max-cases 30 \ --priority high \ --no-boundary # 运行生成的测试 testrunner run tests/api_tests/test_all.yaml ``` #### 生成效果示例 **输入**:5个API端点的OpenAPI规范 **输出**:83个完整的测试用例 ```yaml # 自动生成的测试用例 config: name: "User Management Tests" base_url: "http://localhost:8080" teststeps: - name: "Test POST users - Success" request: method: POST url: /api/v1/users json: username: test_value # 自动生成 email: test@example.com # 识别email格式 age: 1 # 使用minimum值 validate: - "$.code == 201" # 基于Schema - "type($.data.email) == str" # 类型断言 - "$.data.email contains '@'" # 格式断言 - "$.data.age >= 1" # 范围断言 - "len($.data.username) >= 3" # 长度断言 ``` **支持的OpenAPI特性**: - ✅ JSON Schema(类型、约束、格式) - ✅ requestBody(自动生成测试数据) - ✅ responses(自动生成断言) - ✅ required字段、enum、format、minLength/maxLength、minimum/maximum --- ### 🌐 方式2:从浏览器HAR录制生成 🆕🔥 **适用场景**:已有系统回归测试、快速生成真实场景测试 #### 核心优势 - ✅ **真实数据** - 使用录制的真实请求和响应 - ✅ **自动提取认证** - 自动提取Authorization、Token等 - ✅ **基于真实响应的断言** - 更准确的断言 - ✅ **智能过滤** - 自动过滤静态资源、健康检查 - ✅ **依赖分析** - 基于时间顺序和参数传递分析依赖 #### 快速使用 **步骤1:录制HAR文件** 1. 打开Chrome DevTools(F12) 2. 切换到 **Network** 标签页 3. 执行业务操作(登录、创建、查询等) 4. 右键点击请求列表 → **Save all as HAR** **步骤2:生成测试** ```bash # 基础使用 python -m testrunner.ai generate-from-har \ --har-file recording.har \ --output-dir tests/api_tests # 过滤特定域名 python -m testrunner.ai generate-from-har \ --har-file recording.har \ --filter-domain api.example.com \ --output-dir tests/api_tests # 自定义配置 python -m testrunner.ai generate-from-har \ --har-file recording.har \ --output-dir tests/custom \ --max-cases 20 \ --priority high # 运行生成的测试 testrunner run tests/api_tests/test_all.yaml ``` #### 生成效果示例 **输入**:5个录制的HTTP请求 **输出**:109个完整的测试用例 ```yaml # 自动生成的测试用例(使用真实数据) config: name: "HAR Generated Tests" base_url: "http://localhost:8080" teststeps: - name: "Test POST users - Success" request: method: POST url: /api/v1/users headers: Authorization: "Bearer token123" # 从HAR提取 Content-Type: "application/json" json: username: john_doe # 真实数据 email: john@example.com age: 25 validate: - "$.status_code == 201" # 真实状态码 - "$.code == 201" # 真实业务码 - "type($.data.id) in [int, float]" # 基于真实响应 - "type($.data.username) == str" extract: # 自动提取变量 - id: $.data.id - user_id: $.data.user_id ``` **智能特性**: - ✅ 自动过滤噪音(.css, .js, /health) - ✅ 自动去重(相同请求只保留一次) - ✅ 变量自动提取(id, token, timestamp) - ✅ 请求头智能过滤(保留重要的,过滤cookie/user-agent) --- ### 📊 功能对比 | 特性 | 手动编写 | OpenAPI生成 | HAR生成 | |------|---------|------------|----------| | **数据来源** | 手写 | API规范文档 | 浏览器录制 | | **断言准确性** | 手写 | 基于Schema推测 | 基于真实响应 | | **请求数据** | 手写 | 自动生成 | 真实业务数据 | | **认证信息** | 手动配置 | 手动配置 | 自动提取 | | **依赖分析** | 手动管理 | 基于路径推测 | 基于时间顺序 | | **编写时间** | 2-3天 | 10秒 | 10秒 | | **适用场景** | 复杂逻辑 | API设计阶段 | 回归测试 | | **效率提升** | 1x | **2000x** | **2000x** | 📚 **代码实现**:[testrunner/core/ai_assistant.py](testrunner/core/ai_assistant.py) --- ## 🔄 增强的重试策略机制 🆕🔥 TestRunner 提供了**企业级的重试策略**,显著提升测试稳定性和容错能力。 ### 🎯 核心特性 - ✅ **4种重试策略** - Fixed(固定)、Linear(线性)、Exponential(指数)、Adaptive(自适应) - ✅ **抖动机制 (Jitter)** - 防止惊群效应,分散重试流量 - ✅ **断路器 (Circuit Breaker)** - 自动熔断、快速失败、自动恢复 - ✅ **异常分类** - 智能区分可/不可重试异常 - ✅ **错误上下文** - 详细捕获错误信息便于调试 ### 📚 快速示例 #### 1. 指数退避重试(推荐) ```yaml teststeps: - name: "接口测试" retry: times: 4 # 最多重试4次 interval: 0.5 # 基础间隔0.5秒 strategy: "exponential" # 指数退避策略 backoff: 2.0 # 退避倍数 retry_on: [500, 502, 503] # 重试的HTTP状态码 request: method: GET url: /api/service validate: status_code: 200 ``` **效果**:重试间隔按指数增长:`0.5s → 1.0s → 2.0s → 4.0s` #### 2. 带抖动的重试(高并发场景) ```yaml teststeps: - name: "防止惊群效应" retry: times: 3 interval: 1.0 strategy: "exponential" jitter: true # 启用抖动 jitter_range: 0.3 # ±30%随机抖动 retry_on: [500, 502, 503] request: method: GET url: /api/service validate: status_code: 200 ``` **效果**:每次重试间隔带有随机抖动,避免大量请求同时重试 #### 3. 断路器模式(服务保护) ```yaml teststeps: - name: "断路器保护" retry: times: 5 interval: 0.5 strategy: "exponential" circuit_breaker: true # 启用断路器 failure_threshold: 3 # 连续失败3次打开断路器 recovery_timeout: 60.0 # 60秒后尝试恢复 success_threshold: 2 # 连续成功2次关闭断路器 request: method: GET url: /api/critical-service validate: status_code: 200 ``` **效果**:服务持续失败时自动熔断,避免无谓重试,恢复后自动关闭 #### 4. 异常类型过滤 ```yaml teststeps: - name: "智能异常重试" retry: times: 3 strategy: "exponential" retry_on_exception: true retry_on_exception_types: # 只重试这些异常 - "Timeout" - "ConnectionError" - "HTTPError" skip_retry_on_exception_types: # 不重试这些异常 - "ValueError" - "AuthenticationError" retry_on: [500, 502, 503, 504] request: method: POST url: /api/process validate: status_code: 200 ``` **效果**:网络超时等临时性错误会重试,认证失败等永久性错误不重试 #### 5. 自适应重试(高级) ```yaml teststeps: - name: "自适应重试" retry: times: 5 interval: 0.5 strategy: "adaptive" # 自适应策略 success_rate_threshold: 0.3 # 成功率<30%停止重试 adaptive_window: 10 # 统计窗口大小 retry_on: [500, 502, 503] request: method: GET url: /api/unstable-service validate: status_code: 200 ``` **效果**:根据历史成功率动态调整重试策略,服务正在恢复时加快重试,高度不稳定时及时放弃 ### 📊 主要配置参数 | 参数 | 说明 | 默认值 | 示例 | |------|------|--------|------| | `times` | 最大重试次数 | 3 | `times: 5` | | `interval` | 基础重试间隔(秒) | 1.0 | `interval: 0.5` | | `strategy` | 重试策略 | "fixed" | `strategy: "exponential"` | | `backoff` | 退避倍数 | 2.0 | `backoff: 1.5` | | `max_interval` | 最大间隔(秒) | 60.0 | `max_interval: 30.0` | | `jitter` | 启用抖动 | false | `jitter: true` | | `jitter_range` | 抖动范围 (0.0-1.0) | 0.3 | `jitter_range: 0.2` | | `retry_on` | 重试的HTTP状态码 | None | `retry_on: [500, 502, 503]` | | `circuit_breaker` | 启用断路器 | false | `circuit_breaker: true` | | `failure_threshold` | 失败阈值 | 5 | `failure_threshold: 3` | | `recovery_timeout` | 恢复超时(秒) | 60.0 | `recovery_timeout: 120.0` | ### 🎓 最佳实践 1. **选择合适的策略** - 一般场景:指数退避(`strategy: "exponential"`) - 高并发:指数退避 + 抖动(`jitter: true`) - 不稳定服务:自适应重试(`strategy: "adaptive"`) 2. **合理配置重试次数** - 一般API:3次重试 - 关键业务:5-7次重试 - 不稳定服务:启用断路器 3. **外部依赖务必启用断路器** ```yaml circuit_breaker: true failure_threshold: 3 recovery_timeout: 60.0 ``` 4. **高并发场景务必启用抖动** ```yaml jitter: true jitter_range: 0.3 ``` ### 📝 详细文档 📚 **完整指南**:[docs/ENHANCED_RETRY_GUIDE.md](docs/ENHANCED_RETRY_GUIDE.md) 包含: - ✅ 每种策略的详细原理和执行流程 - ✅ 实际日志输出示例 - ✅ 断路器状态转换图解 - ✅ 异常分类决策流程 - ✅ 多场景对比分析 - ✅ 配置参数详解 ### 💡 优势对比 | 特性 | 传统重试 | TestRunner 增强重试 | |------|----------|--------------------| | 重试策略 | 固定间隔 | 4种策略(固定/线性/指数/自适应) | | 抖动机制 | ✖️ 无 | ✅ 支持,防止惊群效应 | | 断路器 | ✖️ 无 | ✅ 完整实现(3种状态) | | 异常分类 | ✖️ 不区分 | ✅ 智能分类,自定义白/黑名单 | | 错误上下文 | ✖️ 基础 | ✅ 详细捕获,便于调试 | | Allure集成 | ✖️ 无 | ✅ 重试历史、断路器统计 | | 生产级 | ✖️ 基础 | ✅ 企业级容错能力 | ### 🚀 快通测试 ```bash # 运行重试策略测试 testrunner run tests/16_enhanced_retry/test_retry_strategies.yaml # 运行断路器测试 testrunner run tests/16_enhanced_retry/test_circuit_breaker.yaml ``` --- ## 📚 文档 ### 基础文档 - [**快速开始**](docs/QUICK_START.md) - 5分钟上手 🚀 - [**用户手册**](docs/USER_GUIDE.md) - 完整功能指南 📖 - [数据库测试](docs/DATABASE_TESTING_GUIDE.md) - SQLite/MySQL 测试 - [MySQL测试](docs/mysql_testing_guide.md) - MySQL专项 ### 高级功能 🔥 - [**高级功能索引**](docs/advanced/README.md) - 所有高级功能总览 - [**性能监控与分析**](docs/PERFORMANCE_MONITORING.md) - 自动瓶颈检测、统计分析、优化建议 🆕🔥 - [**测试数据管理**](docs/TEST_DATA_MANAGEMENT.md) - 数据工厂、自动清理、数据隔离 🆕🔥 - [**智能断言增强**](testrunner/core/smart_assertion.py) - 类型不匹配提示、值差异分析、可视化Diff、自动修复建议 🆕🔥 - [**API录制增强**](testrunner/core/recorder_enhanced.py) - 智能过滤、自动分组、去重优化、变量提取、自动断言 🆕🔥 - [**失败分析与自愈**](testrunner/core/failure_analyzer.py) - 智能分类、根因分析、7种自愈策略、失败模式检测 🆕🔥 - [**分布式追踪**](testrunner/core/distributed_tracer.py) - W3C标准、Trace ID传播、Span管理、Jaeger/Zipkin导出 🆕🔥 - [**AI辅助测试**](testrunner/core/ai_assistant.py) - 智能分析、断言推荐、用例生成、结果分析、自动修复 🆕🔥 - [**增强重试策略**](docs/ENHANCED_RETRY_GUIDE.md) - 指数退避、断路器、自适应重试 🆕🔥 - [**并发性能优化**](docs/advanced/CONCURRENT_PERFORMANCE.md) - 大规模并发执行优化 🆕 - [**环境变量**](docs/advanced/ENV_VARIABLES.md) - .env 文件支持,敏感信息保护 🆕 - [Mock 能力](docs/advanced/MOCK.md) - 模拟外部 API 响应 - [阿里云 SDK](docs/advanced/ALIYUN_SDK.md) - 云产品测试 - [混合测试](docs/advanced/HYBRID_TESTING.md) - YAML + Python - [请求历史](docs/advanced/REQUEST_HISTORY.md) - 调试分析 - [API 录制](docs/advanced/API_RECORDING.md) - 自动生成测试 - [智能断言](docs/advanced/SMART_ASSERTIONS.md) - 自动断言生成 - [分布式测试](docs/advanced/DISTRIBUTED_TESTING.md) - 并行执行 - [Web Dashboard](docs/advanced/DASHBOARD.md) - 可视化管理 --- ## 📁 项目结构 ``` interface/ ├── testrunner/ # 核心框架 │ ├── core/ # 核心模块 (models, loader, runner, client, database) │ └── hybrid/ # 混合测试支持 ├── mock_server/ # Mock API 服务 ├── tests/ # 测试用例 │ ├── 01_basic/ # 基础测试 │ ├── 02_advanced/ # 高级测试 │ ├── 03_hybrid/ # YAML+Python混合测试 │ ├── 04_real_world/ # 真实场景测试 │ ├── 05_performance/ # 性能测试 │ ├── 06_utilities/ # 公共工具 │ ├── 07_shop_api/ # 商城API测试 │ ├── 10_mysql/ # MySQL数据库测试 │ ├── 11_aliyun/ # 阿里云SDK测试 │ ├── hooks/ # Hook函数库 ⭐ NEW │ └── database/ # SQLite数据库测试 ├── docs/ # 文档目录 └── db.yaml # 数据库配置文件 ``` --- ## ✨ 更多特性 ✅ **性能监控与分析** - 自动识别瓶颈、P50/P90/P95统计、优化建议 🆕🔥 ✅ **测试数据管理** - 数据工厂、自动清理、数据隔离 🆕🔥 ✅ **智能断言增强** - 类型不匹配提示、值差异分析、可视化Diff、自动修复建议 🆕🔥 ✅ **API录制增强** - 智能过滤、自动分组、去重优化、变量提取、自动断言 🆕🔥 ✅ **失败分析与自愈** - 智能分类、根因分析、7种自愈策略、失败模式检测 🆕🔥 ✅ **分布式追踪** - W3C标准、Trace ID传播、Span管理、Jaeger/Zipkin导出 🆕🔥 ✅ **AI辅助测试** - 智能分析、断言推荐、用例生成、结果分析、自动修复 🆕🔥 ✅ **增强重试策略** - 指数退避、断路器、抖动、自适应重试 🆕🔥 ✅ If/Loop 控制器 - 条件和循环控制 ✅ 参数化测试 - 数据驱动、循环控制、动态参数 ✅ 步骤级并发 - 资源管理、失败回滚、性能优化 🆕 ✅ 数据库测试 - SQLite/MySQL 原生支持 ✅ 阿里云SDK - ECS/VPC/NLB 等云产品测试 ✅ 性能测试 - Locust 分布式压测 ✅ Allure 报告 - 企业级测试报告 ✅ 混合测试 - YAML + Python 结合 📖 **详细使用**:[用户手册](docs/USER_GUIDE.md) --- ## Hook 机制(完善版)⭐ TestRunner 提供了业界领先的 Hook 机制,支持全生命周期钩子、步骤级钩子、流程控制等高级功能。 ### 核心特性 - ✅ **全局 Hook** - setup/teardown/before_step/after_step - ✅ **步骤级 Hook** - 单个步骤的 setup/teardown/成功/失败钩子 - ✅ **多 Hook 支持** - 支持注册多个钩子函数,按顺序执行 - ✅ **流程控制** - Hook 可以跳过步骤或终止测试 - ✅ **智能变量处理** - Hook 返回字典自动合并到变量 - ✅ **失败策略** - 可配置 Hook 失败时继续或终止 - ✅ **丰富的上下文** - 访问请求、响应、历史记录等信息 ### 快速开始 **1. 定义 Hook 函数** ```python # tests/hooks/my_hooks.py from testrunner.core.hooks import hook, setup_hook, teardown_hook @hook def prepare_data(): """返回字典会自动合并到变量""" return { "user_id": 1001, "timestamp": int(time.time()) } @setup_hook def init_test(ctx: HookContext): """测试开始前执行""" print(f"Starting: {ctx.testcase_name}") ctx.set_variable("test_start", time.time()) @teardown_hook def cleanup(ctx: HookContext): """测试结束后执行(即使失败也会执行)""" print(f"Finished: Success={ctx.success}") ``` **2. YAML 配置使用** ```yaml config: name: "Hook 示例测试" # 全局 Hook 配置 hooks: module: "tests.hooks.my_hooks" # 加载模块 # 支持多个 hook(按顺序执行) setup: - "init_database" - "prepare_test_data" teardown: - "cleanup_data" - "close_database" # Hook 失败策略 on_failure: "continue" # continue(继续) 或 abort(终止) teststeps: # 步骤级 Hook - name: "创建订单" # 步骤前置钩子 setup_hooks: - "prepare_order_data" # 步骤后置钩子 teardown_hooks: - "validate_order_created" - "cleanup_test_order" # 成功时执行 on_success_hooks: - "on_payment_success" # 失败时执行 on_failure_hooks: - "on_payment_failure" request: method: POST url: /api/orders json: user_id: "${user_id}" # 来自 prepare_data hook ``` ### 高级功能 **1. 流程控制** ```python @hook def check_and_skip(ctx: HookContext): """跳过步骤""" if not ctx.get_variable("should_run"): ctx.skip_step = True # 跳过当前步骤 @hook def critical_check(ctx: HookContext): """终止测试""" if ctx.get_variable("critical_error"): ctx.abort_test = True # 终止整个测试 ``` **2. 访问响应历史** ```python @hook def validate_consistency(ctx: HookContext): """跨步骤数据验证""" if len(ctx.response_history) >= 2: prev = ctx.response_history[-2].json_data curr = ctx.response_history[-1].json_data # 验证数据一致性 assert prev["user_id"] == curr["user_id"] ``` **3. HookContext 常用属性** ```python def my_hook(ctx: HookContext): # 基本信息 ctx.testcase_name # 测试用例名 ctx.step_name # 步骤名 ctx.step_index # 步骤索引 ctx.total_steps # 总步骤数 # 执行状态 ctx.success # 是否成功 ctx.error # 错误信息 # 请求响应 ctx.request # 请求对象 ctx.response # 响应对象 ctx.response_history # 响应历史 # 变量操作 ctx.set_variable("key", "value") value = ctx.get_variable("key", default="默认值") # 流程控制 ctx.skip_step = True # 跳过步骤 ctx.abort_test = True # 终止测试 ``` ### 对比 HttpRunner | 功能 | TestRunner | HttpRunner | |------|-----------|------------| | 多 Hook 函数 | ✅ 支持 | ❌ 单个 | | 步骤级 Hook | ✅ 支持 | ❌ 不支持 | | 成功/失败 Hook | ✅ 支持 | ❌ 不支持 | | 跳过步骤 | ✅ ctx.skip_step | ❌ 不支持 | | 终止测试 | ✅ ctx.abort_test | ❌ 不支持 | | 自动变量合并 | ✅ 返回字典 | ⚠️ 手动 | | 失败策略 | ✅ 可配置 | ⚠️ 固定 | | Context 丰富度 | ✅ 10+字段 | ⚠️ 基础 | ### 详细文档 - [用户手册](docs/USER_GUIDE.md) - Hook机制完整指南 --- ## 变量加密 支持敏感信息的加密存储与解密。 ### 命令行加密 ``` # 加密密码 testrunner encrypt "my_secret_password" # 输出: Encrypted value: Z0FBQUFBQm5... # 加密并复制到剪切板 testrunner encrypt "my_token" --copy ``` ### Python 使用 ``` from testrunner.core.encryption import encrypt_value, decrypt_value, EncryptionManager # 加密 encrypted = encrypt_value("my_secret_password") print(f"密文: {encrypted}") # 解密 decrypted = decrypt_value(encrypted) print(f"原文: {decrypted}") # 使用自定义密钥 manager = EncryptionManager(key="your-32-byte-key-here") encrypted = manager.encrypt("secret") ``` ### YAML 配置 ``` config: name: "加密变量测试" encrypted_vars: - name: "db_password" encrypted: "Z0FBQUFBQm5..." # 加密后的值 - name: "api_token" secret_ref: "API_TOKEN" # 环境变量引用 ``` ### 环境变量 ``` # 设置加密密钥 export TESTRUNNER_ENCRYPTION_KEY="your-base64-key" ``` --- ## 断言增强 支持 JSON Schema 校验和响应时间断言。 ### JSON Schema 校验 ``` - name: "JSON Schema 验证" request: method: GET url: /api/user/1 validate: json_schema: type: object required: ["code", "data"] properties: code: type: integer data: type: object required: ["id", "name", "email"] properties: id: type: integer name: type: string email: type: string format: email ``` ### 响应时间断言 ``` - name: "快速接口测试" request: method: GET url: /api/health validate: status_code: 200 response_time_lt: 100 # 响应时间 < 100ms response_time_lte: 200 # 响应时间 <= 200ms ``` --- ## Mock 能力 支持请求拦截与模拟响应。 ### Python 使用 ``` from testrunner.core.mocker import MockManager, MockResponse # 创建 Mock 管理器 mock = MockManager() # 添加 Mock 规则 mock.add_rule( url_pattern="/api/user", response={"code": 200, "data": {"id": 1, "name": "Mock User"}}, status_code=200, method="GET" ) # 添加错误响应 mock.add_rule( url_pattern="/api/error", response={"code": 500, "message": "Internal Error"}, status_code=500 ) # 匹配请求 response = mock.match("/api/user", method="GET") if response: print(f"状态码: {response.status_code}") print(f"响应: {response.json_data}") ``` ### YAML 配置 ``` config: name: "Mock 测试" mocks: - url_pattern: "/api/external" method: GET status_code: 200 response: code: 200 data: {"mocked": true} - url_pattern: "/api/timeout" status_code: 504 response: error: "Gateway Timeout" ``` --- ## CLI 增强 ### 运行命令 ``` # 基本运行 testrunner run tests/test.yaml # 指定环境 testrunner run tests/test.yaml --env prod # 按名称过滤 testrunner run tests/ --filter "*user*" # 按标签过滤 testrunner run tests/ --tag smoke,api # 并行执行 testrunner run tests/ --parallel 4 # 生成报告 testrunner run tests/ --report html testrunner run tests/ --report json # 生成 Allure 报告(推荐使用 pytest 方式) pytest tests/ --alluredir=allure-results allure serve allure-results ``` ### 加密命令 ``` # 加密值 testrunner encrypt "my_password" # 指定密钥 testrunner encrypt "my_password" --key "my-secret-key" ``` ### 验证命令 ``` # 验证 YAML 格式 testrunner validate tests/07_shop_api/test_01_user.yaml # 批量验证 testrunner validate tests/ ``` ### HAR 文件解析命令 ``` # 解析 HAR 文件并生成测试用例(默认过滤静态资源) testrunner parse-har recording.har --output test_cases/har_test.yaml --name "我的HAR测试" # 解析 HAR 文件并保留所有请求(包括静态资源) testrunner parse-har recording.har --output test_cases/har_test.yaml --name "我的HAR测试" --no-filter # 参数说明 # recording.har - 输入的 HAR 文件路径 # --output, -o - 输出的 YAML 测试用例文件路径 # --name, -n - 测试用例名称 # --no-filter - 禁用静态资源过滤(默认启用过滤) ``` ### Postman 集合导入命令 ``` # 导入 Postman 集合并生成测试用例 testrunner import-postman postman_collection.json --output test_cases/imported_test.yaml --name "我的测试用例" # 参数说明 # postman_collection.json - 输入的 Postman 集合 JSON 文件路径 # --output, -o - 输出的 YAML 测试用例文件路径 # --name, -n - 测试用例名称 ``` ### API 录制命令 ``` # 录制 HTTP 请求并生成测试用例 testrunner record http://localhost:5050/api/health http://localhost:5050/api/users --output recorded_test.yaml --name "录制的测试用例" # 参数说明 # http://... - 要录制的一个或多个 URL # --output, -o - 输出的 YAML 测试用例文件路径 # --name, -n - 测试用例名称 ``` ### 智能断言命令 ``` # 基于响应数据生成智能断言 testrunner smart-assert response.json --status-code 200 --confidence 0.8 --output smart_assertions.yaml # 参数说明 # response.json - 包含响应数据的 JSON 文件路径 # --status-code - 期望的 HTTP 状态码 # --confidence, -c - 断言置信度阈值(0.0-1.0,默认0.5) # --output, -o - 输出的断言 YAML 文件路径 ``` ### Web Dashboard 命令 ``` # 启动 Web Dashboard testrunner dashboard --port 8080 --scan-dir tests/ # 参数说明 # --port - Dashboard 监听端口(默认8080) # --scan-dir - 扫描测试用例的目录(默认tests/) # --host - 绑定的主机地址(默认127.0.0.1) ``` ### HAR 转换脚本命令 ``` # 使用集成脚本一键转换 HAR 文件(包含智能断言生成,默认过滤静态资源) python scripts/har_to_testrunner.py recording.har --output test_cases/full_har_test.yaml --name "完整HAR测试" --integrate --confidence 0.8 # 使用集成脚本一键转换 HAR 文件(保留所有请求) python scripts/har_to_testrunner.py recording.har --output test_cases/full_har_test.yaml --name "完整HAR测试" --integrate --confidence 0.8 --no-filter # 参数说明 # recording.har - 输入的 HAR 文件路径 # --output, -o - 输出的 YAML 测试用例文件路径 # --name, -n - 测试用例名称 # --integrate, -i - 集成智能断言生成功能 # --confidence, -c - 断言置信度阈值(0.0-1.0,默认0.7) # --no-filter - 禁用静态资源过滤(默认启用过滤) ``` ### Postman 转换脚本命令 ``` # 使用集成脚本一键转换 Postman 集合(包含智能断言生成) python scripts/postman_to_testrunner.py postman_collection.json --output test_cases/full_test.yaml --name "完整测试" --integrate --confidence 0.8 # 参数说明 # postman_collection.json - 输入的 Postman 集合 JSON 文件路径 # --output, -o - 输出的 YAML 测试用例文件路径 # --name, -n - 测试用例名称 # --integrate, -i - 集成智能断言生成功能 # --confidence, -c - 断言置信度阈值(0.0-1.0,默认0.7) ``` ### 帮助 ``` testrunner --help testrunner run --help testrunner encrypt --help testrunner validate --help testrunner parse-har --help testrunner import-postman --help testrunner record --help testrunner smart-assert --help testrunner dashboard --help ``` --- ## 请求/响应历史记录 框架自动保存所有 HTTP 请求和响应,支持跨步骤数据验证和性能分析。 ### 配置历史记录 ```yaml config: name: "测试用例" base_url: "http://localhost:5050" # 历史记录配置 history: enabled: true # 启用历史记录(默认: true) max_size: 100 # 最多保留100个响应(默认: 无限制) save_body: true # 保存响应体(默认: true) save_headers: false # 不保存请求头(默认: false) # 钩子函数模块 hooks: module: "tests.hooks.history_hooks" ``` ### 访问历史响应 ```yaml teststeps: - name: "步骤1 - 创建用户" request: method: POST url: /api/users json: username: "testuser" extract: user_id: jsonpath $.data.user_id - name: "步骤2 - 验证创建" request: method: GET url: /api/users/{{ user_id }} validate: # 访问上一步的响应 - "{{ response_history[-2].status_code == 201 }}, 上一步骤创建成功" # 验证数据一致性 - "{{ response_history[-1].json()['data']['username'] == response_history[-2].json()['data']['username'] }}, 用户名一致" ``` ### 使用钩子函数 **钩子函数文件** (`hooks_history.py`): ```python def validate_all_responses(response_history): """验证所有响应都成功""" for response in response_history: if not (200 <= response.status_code < 300): return False return True def calculate_avg_response_time(response_history): """计算平均响应时间(秒)""" total = sum(r.elapsed.total_seconds() for r in response_history) return total / len(response_history) if response_history else 0 def check_request_methods(request_history, expected_methods): """检查请求方法序列""" for i, expected in enumerate(expected_methods): if i >= len(request_history): return False if request_history[i]['method'] != expected: return False return True ``` **YAML 中调用:** ```yaml validate: # 调用钩子函数 - "{{ validate_all_responses(response_history) }}, 所有响应都成功" # 性能验证 - "{{ calculate_avg_response_time(response_history) < 2.0 }}, 平均响应时间<2秒" # 请求序列验证 - "{{ check_request_methods(request_history, ['POST', 'GET', 'PUT']) }}, 请求方法序列正确" ``` ### 配置示例 **常规测试:** ```yaml history: enabled: true max_size: 100 save_body: true save_headers: false ``` **性能测试(节省内存):** ```yaml history: enabled: true max_size: 20 save_body: false # 只保存状态码和响应时间 save_headers: false ``` 详细文档参见:[请求/响应历史记录指南](docs/request_response_history.md) --- ## Schema 验证 支持 YAML 配置格式验证。 ### Python 使用 ``` from testrunner.core.schema import validate_testcase_file, get_validator # 验证单个文件 is_valid, errors = validate_testcase_file("tests/test.yaml") if is_valid: print("✅ 有效的测试用例") else: print("❌ 验证失败:") for error in errors: print(f" - {error}") # 获取验证器 validator = get_validator() data = {"config": {"name": "test"}, "teststeps": []} is_valid, errors = validator.validate(data) ``` ### 命令行验证 ``` # 验证文件 testrunner validate tests/07_shop_api/test_01_user.yaml # 输出 # ✅ tests/07_shop_api/test_01_user.yaml is valid ``` --- ## 分布式执行 支持多机器并行执行测试用例。 ### 本地分布式执行 ``` from testrunner.core.distributed import run_distributed, LocalDistributedExecutor # 快捷函数 result = run_distributed( testcase_paths=[ 'tests/test_01.yaml', 'tests/test_02.yaml', 'tests/test_03.yaml', ], num_workers=4 ) print(f"总用例: {result['total_testcases']}") print(f"通过: {result['passed']}") print(f"失败: {result['failed']}") print(f"耗时: {result['total_duration']:.2f}s") # 使用执行器类 executor = LocalDistributedExecutor(num_workers=4) result = executor.execute(testcase_paths) ``` ### Master/Worker 模式 ``` from testrunner.core.distributed import create_master, create_worker # 创建 Master master = create_master(host="0.0.0.0", port=9000) master.start() # 提交任务 master.submit_tasks(['test1.yaml', 'test2.yaml']) # 查看状态 status = master.get_status() print(f"Workers: {status['workers']}") print(f"Tasks: {status['tasks']}") # 创建 Worker worker = create_worker(worker_id="worker-1", port=9001) worker.connect_to_master("localhost", 9000) worker.start() ``` --- ## Web Dashboard 可视化测试管理界面。 ### 启动 Dashboard ``` from testrunner.core.dashboard import Dashboard, create_dashboard, start_dashboard # 快捷启动 start_dashboard(test_dir='tests', host='0.0.0.0', port=8080) # 访问 http://localhost:8080 # 使用 Dashboard 类 dashboard = create_dashboard(port=8080) dashboard.scan_testcases('tests') # 扫描测试用例 dashboard.start() # 启动服务 ``` ### 后台启动 ``` dashboard = Dashboard(port=8080) dashboard.scan_testcases('tests') dashboard.start_background() # 后台运行 # 继续其他操作... ``` ### 功能特性 - 实时查看测试用例状态 - 一键运行单个/全部测试 - 测试结果统计和趋势图 - 自动刷新 (5秒) - 响应式设计 ### CLI 启动 ``` # 启动 Web Dashboard testrunner dashboard --port 8080 --scan-dir tests/ ``` --- ## API 录制 录制 HTTP 请求并自动生成 YAML 测试用例。 ### 基本使用 ``` from testrunner.core.recorder import RequestRecorder, TestCaseGenerator # 创建录制器 recorder = RequestRecorder() recorder.start_recording() # 录制请求 (手动记录) recorder.record_request( request_data={ 'method': 'POST', 'url': 'http://localhost:5050/api/user/login', 'headers': {'Content-Type': 'application/json'}, 'body': {'username': 'test', 'password': '123456'} }, response_data={ 'status_code': 200, 'body': {'code': 200, 'data': {'token': 'xxx'}} } ) recorder.stop_recording() # 生成测试用例 generator = TestCaseGenerator() generator.generate_yaml( recorder.records, output_path='tests/recorded_test.yaml', name='录制的测试用例' ) ``` ### 代理录制 ``` from testrunner.core.recorder import ProxyRecorder # 创建代理录制器 proxy = ProxyRecorder( target_host='http://localhost:5050', # 目标服务器 listen_port=8888 # 代理端口 ) # 启动代理 proxy.start() # 所有经过 http://localhost:8888 的请求都会被录制 # 导出测试用例 proxy.export_testcase('tests/proxy_recorded.yaml') ``` ### Requests 库钩子 ``` from testrunner.core.recorder import install_requests_hook, uninstall_requests_hook, RequestsHook import requests # 安装钩子 - 自动录制所有 requests 请求 install_requests_hook() # 正常发请求 requests.get('http://localhost:5050/api/health') requests.post('http://localhost:5050/api/user/login', json={...}) # 获取录制结果 recorder = RequestsHook.get_recorder() print(f"录制了 {len(recorder.records)} 个请求") # 卸载钩子 uninstall_requests_hook() ``` ### CLI 录制 ``` # 录制 HTTP 请求并生成测试用例 testrunner record http://localhost:5050/api/health http://localhost:5050/api/users --output recorded_test.yaml --name "录制的测试用例" ``` --- ## 智能断言 基于响应结构自动生成断言规则。 ### 基本使用 ``` from testrunner.core.smart_assert import ( SmartAssertionGenerator, generate_assertions, generate_schema ) # 示例响应数据 response_data = { 'code': 200, 'message': 'success', 'data': { 'id': 12345, 'name': 'Test User', 'email': 'test@example.com', 'is_active': True, 'created_at': '2024-01-01T00:00:00Z', 'balance': 99.99 } } # 生成断言 assertions = generate_assertions(response_data, status_code=200) for a in assertions: print(a) # {'status_code': 200}, {'eq': ['$.code', 200]}, ... # 生成 JSON Schema schema = generate_schema(response_data) print(schema) ``` ### 智能断言生成器 ``` from testrunner.core.smart_assert import SmartAssertionGenerator generator = SmartAssertionGenerator() # 生成断言 assertions = generator.generate_assertions( response_data=response_data, status_code=200, response_time_ms=150, min_confidence=0.7 # 最小置信度 ) # 转换为 YAML 格式 yaml_validators = generator.to_yaml_format(assertions) ``` ### 支持的字段模式 | 字段模式 | 生成的断言 | |----------|------------| | `id`, `*_id` | 存在性、类型检查 | | `email` | 邮箱格式正则 | | `phone`, `mobile` | 手机号格式正则 | | `url`, `link` | URL 格式正则 | | `created_at`, `*_time` | 时间格式验证 | | `is_*`, `has_*` | 布尔类型检查 | | `count`, `total` | 数字范围检查 | | `price`, `amount` | 金额范围检查 | | `code`, `status` | 值相等检查 | ### 从响应生成 ``` # 从 HTTP 响应对象生成 from testrunner.core.smart_assert import smart_validate result = smart_validate(response, min_confidence=0.7) print(result['validate']) # 断言列表 print(result['json_schema']) # JSON Schema ``` ### CLI 生成智能断言 ``` # 基于响应数据生成智能断言 testrunner smart-assert response.json --status-code 200 --confidence 0.8 --output smart_assertions.yaml ``` --- ## HAR 文件集成 支持从浏览器导出的 HAR (HTTP Archive) 文件导入并生成测试用例。 ### 基本使用 ``` from testrunner.core.har_parser import parse_har_file # 解析 HAR 文件并生成测试用例(默认过滤静态资源) result = parse_har_file('recording.har', filter_static_resources=True) # 解析 HAR 文件并保留所有请求 result = parse_har_file('recording.har', filter_static_resources=False) ``` ### CLI 使用 ``` # 解析 HAR 文件并生成测试用例(默认过滤静态资源) testrunner parse-har recording.har --output test_cases/har_test.yaml --name "我的HAR测试" # 解析 HAR 文件并保留所有请求(包括静态资源) testrunner parse-har recording.har --output test_cases/har_test.yaml --name "我的HAR测试" --no-filter ``` ### 请求类型过滤 默认会过滤掉以下类型的请求,只保留 API 请求: - CSS 样式文件 (text/css) - JavaScript 文件 (application/javascript) - 图片文件 (image/png, image/jpeg, image/gif) - 字体文件 (font/woff, font/ttf) - 其他静态资源 ### 支持的 HAR 特性 - GET/POST/PUT/DELETE 等 HTTP 方法 - 请求头 (Headers) - URL 参数和查询字符串 - JSON 请求体 - 表单数据 (Form Data) - 响应状态码验证 --- ## Postman 集成 支持从 Postman 导出的集合文件导入并生成测试用例。 ### 基本使用 ``` from testrunner.core.postman_importer import import_postman_collection # 导入 Postman 集合并生成测试用例 result = import_postman_collection('postman_collection.json') ``` ### CLI 使用 ``` # 导入 Postman 集合并生成测试用例 testrunner import-postman postman_collection.json --output test_cases/imported_test.yaml --name "我的测试用例" ``` ### 支持的 Postman 特性 - GET/POST/PUT/DELETE 等 HTTP 方法 - 请求头 (Headers) - URL 参数和查询字符串 - JSON 请求体 - 表单数据 (Form Data) - Postman 变量 (Variables) --- ## 测试用例列表 | 目录 | 说明 | |------|------| | 01_basic | 基础测试(GET/POST/变量/CRUD) | | 02_advanced | 高级测试(断言/提取/错误处理/模板) | | 03_hybrid | YAML+Python混合测试 | | 04_real_world | 真实场景测试(注册/订单/支付) | | 05_performance | 性能测试(Locust集成) | | 07_shop_api | 商城API测试(用户/商品/订单/E2E) | | 08_file_operations | 文件上传下载测试 | | 10_mysql | MySQL数据库测试(基础/事务/性能) | | 11_aliyun | 阿里云SDK测试(ECS/RDS/多种产品) | | database | SQLite数据库测试 | --- ## 模块导入参考 ``` # 核心模块 from testrunner.core import ( TestCase, TestStep, Config, YAMLLoader, TestRunner, HTTPClient, ReportGenerator, ) # Hook 模块 from testrunner.core import HookManager, HookContext # 加密模块 from testrunner.core import encrypt_value, decrypt_value # Mock 模块 from testrunner.core import MockManager # Schema 验证 from testrunner.core import validate_testcase_file # 分布式执行 from testrunner.core import run_distributed, LocalDistributedExecutor # Dashboard from testrunner.core import Dashboard, create_dashboard # 录制器 from testrunner.core import RequestRecorder, TestCaseGenerator # 智能断言 from testrunner.core import SmartAssertionGenerator, generate_assertions ``` --- ## 测试运行 ```bash # 运行所有测试 python test_new_features.py # 运行指定类型测试 python test_new_features.py basic # 基础测试 python test_new_features.py advanced # 高级测试 python test_new_features.py modules # 模块测试 ``` 测试覆盖:基础功能、重试机制、环境管理、数据驱动、并发执行、依赖注入、If/Loop控制器、Poll轮询、HTML/JSON/Allure报告、加密模块、Mock模块、Schema验证、Hooks机制、CLI功能、分布式执行、Dashboard、API录制、智能断言、HAR/Postman集成等。 --- ## License MIT License