
本文详细介绍了如何利用TestRail API,根据自定义字段(如“can_be_automated”)筛选特定测试用例,并将其动态添加到现有的测试运行中。教程涵盖了通过get_cases端点获取并过滤测试用例ID,以及使用update_run端点更新测试运行的完整流程,并提供了API请求示例和关键注意事项,帮助用户实现TestRail与自动化测试脚本的深度集成。
1. 背景与目标
在自动化测试流程中,我们经常需要根据测试用例的特定属性来动态选择并执行。例如,在testrail中,可能存在一个自定义字段“can_be_automated”来标记哪些测试用例可以进行自动化。本教程旨在指导您如何通过testrail api,筛选出这些标记为“可自动化”的测试用例,并将它们批量添加到指定的测试运行(test run)中。
整个过程可以分解为两个主要步骤:
从TestRail测试套件中获取所有测试用例,并根据自定义字段进行过滤。将过滤后的测试用例ID集合添加到现有的测试运行中。
2. 筛选特定测试用例
要从测试套件中筛选出符合条件的测试用例,我们需要使用TestRail的get_cases API端点。
2.1 获取测试用例
get_cases端点允许您检索指定项目和测试套件下的所有测试用例。
API 请求格式:
GET index.php?/api/v2/get_cases/{project_id}&suite_id={suite_id}
其中:
{project_id}:您的TestRail项目ID。{suite_id}:您要查询的测试套件ID。
示例响应(JSON 格式):
执行上述查询后,TestRail会返回一个包含所有测试用例信息的JSON数组。其中,自定义字段会以custom_前缀命名。例如,如果您的自定义字段名为“can_be_automated”,则在响应中会显示为custom_can_be_automated。
{ "offset": 0, "limit": 250, "size": 2, "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, // 关注此字段 // ... 其他自定义字段 ... } ]}
从上述响应中可以看出,custom_can_be_automated字段的值可以是true或false。
2.2 根据自定义字段过滤
获取到JSON响应后,您需要解析该响应并根据custom_can_be_automated字段的值进行过滤,提取出符合条件的测试用例ID。
以下是一个使用curl和jq工具进行过滤的示例。jq是一个轻量级且灵活的命令行JSON处理器,非常适合在Shell脚本中处理JSON数据。在JavaScript环境中,您可以使用Array.prototype.filter()方法来实现类似的功能。
使用 curl 和 jq 过滤示例:
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: 静默模式,不显示进度或错误信息。-H “Content-Type: application/json”: 设置请求头。-u “$TESTRAIL_EMAIL:$TESTRAIL_PASS”: 使用您的TestRail邮箱和API密钥进行认证。$TESTRAIL_URL: 您的TestRail实例URL。jq ‘[.cases[] | select(.custom_can_be_automated == true) | .id]’: jq命令用于处理JSON输出。.cases[]: 遍历cases数组中的每个元素。select(.custom_can_be_automated == true): 过滤出custom_can_be_automated字段值为true的用例。.id: 提取过滤后用例的id字段。[…]: 将所有提取的ID放入一个JSON数组中。
执行此命令后,您将获得一个包含所有“可自动化”测试用例ID的JSON数组,例如 [22478, 22501, 22505]。
3. 将筛选出的用例添加到测试运行
获取到需要添加到测试运行的用例ID列表后,下一步是使用TestRail的update_run API端点来修改现有的测试运行。
3.1 更新测试运行
update_run端点允许您修改指定测试运行的属性,包括其包含的测试用例。
API 请求格式:
POST index.php?/api/v2/update_run/{run_id}
其中:
{run_id}:您要更新的测试运行ID。
请求体 (JSON 格式):
请求体需要包含一个case_ids数组,其中列出所有要添加到测试运行的用例ID。include_all字段通常设置为false,除非您想包含所有用例并只排除特定的。在此场景下,我们明确指定要包含的用例,因此通常设置为false或不设置(默认行为)。如果设置为true并提供了case_ids,则case_ids会指定 包含 哪些用例,而不是排除。
{ "include_all": false, "case_ids": [1, 2, 3, 5, 8]}
示例:
假设您已经通过上一步获得了用例ID列表 [22478, 22501, 22505],并且您的测试运行ID是 123。
使用 curl 发送 POST 请求示例:
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": [22478, 22501, 22505]}'
解释:
-X POST: 指定HTTP请求方法为POST。-d ‘…’: 指定请求体数据。
如果操作成功,TestRail API将返回HTTP状态码 200 OK,表示测试用例已成功添加到测试运行中。
4. 关键注意事项与集成建议
API 认证: 确保您使用正确的TestRail邮箱和API密钥进行认证。API密钥可以在TestRail用户设置中生成。
自定义字段名称: TestRail API在返回自定义字段时会加上custom_前缀。例如,如果您在UI中创建的字段名为Can be Automated?,其系统名称可能为can_be_automated,那么在API响应中会是custom_can_be_automated。请务必使用正确的带custom_前缀的名称。
JavaScript 环境集成:
在JavaScript中,您可以使用fetch API或axios等库来发送HTTP请求。获取响应后,使用response.json()解析JSON数据。使用Array.prototype.filter()和Array.prototype.map()方法来过滤和提取用例ID。
JavaScript 示例 (伪代码):
async function getAndFilterTestCases(projectId, suiteId, testrailUrl, email, password) { const auth = btoa(`${email}:${password}`); // Base64 encode credentials const url = `${testrailUrl}/index.php?/api/v2/get_cases/${projectId}&suite_id=${suiteId}`; const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': `Basic ${auth}` } }); if (!response.ok) { throw new Error(`Failed to fetch cases: ${response.statusText}`); } const data = await response.json(); const automatedCaseIds = data.cases .filter(testCase => testCase.custom_can_be_automated === true) .map(testCase => testCase.id); return automatedCaseIds;}async function addCasesToTestRun(runId, caseIds, testrailUrl, email, password) { const auth = btoa(`${email}:${password}`); const url = `${testrailUrl}/index.php?/api/v2/update_run/${runId}`; const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Basic ${auth}` }, body: JSON.stringify({ include_all: false, // Or true, depending on desired behavior case_ids: caseIds }) }); if (!response.ok) { throw new Error(`Failed to update run: ${response.statusText}`); } console.log(`Successfully updated test run ${runId} with cases: ${caseIds.join(', ')}`); return response.json(); // Or just check response.ok}// 示例调用// (async () => {// const PROJECT_ID = 1;// const SUITE_ID = 196;// const TEST_RUN_ID = 123;// const TESTRAIL_URL = "https://your.testrail.instance";// const TESTRAIL_EMAIL = "your@email.com";// const TESTRAIL_PASS = "your_api_key";// try {// const automatedCases = await getAndFilterTestCases(// PROJECT_ID, SUITE_ID, TESTRAIL_URL, TESTRAIL_EMAIL, TESTRAIL_PASS// );// console.log("Automated Case IDs:", automatedCases);// if (automatedCases.length > 0) {// await addCasesToTestRun(// TEST_RUN_ID, automatedCases, TESTRAIL_URL, TESTRAIL_EMAIL, TESTRAIL_PASS// );// } else {// console.log("No automated cases found to add.");// }// } catch (error) {// console.error("An error occurred:", error);// }// })();
错误处理: 在实际应用中,务必对API请求进行错误处理,例如检查HTTP状态码、解析错误信息,以确保脚本的健壮性。
API 速率限制: TestRail API可能有速率限制。在进行大量请求时,请注意控制请求频率,避免被服务器拒绝。
5. 总结
通过遵循本教程中的步骤,您可以有效地利用TestRail API来自动化测试用例的选择和测试运行的创建过程。这种方法极大地提高了自动化测试流程的灵活性和效率,确保只有符合特定条件的测试用例才会被纳入到自动化执行计划中。
相关API文档链接:
TestRail update_run API: https://www.php.cn/link/7966a1b638bd6906654fd9190feeb801TestRail get_cases API: https://www.php.cn/link/31beb41824b307d9f0deb076f8f9ee3b
以上就是TestRail API:按自定义字段过滤并添加到测试运行的详细内容,更多请关注php中文网其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/55932.html
微信扫一扫
支付宝扫一扫