Beispiele für synthetische Monitore

In diesem Dokument werden die verfügbaren Vorlagen und Beispielcode für das Erstellen synthetischer Monitore beschrieben. Die Beispielfunktionen sind im GitHub-Repository Google Cloud/synthetics-sdk-nodjs verfügbar.

Wenn Sie Tests schreiben und sich nicht auf eine Vorlage verlassen, prüfen Sie, ob der Test bestanden wird, sofern kein Error ausgegeben wird. Wir empfehlen, die Assert-Bibliothek zu verwenden. So sorgen Sie dafür, dass Fehler, die auftreten, der richtigen Codezeile zugeordnet werden.

Allgemeine Vorlagen

Die generischen Vorlagen sind so konfiguriert, dass sie Trace- und Logdaten für ausgehende HTTP-Anfragen erfassen. Die Lösung nutzt das OpenTelemetry-Modul auto-instrumentation-node und den winston Logger. Aufgrund der Abhängigkeit von Open-Source-Produkten sind Änderungen an der Struktur der Trace- und Logdaten zu erwarten. Daher sollten die erfassten Trace- und Logdaten nur zu Fehlerbehebungszwecken verwendet werden.

Sie können einen eigenen Ansatz implementieren, um Trace- und Logdaten für ausgehende HTTP-Anfragen zu erfassen. Ein Beispiel für einen benutzerdefinierten Ansatz finden Sie in der Klasse SyntheticAutoInstrumentation.

Generisches Node.js-Beispiel

Das Beispiel generic-synthetic-nodejs zeigt, wie eine URL abgefragt wird. Dieses Beispiel enthält die gleiche Standardfunktion, die in der Google Cloud Console angezeigt wird.

Um das vollständige generic-synthetic-nodejs-Beispiel anzusehen, klicken Sie auf das Dreipunkt-Menü und wählen Sie dann Auf GitHub ansehen aus:

const { instantiateAutoInstrumentation, runSyntheticHandler } = require('@google-cloud/synthetics-sdk-api');
// Run instantiateAutoInstrumentation before any other code runs, to get automatic logs and traces
instantiateAutoInstrumentation();
const functions = require('@google-cloud/functions-framework');
const axios = require('axios');
const assert = require('node:assert');

functions.http('SyntheticFunction', runSyntheticHandler(async ({logger, executionId}) => {
  /*
   * This function executes the synthetic code for testing purposes.
   * If the code runs without errors, the synthetic test is considered successful.
   * If an error is thrown during execution, the synthetic test is considered failed.
   */
  logger.info('Making an http request using synthetics, with execution id: ' + executionId);
  const url = 'https://www.google.com/'; // URL to send the request to
  return await assert.doesNotReject(axios.get(url));
}));

TypeScript-Beispiel

Im Beispiel generic-synthetic-typescript wird gezeigt, wie Sie eine URL abfragen.

Um das vollständige generic-synthetic-typescript-Beispiel anzusehen, klicken Sie auf das Dreipunkt-Menü und wählen Sie dann Auf GitHub ansehen aus:

import {runSyntheticHandler, instantiateAutoInstrumentation} from '@google-cloud/synthetics-sdk-api'
// Run instantiateAutoInstrumentation before any other code runs, to get automatic logs and traces
instantiateAutoInstrumentation();
import * as ff from '@google-cloud/functions-framework';
import axios from 'axios';
import assert from 'node:assert';
import {Logger} from 'winston';

ff.http('SyntheticFunction', runSyntheticHandler(async ({logger, executionId}: {logger: Logger, executionId: string|undefined}) => {
  /*
   * This function executes the synthetic code for testing purposes.
   * If the code runs without errors, the synthetic test is considered successful.
   * If an error is thrown during execution, the synthetic test is considered failed.
   */
  logger.info('Making an http request using synthetics, with execution id: ' + executionId);
  const url = 'https://www.google.com/'; // URL to send the request to
  return await assert.doesNotReject(axios.get(url));
}));

Puppeteer-Vorlage

Wenn Sie Puppeteer verwenden, sollten Sie mit dem Beispiel generic-puppeteer-nodejs beginnen.

Erforderliche Puppeteer-Einrichtung

Um Puppeteer zu verwenden, müssen Sie die folgenden Schritte ausführen:

  1. Fügen Sie .puppeteerrc.cjs in das Quellverzeichnis Ihrer Cloud Functions-Funktion ein:

    const { join } = require('path');
    
    /**
     * @type {import("puppeteer").Configuration}
     */
    module.exports = {
      cacheDirectory: join(__dirname, '.cache', 'puppeteer'),
    };
  2. Fügen Sie der Datei package.json Ihrer Cloud Functions-Funktion das folgende Skript hinzu:

    "scripts": {
         "gcp-build": "node node_modules/puppeteer/install.mjs"
    },
    

Puppeteer-Beispiel

Das Beispiel generic-puppeteer-nodejs zeigt, wie Puppeteer mit Ihrer Cloud Functions-Funktion verwendet wird.

Um das vollständige generic-puppeteer-nodejs-Beispiel anzusehen, klicken Sie auf das Dreipunkt-Menü und wählen Sie dann Auf GitHub ansehen aus:

const { instantiateAutoInstrumentation, runSyntheticHandler } = require('@google-cloud/synthetics-sdk-api');
// Run instantiateAutoInstrumentation before any other code runs, to get automatic logs and traces
instantiateAutoInstrumentation();
const functions = require('@google-cloud/functions-framework');
const axios = require('axios');
const assert = require('node:assert');
const puppeteer = require('puppeteer');


functions.http('CustomPuppeteerSynthetic', runSyntheticHandler(async ({logger, executionId}) => {
 /*
  * This function executes the synthetic code for testing purposes.
  * If the code runs without errors, the synthetic test is considered successful.
  * If an error is thrown during execution, the synthetic test is considered failed.
  */

 // Launch a headless Chrome browser and open a new page
 const browser = await puppeteer.launch({ headless: 'new', timeout: 0});
 const page = await browser.newPage();

 // Navigate to the target URL
 const result = await page.goto('https://www.example.com', {waitUntil: 'load'});

 // Confirm successful navigation
 await assert.equal(result.status(), 200);

 // Print the page title to the console
 const title = await page.title();
 logger.info(`My Page title: ${title} ` + executionId);

 // Close the browser
 await browser.close();
}));

Selenium WebDriver-Vorlage

Wenn Sie Selenium WebDriver verwenden, sollten Sie mit dem Beispiel generic-selenium-nodejs beginnen. Das Beispiel, das auf GitHub verfügbar ist, enthält die Dateien index.js und package.json.

Um das vollständige generic-selenium-nodejs-Beispiel anzusehen, klicken Sie auf das Dreipunkt-Menü und wählen Sie dann Auf GitHub ansehen aus:

const {
  instantiateAutoInstrumentation,
  runSyntheticHandler,
} = require('@google-cloud/synthetics-sdk-api');
// Run instantiateAutoInstrumentation before any other code runs, to get automatic logs and traces
instantiateAutoInstrumentation();
const functions = require('@google-cloud/functions-framework');
const assert = require('node:assert');

const { Builder, Browser, By } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');

/*
 * This function executes the synthetic code for testing purposes.
 * If the code runs without errors, the synthetic test is considered successful.
 * If an error is thrown during execution, the synthetic test is considered failed.
 */
functions.http(
  'CustomSeleniumSynthetic',
  runSyntheticHandler(async ({ logger, executionId }) => {
    /*
     * Construct chrome options
     * Note: `setChromeBinaryPath` must be set to '/srv/bin/chromium' when running in
     *   GCF (but will need to be changed if running on local machine).
     */
    const options = new chrome.Options();
    options.setChromeBinaryPath('/srv/bin/chromium');
    options.addArguments('--headless', '--disable-gpu', '--no-sandbox');

    // Launch headless chrome webdriver with options
    const driver = await new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options)
      .build();

    // Navigate to the target URL
    await driver.get('https://example.com');

    // Retrieve title and `a` tag of page
    const title = await driver.getTitle();
    const aTag = await driver.findElement(By.css('a')).getText();

    // assert title is as expected and print to console
    await assert.equal(title, 'Example Domain');
    logger.info(`My URL title is: ${title} ` + executionId);

    await driver.quit();
  })
);

Mocha-Vorlage

Wenn Sie Tests schreiben, die auf der Mocha-Vorlage basieren, überlegen Sie, ob eine Reihe von Tests fortgesetzt oder beendet werden soll, wenn ein Fehler auftritt. Wenn Sie eine Reihe von Tests nach einem Fehler beenden möchten, müssen Sie das Flag bail festlegen.

Ein End-to-End-Beispiel, das die Bereitstellung einer API, eine Mocha-Beispieltestsuite für die API-Endpunkte und die Konfiguration des synthetischen Monitors umfasst, finden Sie im Blog Anleitung zum synthetischen Monitoring von Google Cloud.

Das Beispiel mocha-url-ok zeigt, wie eine Cloud Functions-Funktion eine Mocha-Testsuite aufrufen kann, und bietet eine Beispieltestsuite.

Um das vollständige mocha-url-ok-Beispiel anzusehen, klicken Sie auf das Dreipunkt-Menü und wählen Sie dann Auf GitHub ansehen aus:


const functions = require('@google-cloud/functions-framework');
const GcmSynthetics = require('@google-cloud/synthetics-sdk-mocha');

/*
 * This is the server template that is required to run a synthetic monitor in
 * Google Cloud Functions.
 */

functions.http('SyntheticMochaSuite', GcmSynthetics.runMochaHandler({
  spec: `${__dirname}/mocha_tests.spec.js`
}));

/*
 * This is the file may be interacted with to author mocha tests. To interact
 * with other GCP products or services, users should add dependencies to the
 * package.json file, and require those dependencies here A few examples:
 *  - @google-cloud/secret-manager:
 *        https://www.npmjs.com/package/@google-cloud/secret-manager
 *  - @google-cloud/spanner: https://www.npmjs.com/package/@google-cloud/spanner
 *  - Supertest: https://www.npmjs.com/package/supertest
 */

const {expect} = require('chai');
const fetch = require('node-fetch');

it('pings my website', async () => {
  const url = 'https://google.com/'; // URL to send the request to
  const externalRes = await fetch(url);
  expect(externalRes.ok).to.be.true;
});

Das Beispiel broken-links-ok zeigt, wie eine Prüfung auf fehlerhafte Links konfiguriert wird. Für diese Vorlage geben Sie nur die Werte des Objekts options an. Dieses Objekt gibt den zu testenden URI und die Parameter des Tests an. Weitere Informationen findest du im folgenden Code:

Wenn Sie Puppeteer verwenden, führen Sie die erforderlichen Schritte zur Einrichtung von Puppeteer aus.

Um das vollständige broken-links-ok-Beispiel anzusehen, klicken Sie auf das Dreipunkt-Menü und wählen Sie dann Auf GitHub ansehen aus:


const functions = require('@google-cloud/functions-framework');
const GcmSynthetics = require('@google-cloud/synthetics-sdk-broken-links');

const options = {
  origin_uri: "https://example.com",
  // link_limit: 10,
  // query_selector_all: "a", // https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
  // get_attributes: ['href'], // https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
  // link_order: "FIRST_N", // "FIRST_N" or "RANDOM"
  // link_timeout_millis: 30000, // timeout per link
  // max_retries: 0, // number of retries per link if it failed for any reason
  // wait_for_selector: '', // https://pptr.dev/api/puppeteer.page.waitforselector
  // per_link_options: {},
    /*
    // example:
      per_link_options: {
        'http://fake-link1': { expected_status_code: "STATUS_CLASS_4XX" },
        'http://fake-link2': { expected_status_code: 304 },
        'http://fake-link3': { link_timeout_millis: 10000 },
        'http://fake-link4': {
          expected_status_code: "STATUS_CLASS_3XX",
          link_timeout_millis: 10,
        },
      },
    */
  // total_synthetic_timeout_millis: 60000 // Timeout set for the entire Synthetic Monitor
  // screenshot_options: { capture_condition: 'FAILING', storage_location: '' }
};

functions.http('BrokenLinkChecker', GcmSynthetics.runBrokenLinksHandler(options));

Nächste Schritte