本教程详细指导如何利用 TestRail API 筛选出具有特定自定义字段(如“可自动化”)的测试用例,并将其动态添加到新的测试运行中。文章涵盖了从获取测试套件中的用例数据、解析JSON响应、根据自定义字段进行过滤,到最终通过API更新测试运行的完整流程,并提供了实用的代码示例。在自动化测试与TestRail集成的工作流中,经常需要根据用例的特定属性(例如,是否可自动化)来动态创建或更新测试运行,以确保只执行相关的测试用例。本文将分步演示如何通过TestRail API实现这一高效且灵活的过程。
一、从测试套件中筛选特定测试用例
要筛选出具有特定属性的测试用例,首先需要从 TestRail 获取测试套件中的所有用例数据,然后对这些数据进行解析和过滤。
1.1 理解 get_cases API 端点
get_cases 是 TestRail API 中用于检索测试用例的核心端点。它允许你根据项目ID和测试套件ID获取该套件下的所有测试用例。
- API 请求格式:
GET index.php?/api/v2/get_cases/{project_id}&suite_id={suite_id}
- 参数说明:
- {project_id}:你的 TestRail 项目的唯一标识符。
- {suite_id}:你希望从中筛选用例的测试套件的唯一标识符。
1.2 解析 API 响应与自定义字段
执行 get_cases 请求后,TestRail 会返回一个 JSON 格式的响应,其中包含测试套件中所有测试用例的详细信息。每个用例对象都包含其 ID、标题以及所有自定义字段。
以下是一个响应示例,其中展示了 custom_can_be_automated 这一自定义字段:
{ "cases":[ { "id":22478, "title":"Test Case Steps (Text)", "section_id":2347, // ... 其他字段 ... "suite_id":196, "custom_automation_type":6, "custom_can_be_automated":true, // 关注此字段 // ... 更多自定义字段 ... }, { "id":22494, "title":"Automated Checkout", "section_id":2347, // ... 其他字段 ... "suite_id":196, "custom_automation_type":0, "custom_can_be_automated":false, // 关注此字段 // ... 更多自定义字段 ... } ] }
在这个 JSON 结构中,custom_can_be_automated 字段是一个布尔值,用于指示该测试用例是否可自动化。
1.3 过滤自动化测试用例
获取到 JSON 响应后,下一步是根据 custom_can_be_automated 属性进行过滤,提取出所有标记为 true 的测试用例的 ID。
-
命令行示例(使用 curl 和 jq): 如果你在命令行环境工作,可以使用 curl 发送 API 请求,并结合 jq 工具来解析和过滤 JSON 响应。
TESTRAIL_URL="your_testrail_instance.testrail.io" TESTRAIL_EMAIL="your_email@example.com" TESTRAIL_PASS="your_api_key_or_password" PROJECT_ID="1" # 替换为你的项目ID SUITE_ID="196" # 替换为你的测试套件ID curl -s -H "Content-Type: application/json" -u "$TESTRAIL_EMAIL:$TESTRAIL_PASS" "$TESTRAIL_URL/index.php?/api/v2/get_cases/$PROJECT_ID&suite_id=$SUITE_ID" | jq '[.cases[] | select(.custom_can_be_automated == true) | .id]'
- -s 参数用于抑制 curl 的进度信息。
- jq ‘[.cases[] | select(.custom_can_be_automated == true) | .id]’ 这部分命令会:
- 遍历 cases 数组中的每一个元素。
- select(.custom_can_be_automated == true) 筛选出 custom_can_be_automated 字段为 true 的用例。
- |.id 提取这些筛选出用例的 id 字段。
- 最终输出一个包含所有符合条件用例 ID 的 JSON 数组,例如 [22478, 30001]。
-
JavaScript 环境下的实现思路: 如果你在 JavaScript 环境中开发(例如 Node.js 或浏览器环境),可以使用 fetch 或 axios 等库来发送 HTTP 请求并处理响应:
async function getAutomatedCaseIds(projectId, suiteId) { const testrailUrl = "https://your_testrail_instance.testrail.io"; const email = "your_email@example.com"; const apiKey = "your_api_key_or_password"; // 推荐使用API Key const auth = btoa(`${email}:${apiKey}`); // Base64 编码认证信息 try { const response = await fetch(`${testrailUrl}/index.php?/api/v2/get_cases/${projectId}&suite_id=${suiteId}`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': `Basic ${auth}` } }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); const automatedCaseIds = data.cases .filter(testCase => testCase.custom_can_be_automated === true) .map(testCase => testCase.id); return automatedCaseIds; } catch (error) { console.error("Error fetching automated test cases:", error); return []; } } // 示例调用 // getAutomatedCaseIds(1, 196).then(ids => console.log("Automated Case IDs:", ids));
二、将筛选后的用例添加到测试运行
获取到需要添加到测试运行的用例 ID 列表后,下一步就是使用 update_run API 端点来更新现有的测试运行。
2.1 理解 update_run API 端点
update_run 用于修改一个已存在的测试运行的属性,包括其包含的测试用例。
- API 请求格式:
POST index.php?/api/v2/update_run/{run_id}
- 参数说明:
- {run_id}:你希望更新的测试运行的唯一标识符。
2.2 构建请求体
要将特定用例添加到测试运行,你需要在 POST 请求体中提供一个 JSON 对象,其中包含 case_ids 数组。
-
关键字段:
- include_all (布尔值):
- 如果设置为 true,TestRail 将会包含测试套件中的所有用例,此时 case_ids 字段会被忽略。
- 如果只想添加特定用例,请将此字段设置为 false 或省略此字段,并提供 case_ids 数组。
- case_ids (数组):包含你希望添加到测试运行中的测试用例 ID 列表。
- include_all (布尔值):
-
示例请求体:
{ "include_all": false, "case_ids": [22478, 30001, 30005] // 替换为实际筛选出的用例ID }
2.3 发送 POST 请求
-
命令行示例(使用 curl):
TESTRAIL_URL="your_testrail_instance.testrail.io" TESTRAIL_EMAIL="your_email@example.com" TESTRAIL_PASS="your_api_key_or_password" RUN_ID="123" # 替换为你的测试运行ID CASE_IDS="[22478, 30001, 30005]" # 替换为上一步获取到的用例ID数组 curl -X POST "https://$TESTRAIL_URL/index.php?/api/v2/update_run/$RUN_ID" -H "Content-Type: application/json" -u "$TESTRAIL_EMAIL:$TESTRAIL_PASS" -d "{"include_all": false, "case_ids": $CASE_IDS}"
-
JavaScript 环境下的实现思路:
async function addCasesToTestRun(runId, caseIds) { const testrailUrl = "https://your_testrail_instance.testrail.io"; const email = "your_email@example.com"; const apiKey = "your_api_key_or_password"; const auth = btoa(`${email}:${apiKey}`); try { const response = await fetch(`${testrailUrl}/index.php?/api/v2/update_run/${runId}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Basic ${auth}` }, body: JSON.stringify({ include_all: false, // 明确指定不包含所有用例 case_ids: caseIds }) }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } console.log(`Successfully added cases to TestRun ${runId}.`); return await response.json(); // 返回更新后的 TestRun 信息 } catch (error) { console.error(`Error adding cases to TestRun ${runId}:`, error); return null; } } // 示例调用 // const automatedIds = await getAutomatedCaseIds(1, 196); // 假设已获取 // if (automatedIds.length > 0) { // addCasesToTestRun(123, automatedIds); // } else { // console.log("No automated cases found to add."); // }
2.4 验证操作结果
当 update_run 请求成功执行后,TestRail API 会返回一个 HTTP 状态码 200 OK,表示操作成功。你可以根据这个状态码来判断用例是否已成功添加到测试运行中。
三、注意事项与最佳实践
在实际集成 TestRail API 时,请考虑以下几点以确保操作的健壮性和可靠性:
- API 认证: 始终使用 TestRail 提供的 API Key 进行认证,而非账户密码。API Key 具有更好的安全性和管理性。
- 错误处理: 在你的脚本或应用程序中,务必对 API 的响应进行错误检查。除了检查 HTTP 状态码(非 200 通常表示失败),还要解析响应体中的错误信息,以便更好地诊断问题。
- 自定义字段名称: 确保你在代码中使用的自定义字段名称(例如 custom_can_be_automated)与 TestRail 实例中实际配置的字段名称完全一致。这些名称通常是小写且以下划线分隔。
- API 速率限制: TestRail API 有请求速率限制。对于需要处理大量用例或频繁调用的场景,请注意这些限制,并考虑在请求之间添加适当的延迟,或采用批量处理策略。
- TestRun 生命周期: 在尝试更新测试运行之前,确保目标测试运行(run_id)已经存在。通常,你会先创建一个测试运行(使用 add_run API),然后根据筛选结果更新它。
- include_all 字段: 务必正确理解 update_run 请求体中 include_all 字段的作用。如果你只想添加筛选出的特定用例,应将其设置为 false 或省略,并提供 case_ids 数组。
总结
通过本文的指导,你已经掌握了如何利用 TestRail API 动态筛选特定测试用例(例如,标记为“可自动化”的用例)并将其添加到现有的测试运行中。这一过程涉及到 get_cases 端点获取数据、解析 JSON 响应、根据自定义字段进行过滤,以及使用 update_run 端点更新测试运行。掌握这些技能将极大地提升你的自动化测试流程与 TestRail 管理的集成效率和灵活性。
参考资料
- TestRail API 文档 – Runs#updaterun:https://www.php.cn/link/7966a1b638bd6906654fd9190feeb801
- TestRail API 文档 – Cases#getcases:https://www.php.cn/link/31beb41824b307d9f0deb076f8f9ee3b
以上就是TestRail API 实战:动态筛选测试用例并集成至测试运行的详细内容,更多请关注php javascript word java js node.js json node 编码 浏览器 app JavaScript json select cURL 标识符 字符串 JS 对象 http https 自动化 axios