如何从Testrail套件筛选can_be_automated=yes的测试用例加入Testrun
解决TestRail筛选
can_be_automated=yes用例并创建TestRun的问题 核心流程
要实现需求,需分三步执行:
- 调用TestRail API的
get_cases接口,拉取目标测试套件下的所有测试用例 - 筛选出自定义字段
can_be_automated值为yes的用例,提取它们的ID - 将筛选后的case ID列表传入
add_run接口,创建包含指定用例的测试运行
示例JavaScript脚本(TestComplete环境)
function CreateTestRunWithAutomatedCases() { // TestRail基础配置 const testRailUrl = "https://your-testrail-instance.testrail.io"; const userName = "your-email@example.com"; const apiKey = "your-api-key"; const projectId = 1; // 替换为你的项目ID const suiteId = 5; // 替换为目标测试套件ID const testRunName = "Automated Test Run - " + aqDateTime.Now(); // 1. 获取套件下所有测试用例 const getCasesEndpoint = `${testRailUrl}/index.php?/api/v2/get_cases/${projectId}&suite_id=${suiteId}`; const httpClient = aqHttp.CreateHttpClient(); httpClient.SetBasicAuthentication(userName, apiKey); httpClient.SetHeader("Content-Type", "application/json"); const getCasesResponse = httpClient.Get(getCasesEndpoint); if (getCasesResponse.StatusCode !== 200) { Log.Error(`获取用例失败,状态码:${getCasesResponse.StatusCode},响应:${getCasesResponse.Text}`); return; } const allCases = JSON.parse(getCasesResponse.Text); Log.Message(`共获取${allCases.length}个测试用例`); // 2. 筛选可自动化的用例 // 注意:TestRail自定义字段会自动添加custom_前缀,需核对实际返回的字段键名 const automatedCaseIds = []; for (let i = 0; i < allCases.length; i++) { const testCase = allCases[i]; if (testCase.custom_can_be_automated === "yes") { automatedCaseIds.push(testCase.id); } } if (automatedCaseIds.length === 0) { Log.Warning("未找到标记为可自动化的测试用例"); return; } Log.Message(`筛选出${automatedCaseIds.length}个可自动化用例:${automatedCaseIds.join(", ")}`); // 3. 创建包含筛选用例的TestRun const addRunEndpoint = `${testRailUrl}/index.php?/api/v2/add_run/${projectId}`; const runData = { suite_id: suiteId, name: testRunName, case_ids: automatedCaseIds // 可按需添加description、assigned_to_id等参数 }; const addRunResponse = httpClient.Post(addRunEndpoint, JSON.stringify(runData)); if (addRunResponse.StatusCode !== 200) { Log.Error(`创建测试运行失败,状态码:${addRunResponse.StatusCode},响应:${addRunResponse.Text}`); return; } const createdRun = JSON.parse(addRunResponse.Text); Log.Message(`成功创建测试运行,ID:${createdRun.id},名称:${createdRun.name}`); }
关键注意事项
- 自定义字段键名:TestRail中自定义字段的系统键会自动加上
custom_前缀,比如你创建的can_be_automated字段,API返回的实际键是custom_can_be_automated,必须核对API返回的字段结构,避免键名错误导致筛选失效。 - 分页处理:如果套件下用例数量超过250条(TestRail API默认分页上限),需通过
offset参数循环拉取所有页的用例。 - 权限验证:确保你的TestRail账号拥有
view_tests和add_runs权限,API密钥需正确生成并启用。 - TestComplete环境适配:脚本使用了TestComplete的
aqHttp和Log对象,需在TestComplete的JavaScript项目中运行。
内容的提问来源于stack exchange,提问作者user21954959
相关产品推荐
相关产品推荐

