합성 모니터 샘플

이 문서에서는 합성 모니터를 만드는 데 사용할 수 있는 템플릿과 샘플 코드를 설명합니다. 샘플 함수는 Google Cloud/synthetics-sdk-nodjs GitHub 저장소에서 사용할 수 있습니다.

테스트를 작성하고 템플릿을 사용하지 않는 경우 Error가 발생하지 않으면 테스트가 통과하는지 확인합니다. Assert 라이브러리를 사용하여 오류가 발생할 때 적절한 코드 줄에 기여했는지 확인하는 것이 좋습니다.

일반 템플릿

일반 템플릿은 아웃바운드 HTTP 요청의 trace 및 로그 데이터를 수집하도록 구성됩니다. 이 솔루션은 OpenTelemetry auto-Instrumentation-node 모듈과 winston logger를 활용합니다. 오픈소스 제품에 대한 종속 항목으로 인해 trace 및 로그 데이터 구조가 변경될 수 있습니다. 따라서 수집된 trace 및 로그 데이터는 디버깅 목적으로만 사용해야 합니다.

아웃바운드 HTTP 요청의 trace 및 로그 데이터를 수집하는 고유한 방법을 구현할 수 있습니다. 커스텀 방식의 예시는 SyntheticAutoInstrumentation 클래스를 참조하세요.

일반 Node.js 샘플

generic-synthetic-nodejs 샘플에서는 URL을 쿼리하는 방법을 보여줍니다. 이 샘플에는 Google Cloud 콘솔에 표시된 기본 함수와 동일한 값이 포함됩니다. 전체 샘플을 보려면 더보기를 클릭한 다음 GitHub에서 보기를 선택합니다.

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 샘플

generic-synthetic-typescript 샘플에서는 URL을 쿼리하는 방법을 보여줍니다. 전체 샘플을 보려면 더보기를 클릭한 다음 GitHub에서 보기를 선택합니다.

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 템플릿

Puppeteer를 사용하는 경우 generic-puppeteer-nodejs 샘플로 시작하는 것이 좋습니다.

필수 Puppeteer 설정

Puppeteer를 사용하려면 다음 단계를 완료해야 합니다.

  1. Cloud 함수의 소스 디렉터리에 .puppeteerrc.cjs를 포함합니다.

    const { join } = require('path');
    
    /**
     * @type {import("puppeteer").Configuration}
     */
    module.exports = {
      cacheDirectory: join(__dirname, '.cache', 'puppeteer'),
    };
  2. Cloud 함수의 package.json 파일에 다음 스크립트를 추가합니다.

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

Puppeteer 샘플

generic-puppeteer-nodejs 샘플에서는 Cloud 함수와 함께 Puppeteer를 사용하는 방법을 보여줍니다. 전체 샘플을 보려면 더보기를 클릭한 다음 GitHub에서 보기를 선택합니다.

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 템플릿

Selenium WebDriver를 사용하는 경우 generic-selenium-nodejs 샘플로 시작하는 것이 좋습니다. GitHub에서 사용할 수 있는 샘플에는 index.jspackage.json 파일이 포함됩니다.

전체 샘플을 보려면 더보기를 클릭한 다음 GitHub에서 보기를 선택합니다.

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 템플릿

Mocha 템플릿을 사용하는 테스트를 작성하는 경우 오류가 발생할 때 테스트 시퀀스를 계속할지 또는 중지할지 여부를 고려합니다. 실패 후 일련의 테스트를 중지하려면 bail 플래그를 설정해야 합니다.

API 배포, API 엔드포인트를 위한 샘플 Mocha 테스트 모음, 합성 모니터를 구성하는 방법을 포함하는 포괄적인 예시는 블로그 Google Cloud 합성 모니터링 튜토리얼을 참조하세요.

mocha-url-ok 샘플에서는 Cloud 함수가 Mocha 테스트 모음을 호출하는 방법을 보여주고 샘플 테스트 모음을 제공합니다. 전체 샘플을 보려면 더보기를 클릭한 다음 GitHub에서 보기를 선택합니다.


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;
});

broken-links-ok 샘플에서는 깨진 링크 검사기를 구성하는 방법을 보여줍니다. 이 템플릿에는 options 객체 값만 지정합니다. 이 객체는 테스트할 URI와 테스트 매개변수를 지정합니다.

Puppeteer를 사용하는 경우 필수 Puppeteer 설정 단계를 완료해야 합니다.

전체 샘플을 보려면 더보기를 클릭한 다음 GitHub에서 보기를 선택합니다.


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));

다음 단계