
在自动化测试流程中,我们经常需要根据测试用例的特定属性来动态选择并执行。例如,在testrail中,可能存在一个自定义字段“can_be_automated”来标记哪些测试用例可以进行自动化。本教程旨在指导您如何通过testrail api,筛选出这些标记为“可自动化”的测试用例,并将它们批量添加到指定的测试运行(test run)中。
整个过程可以分解为两个主要步骤:
要从测试套件中筛选出符合条件的测试用例,我们需要使用TestRail的get_cases API端点。
get_cases端点允许您检索指定项目和测试套件下的所有测试用例。
API 请求格式:
GET index.php?/api/v2/get_cases/{project_id}&suite_id={suite_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。
获取到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]'解释:
执行此命令后,您将获得一个包含所有“可自动化”测试用例ID的JSON数组,例如 [22478, 22501, 22505]。
获取到需要添加到测试运行的用例ID列表后,下一步是使用TestRail的update_run API端点来修改现有的测试运行。
update_run端点允许您修改指定测试运行的属性,包括其包含的测试用例。
API 请求格式:
POST index.php?/api/v2/update_run/{run_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]}'解释:
如果操作成功,TestRail API将返回HTTP状态码 200 OK,表示测试用例已成功添加到测试运行中。
API 认证: 确保您使用正确的TestRail邮箱和API密钥进行认证。API密钥可以在TestRail用户设置中生成。
自定义字段名称: TestRail API在返回自定义字段时会加上custom_前缀。例如,如果您在UI中创建的字段名为Can be Automated?,其系统名称可能为can_be_automated,那么在API响应中会是custom_can_be_automated。请务必使用正确的带custom_前缀的名称。
JavaScript 环境集成:
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可能有速率限制。在进行大量请求时,请注意控制请求频率,避免被服务器拒绝。
通过遵循本教程中的步骤,您可以有效地利用TestRail API来自动化测试用例的选择和测试运行的创建过程。这种方法极大地提高了自动化测试流程的灵活性和效率,确保只有符合特定条件的测试用例才会被纳入到自动化执行计划中。
相关API文档链接:
以上就是TestRail API:按自定义字段过滤并添加到测试运行的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号