使用 Cloud Functions 函数扩展 Firebase Test Lab 功能


首先,导入处理 Firebase Test Lab 事件所需的模块:

 // The Cloud Functions for Firebase SDK to set up triggers and logging.
const {onTestMatrixCompleted} = require("firebase-functions/v2/testLab");
const {logger} = require("firebase-functions");
 # The Cloud Functions for Firebase SDK to set up triggers and logging.
from firebase_functions import test_lab_fn, params

# The requests library to send web requests to Slack.
import requests

在 TestMatrix 完成时触发函数

如需触发 Firebase Test Lab 函数,请为测试矩阵完成事件定义一个处理程序。在此示例中,函数会在测试完成时触发,从 CloudEvent 对象中检索测试矩阵数据,并将相应的测试结果发送到 Slack 频道:

exports.posttestresultstoslack = onTestMatrixCompleted(
    {secrets: ["SLACK_WEBHOOK_URL"]},
    async (event) => {
    // Obtain Test Matrix properties from the CloudEvent
      const {testMatrixId, state, outcomeSummary} = event.data;

      // Create the title of the message
      const title = `${getSlackmoji(state)} ${getSlackmoji(
          outcomeSummary,
      )} ${testMatrixId}`;

      // Create the details of the message
      const details = `Status: *${state}* ${getSlackmoji(
          state,
      )}\nOutcome: *${outcomeSummary}* ${getSlackmoji(outcomeSummary)}
    `;

      // Post the message to slack
      const slackResponse = await postToSlack(title, details);

      // Log the response
      logger.log(slackResponse);
    });
@test_lab_fn.on_test_matrix_completed(secrets=["SLACK_WEBHOOK_URL"])
def posttestresultstoslack(
        event: test_lab_fn.CloudEvent[test_lab_fn.TestMatrixCompletedData]) -> None:
    """Posts a test matrix result to Slack."""

    # Obtain Test Matrix properties from the CloudEvent
    test_matrix_id = event.data.test_matrix_id
    state = event.data.state
    outcome_summary = event.data.outcome_summary

    # Create the title of the message
    title = f"{slackmoji(state)} {slackmoji(outcome_summary)} {test_matrix_id}"

    # Create the details of the message
    details = (f"Status: *{state}* {slackmoji(state)}\n"
               f"Outcome: *{outcome_summary}* {slackmoji(outcome_summary)}")

    # Post the message to Slack
    response = post_to_slack(title, details)

    # Log the response
    print(response.status_code, response.text)

访问客户端详细信息

测试矩阵可能基于不同的来源或工作流而创建。因此,开发者通常希望创建能够根据测试的来源或其他重要上下文来执行不同操作的函数。为帮助完成此任务,您可以使用 gcloud 在开始测试时传递任意信息,以便稍后可在您的函数中使用。例如:

gcloud beta firebase test android run \
    --app=path/to/app.apk \
    --client-details testType=pr,link=<path/to/pull-request>

之后,如需访问函数中的信息,请使用以下代码:

const testType = event.data.clientInfo.details.testType;
const link = event.data.clientInfo.details.link;
test_type: str | None = event.data.client_info.details.get("testType")
link: str | None = event.data.client_info.details.get("link")