如何从Firebase Test Lab获取测试用例具体通过结果数据
实现方案
该需求完全可以落地,你只需要调用Tool Results API拉取测试执行的详细统计数据,替换现有代码里硬编码的通过率部分即可,具体操作步骤如下:
- 首先配置权限:给Cloud Function的默认运行服务账号(格式为
你的项目ID@appspot.gserviceaccount.com)授予Tool Results Viewer角色,否则调用API会返回权限不足错误。 - 安装依赖包:在Cloud Function代码目录下执行以下命令安装官方SDK:
npm install @google-cloud/toolresults - 调整业务代码,以下是修改后的完整函数示例:
const { ToolResultsServiceClient } = require('@google-cloud/toolresults'); const toolResultsClient = new ToolResultsServiceClient(); exports.postTestResultsToSlack = functions.testLab .testMatrix() .onComplete(async testMatrix => { if (testMatrix.clientInfo.details['testType'] != 'regression') { // 非回归测试直接跳过 return null; } const { testMatrixId, state, outcomeSummary, resultStorage } = testMatrix; const projectId = process.env.GCP_PROJECT || process.env.GCLOUD_PROJECT; const { toolResultsHistoryId, toolResultsExecutionId } = resultStorage; // 拉取测试执行详情统计用例数据 let totalCases = 0; let passedCases = 0; try { const [execution] = await toolResultsClient.getExecution({ projectId: projectId, historyId: toolResultsHistoryId, executionId: toolResultsExecutionId }); // 遍历所有测试步骤统计用例数 if (execution.step) { for (const step of execution.step) { const testOverview = step.testExecutionStep?.testSuiteOverviews?.[0]; if (testOverview) { totalCases += testOverview.totalCount || 0; passedCases += testOverview.successCount || 0; } } } } catch (err) { functions.logger.error('拉取用例统计失败', err); } const colour = getSlackColour(outcomeSummary) const title = `*Test Session: ${testMatrixId}*`; // 拼接通过率字符串,处理无有效用例的边界情况 const passRate = totalCases > 0 ? Math.round((passedCases / totalCases) * 100) : 0; const details = totalCases > 0 ? `${passedCases}/${totalCases} passed (${passRate}%)` : '无有效测试用例'; const resultURL = resultStorage.resultsUrl const slackResponse = await postToSlack(colour, title, details, resultURL); functions.logger.log(JSON.stringify(slackResponse.data)); });
如果你的测试任务会在多台设备上并行执行,你可以根据需求调整统计逻辑,既可以累加所有设备的用例数据计算总通过率,也可以按设备维度分别展示各设备的测试通过率。
内容的提问来源于stack exchange,提问作者George
相关产品推荐
相关产品推荐

