Skip to content
This repository has been archived by the owner on Jul 13, 2023. It is now read-only.

refactor: modernize and fix the sample tests #193

Merged
merged 1 commit into from
Dec 19, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion samples/metrics.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ async function createMetricDescriptor(projectId) {
descriptor.labels.forEach(label => {
console.log(` ${label.key} (${label.valueType}) - ${label.description}`);
});

// [END monitoring_create_metric]
}

Expand Down
9 changes: 4 additions & 5 deletions samples/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"name": "nodejs-docs-samples-monitoring",
"version": "0.0.1",
"private": true,
"license": "Apache-2.0",
"author": "Google Inc.",
Expand All @@ -12,17 +11,17 @@
"node": ">=8"
},
"scripts": {
"test": "mocha system-test/*.js --timeout 600000"
"test": "mocha system-test --timeout 600000"
},
"dependencies": {
"@google-cloud/monitoring": "^0.6.0",
"yargs": "^12.0.0"
},
"devDependencies": {
"@google-cloud/nodejs-repo-tools": "^3.0.0",
"chai": "^4.2.0",
"execa": "^1.0.0",
"mocha": "^5.0.0",
"proxyquire": "^2.0.1",
"sinon": "^7.0.0",
"p-retry": "^3.0.0",
"uuid": "^3.3.2"
}
}
9 changes: 5 additions & 4 deletions samples/quickstart.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@
// [START monitoring_quickstart]
// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');
async function quickStart() {

async function quickstart() {
// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';
const projectId = process.env.GCLOUD_PROJECT || 'YOUR_PROJECT_ID';

// Creates a client
const client = new monitoring.MetricServiceClient();
Expand Down Expand Up @@ -65,6 +66,6 @@ async function quickStart() {
const [result] = await client.createTimeSeries(request);
console.log(`Done writing time series data.`, result);
}

quickStart().catch(console.error);
// [END monitoring_quickstart]

quickstart().catch(console.error);
2 changes: 0 additions & 2 deletions samples/system-test/.eslintrc.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
---
env:
mocha: true
rules:
node/no-unpublished-require: off
209 changes: 102 additions & 107 deletions samples/system-test/alerts.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,25 @@

'use strict';

const fs = require(`fs`);
const monitoring = require(`@google-cloud/monitoring`);
const path = require(`path`);
const assert = require('assert');
const tools = require(`@google-cloud/nodejs-repo-tools`);
const monitoring = require('@google-cloud/monitoring');
const {assert} = require('chai');
const execa = require('execa');
const uuid = require('uuid');
const path = require('path');
const fs = require('fs');

const client = new monitoring.AlertPolicyServiceClient();
const channelClient = new monitoring.NotificationChannelServiceClient();
const cwd = path.join(__dirname, `..`);
const projectId = process.env.GCLOUD_PROJECT;
const cmd = 'node alerts';
const exec = async cmd => (await execa.shell(cmd)).stdout;

let policyOneName, policyTwoName, channelName;

const testPrefix = `gcloud-test-${uuid.v4().split('-')[0]}`;

before(tools.checkCredentials);
before(async () => {
try {
tools.checkCredentials;
describe('alerts', () => {
before(async () => {
await reapPolicies();
let results = await client.createAlertPolicy({
name: client.projectPath(projectId),
alertPolicy: {
Expand All @@ -48,7 +47,8 @@ before(async () => {
{
displayName: 'Condition 1',
conditionAbsent: {
filter: `resource.type = "cloud_function" AND metric.type = "cloudfunctions.googleapis.com/function/execution_count"`,
filter:
'resource.type = "cloud_function" AND metric.type = "cloudfunctions.googleapis.com/function/execution_count"',
aggregations: [
{
alignmentPeriod: {
Expand Down Expand Up @@ -79,7 +79,8 @@ before(async () => {
{
displayName: 'Condition 2',
conditionAbsent: {
filter: `resource.type = "cloud_function" AND metric.type = "cloudfunctions.googleapis.com/function/execution_count"`,
filter:
'resource.type = "cloud_function" AND metric.type = "cloudfunctions.googleapis.com/function/execution_count"',
aggregations: [
{
alignmentPeriod: {
Expand Down Expand Up @@ -112,108 +113,102 @@ before(async () => {
},
});
channelName = results[0].name;
} catch (err) {
// ignore error
});

/**
* Delete any policies created by a test that's older than 2 minutes.
*/
async function reapPolicies() {
const [policies] = await client.listAlertPolicies({
name: client.projectPath(projectId),
});
const crustyPolicies = policies
.filter(p => p.displayName.match(/^gcloud-test-/))
.filter(p => {
const minutesOld =
(Date.now() - p.creationRecord.mutateTime.seconds * 1000) / 1000 / 60;
return minutesOld > 2;
});
// This is serial on purpose. When trying to delete all alert policies in
// parallel, all of the promises return successful, but then only 2?
// get deleted. Super, super bizarre.
// https://github.com/googleapis/nodejs-monitoring/issues/192
for (const p of crustyPolicies) {
console.log(`\tReaping ${p.name}...`);
await client.deleteAlertPolicy({name: p.name});
}
}
});

async function deletePolicies() {
await client.deleteAlertPolicy({
name: policyOneName,
});
await client.deleteAlertPolicy({
name: policyTwoName,
});
}
async function deletePolicies() {
await client.deleteAlertPolicy({
name: policyOneName,
});
await client.deleteAlertPolicy({
name: policyTwoName,
});
}

async function deleteChannels() {
await channelClient.deleteNotificationChannel({
name: channelName,
force: true,
});
}
async function deleteChannels() {
await channelClient.deleteNotificationChannel({
name: channelName,
force: true,
});
}

after(async () => {
await deletePolicies();
// has to be done after policies are deleted
await deleteChannels();
});
after(async () => {
await deletePolicies();
// has to be done after policies are deleted
await deleteChannels();
});

it(`should replace notification channels`, async () => {
const results = await tools.spawnAsyncWithIO(
`node`,
[`alerts.js`, `replace`, policyOneName, channelName],
cwd
);
assert.strictEqual(results.output.includes('Updated projects'), true);
assert.strictEqual(results.output.includes(policyOneName), true);
});
it('should replace notification channels', async () => {
const stdout = await exec(`${cmd} replace ${policyOneName} ${channelName}`);
assert.match(stdout, /Updated projects/);
assert.match(stdout, new RegExp(policyOneName));
});

it(`should disable policies`, async () => {
const results = await tools.spawnAsyncWithIO(
`node`,
[`alerts.js`, `disable`, projectId, `'display_name.size < 28'`],
cwd
);
assert.strictEqual(results.output.includes('Disabled projects'), true);
assert.strictEqual(results.output.includes(policyOneName), false);
assert.strictEqual(results.output.includes(policyTwoName), true);
});
it('should disable policies', async () => {
const stdout = await exec(
`${cmd} disable ${projectId} 'display_name.size < 28'`
);
assert.match(stdout, /Disabled projects/);
assert.notMatch(stdout, new RegExp(policyOneName));
assert.match(stdout, new RegExp(policyTwoName));
});

it(`should enable policies`, async () => {
const results = await tools.spawnAsyncWithIO(
`node`,
[`alerts.js`, `enable`, projectId, `'display_name.size < 28'`],
cwd
);
assert.strictEqual(results.output.includes('Enabled projects'), true);
assert.strictEqual(results.output.includes(policyOneName), false);
assert.strictEqual(results.output.includes(policyTwoName), true);
});
it('should enable policies', async () => {
const stdout = await exec(
`${cmd} enable ${projectId} 'display_name.size < 28'`
);
assert.match(stdout, /Enabled projects/);
assert.notMatch(stdout, new RegExp(policyOneName));
assert.match(stdout, new RegExp(policyTwoName));
});

it(`should list policies`, async () => {
const results = await tools.spawnAsyncWithIO(
`node`,
[`alerts.js`, `list`, projectId],
cwd
);
assert.strictEqual(results.output.includes('Policies:'), true);
assert.strictEqual(results.output.includes('first-policy'), true);
assert.strictEqual(results.output.includes('Test'), true);
assert.strictEqual(results.output.includes('second'), true);
});
it('should list policies', async () => {
const stdout = await exec(`${cmd} list ${projectId}`);
assert.match(stdout, /Policies:/);
assert.match(stdout, /first-policy/);
assert.match(stdout, /Test/);
assert.match(stdout, /second/);
});

it(`should backup all policies`, async () => {
const results = await tools.spawnAsyncWithIO(
`node`,
[`alerts.js`, `backup`, projectId],
cwd
);
assert.strictEqual(
results.output.includes('Saved policies to ./policies_backup.json'),
true
);
assert.strictEqual(
fs.existsSync(path.join(cwd, `policies_backup.json`)),
true
);
await client.deleteAlertPolicy({name: policyOneName});
});
it('should backup all policies', async () => {
const output = await exec(`${cmd} backup ${projectId}`);
assert.match(output, /Saved policies to .\/policies_backup.json/);
assert.ok(fs.existsSync(path.join(__dirname, '../policies_backup.json')));
await client.deleteAlertPolicy({name: policyOneName});
});

it(`should restore policies`, async () => {
const results = await tools.spawnAsyncWithIO(
`node`,
[`alerts.js`, `restore`, projectId],
cwd
);
assert.strictEqual(
results.output.includes('Loading policies from ./policies_backup.json'),
true
);
const nameRegexp = /projects\/[A-Za-z0-9-]+\/alertPolicies\/([\d]+)/gi;
const matches = results.output.match(nameRegexp);
assert.strictEqual(Array.isArray(matches), true);
assert(matches.length > 1);
policyOneName = matches[0];
policyTwoName = matches[1];
it('should restore policies', async () => {
const output = await exec(`${cmd} restore ${projectId}`);
assert.match(output, /Loading policies from .\/policies_backup.json/);
const matches = output.match(
/projects\/[A-Za-z0-9-]+\/alertPolicies\/([\d]+)/gi
);
assert.ok(Array.isArray(matches));
assert(matches.length > 1);
policyOneName = matches[0];
policyTwoName = matches[1];
});
});
Loading