Importar los módulos requeridos
Para comenzar, importe los módulos necesarios para manejar los eventos de Firebase Test Lab:
Nodo.js
// The Cloud Functions for Firebase SDK to set up triggers and logging.
const {onTestMatrixCompleted} = require("firebase-functions/v2/testLab");
const {logger} = require("firebase-functions");
Pitón
# 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
Activar una función al finalizar TestMatrix
Para activar una función de Firebase Test Lab, defina un controlador para el evento de finalización de la matriz de prueba. En este ejemplo, la función se activa al finalizar la prueba, recupera los datos de la matriz de prueba del objeto CloudEvent y envía los resultados de la prueba correspondientes a un canal de Slack:
Nodo.js
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);
});
Pitón
@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)
Acceder a los datos del cliente
Las matrices de prueba se pueden crear a partir de diferentes fuentes o flujos de trabajo. Por lo tanto, a menudo es deseable crear funciones que realicen diferentes acciones según el origen u otro contexto importante de la prueba. Para ayudar con esto, gcloud
te permite pasar información arbitraria al iniciar una prueba a la que se puede acceder más adelante en tu función. Por ejemplo:
gcloud beta firebase test android run \
--app=path/to/app.apk \
--client-details testType=pr,link=<path/to/pull-request>
Y luego para acceder a la información en su función:
Nodo.js
const testType = event.data.clientInfo.details.testType;
const link = event.data.clientInfo.details.link;
Pitón
test_type: str | None = event.data.client_info.details.get("testType")
link: str | None = event.data.client_info.details.get("link")