From 23b1b0422a801caef65c44cc80658e8c9d86dc62 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Tue, 18 Dec 2018 12:23:25 -0800 Subject: [PATCH] refactor: modernize and fix the sample tests --- samples/metrics.js | 1 - samples/package.json | 9 +- samples/quickstart.js | 9 +- samples/system-test/.eslintrc.yml | 2 - samples/system-test/alerts.test.js | 209 +++++++++-------- samples/system-test/metrics.test.js | 305 ++++++++++++------------- samples/system-test/quickstart.test.js | 53 ++--- samples/system-test/uptime.test.js | 166 ++++++-------- 8 files changed, 349 insertions(+), 405 deletions(-) diff --git a/samples/metrics.js b/samples/metrics.js index 4c3f492d..bf52b0dd 100644 --- a/samples/metrics.js +++ b/samples/metrics.js @@ -68,7 +68,6 @@ async function createMetricDescriptor(projectId) { descriptor.labels.forEach(label => { console.log(` ${label.key} (${label.valueType}) - ${label.description}`); }); - // [END monitoring_create_metric] } diff --git a/samples/package.json b/samples/package.json index e4ec5035..7128c148 100644 --- a/samples/package.json +++ b/samples/package.json @@ -1,6 +1,5 @@ { "name": "nodejs-docs-samples-monitoring", - "version": "0.0.1", "private": true, "license": "Apache-2.0", "author": "Google Inc.", @@ -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" } } diff --git a/samples/quickstart.js b/samples/quickstart.js index fbd123c8..924691c0 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -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(); @@ -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); diff --git a/samples/system-test/.eslintrc.yml b/samples/system-test/.eslintrc.yml index 73f7bbc9..6db2a46c 100644 --- a/samples/system-test/.eslintrc.yml +++ b/samples/system-test/.eslintrc.yml @@ -1,5 +1,3 @@ --- env: mocha: true -rules: - node/no-unpublished-require: off diff --git a/samples/system-test/alerts.test.js b/samples/system-test/alerts.test.js index 2fb38c03..1810b86a 100644 --- a/samples/system-test/alerts.test.js +++ b/samples/system-test/alerts.test.js @@ -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: { @@ -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: { @@ -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: { @@ -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]; + }); }); diff --git a/samples/system-test/metrics.test.js b/samples/system-test/metrics.test.js index f74fffca..f80e4f3c 100644 --- a/samples/system-test/metrics.test.js +++ b/samples/system-test/metrics.test.js @@ -15,193 +15,182 @@ 'use strict'; -const monitoring = require(`@google-cloud/monitoring`); -const client = new monitoring.MetricServiceClient(); -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 retry = require('p-retry'); +const exec = async cmd => (await execa.shell(cmd)).stdout; +const client = new monitoring.MetricServiceClient(); const cmd = `node metrics.js`; -const cwd = path.join(__dirname, `..`); const customMetricId = `custom.googleapis.com/stores/daily_sales`; const computeMetricId = `compute.googleapis.com/instance/cpu/utilization`; const filter = `metric.type="${computeMetricId}"`; const projectId = process.env.GCLOUD_PROJECT; const resourceId = `cloudsql_database`; -before(tools.checkCredentials); - -it(`should create a metric descriptors`, async () => { - const output = await tools.runAsync(`${cmd} create`, cwd); - assert.strictEqual(output.includes(`Created custom Metric`), true); - assert.strictEqual(output.includes(`Type: ${customMetricId}`), true); -}); +describe('metrics', () => { + it('should create a metric descriptors', async () => { + const output = await exec(`${cmd} create`); + assert.match(output, /Created custom Metric/); + assert.match(output, new RegExp(`Type: ${customMetricId}`)); + }); -it(`should list metric descriptors, including the new custom one`, async () => { - const attempt = tools.tryTest(async assert => { - const output = await tools.runAsync(`${cmd} list`, cwd); - assert(output.includes(customMetricId)); - assert(output.includes(computeMetricId)); + it('should list metric descriptors, including the new custom one', async () => { + // The write above appears to be eventually consistent. This retry should + // not be needed. The tracking bug is here: + // https://github.com/googleapis/nodejs-monitoring/issues/190 + await retry( + async () => { + const output = await exec(`${cmd} list`); + assert.match(output, new RegExp(customMetricId)); + assert.match(output, new RegExp(computeMetricId)); + }, + { + retries: 10, + onFailedAttempt: () => console.warn('Read failed, retrying...'), + } + ); }); - attempt.tries(30); - attempt.timeout(120000); - await attempt.start(); -}); -it(`should get a metric descriptor`, async () => { - const attempt = tools.tryTest(async assert => { - const output = await tools.runAsync(`${cmd} get ${customMetricId}`, cwd); - assert(output.includes(`Type: ${customMetricId}`)); + it('should get a metric descriptor', async () => { + const output = await exec(`${cmd} get ${customMetricId}`); + assert.match(output, new RegExp(`Type: ${customMetricId}`)); }); - attempt.tries(30); - attempt.timeout(120000); - await attempt.start(); -}); -it(`should write time series data`, async () => { - const output = await tools.runAsync(`${cmd} write`, cwd); - assert.strictEqual(output.includes(`Done writing time series data.`), true); -}); + it('should write time series data', async () => { + const output = await exec(`${cmd} write`); + assert.match(output, /Done writing time series data./); + }); -it(`should delete a metric descriptor`, async () => { - const output = await tools.runAsync(`${cmd} delete ${customMetricId}`, cwd); - assert.strictEqual(output.includes(`Deleted ${customMetricId}`), true); -}); + it('should delete a metric descriptor', async () => { + const output = await exec(`${cmd} delete ${customMetricId}`); + assert.match(output, new RegExp(`Deleted ${customMetricId}`)); + }); -it(`should list monitored resource descriptors`, async () => { - const output = await tools.runAsync(`${cmd} list-resources`, cwd); - assert.strictEqual( - output.includes( - `projects/${projectId}/monitoredResourceDescriptors/${resourceId}` - ), - true - ); -}); + it('should list monitored resource descriptors', async () => { + const output = await exec(`${cmd} list-resources`); + assert.match( + output, + new RegExp( + `projects/${projectId}/monitoredResourceDescriptors/${resourceId}` + ) + ); + }); -it(`should get a monitored resource descriptor`, async () => { - const output = await tools.runAsync(`${cmd} get-resource ${resourceId}`, cwd); - assert.strictEqual(output.includes(`Type: ${resourceId}`), true); -}); + it('should get a monitored resource descriptor', async () => { + const output = await exec(`${cmd} get-resource ${resourceId}`); + assert.match(output, new RegExp(`Type: ${resourceId}`)); + }); -it(`should read time series data`, async () => { - const [timeSeries] = await client.listTimeSeries({ - name: client.projectPath(projectId), - filter: filter, - interval: { - startTime: { - // Limit results to the last 20 minutes - seconds: Date.now() / 1000 - 60 * 20, - }, - endTime: { - seconds: Date.now() / 1000, + it('should read time series data', async () => { + const [timeSeries] = await client.listTimeSeries({ + name: client.projectPath(projectId), + filter: filter, + interval: { + startTime: { + // Limit results to the last 20 minutes + seconds: Date.now() / 1000 - 60 * 20, + }, + endTime: { + seconds: Date.now() / 1000, + }, }, - }, - }); - const output = await tools.runAsync(`${cmd} read '${filter}'`, cwd); - //t.true(true); // Do not fail if there is simply no data to return. - timeSeries.forEach(data => { - assert.strictEqual( - output.includes(`${data.metric.labels.instance_name}:`), - true - ); - data.points.forEach(point => { - assert.strictEqual(output.includes(JSON.stringify(point.value)), true); + }); + const output = await exec(`${cmd} read '${filter}'`); + //t.true(true); // Do not fail if there is simply no data to return. + timeSeries.forEach(data => { + assert.match(output, new RegExp(`${data.metric.labels.instance_name}:`)); + data.points.forEach(point => { + assert.match(output, new RegExp(JSON.stringify(point.value))); + }); }); }); -}); -it(`should read time series data fields`, async () => { - const [timeSeries] = await client.listTimeSeries({ - name: client.projectPath(projectId), - filter: filter, - interval: { - startTime: { - // Limit results to the last 20 minutes - seconds: Date.now() / 1000 - 60 * 20, - }, - endTime: { - seconds: Date.now() / 1000, + it('should read time series data fields', async () => { + const [timeSeries] = await client.listTimeSeries({ + name: client.projectPath(projectId), + filter: filter, + interval: { + startTime: { + // Limit results to the last 20 minutes + seconds: Date.now() / 1000 - 60 * 20, + }, + endTime: { + seconds: Date.now() / 1000, + }, }, - }, - // Don't return time series data, instead just return information about - // the metrics that match the filter - view: `HEADERS`, - }); - const output = await tools.runAsync(`${cmd} read-fields`, cwd); - assert.strictEqual( - output.includes(`Found data points for the following instances:`), - true - ); - timeSeries.forEach(data => { - assert.strictEqual(output.includes(data.metric.labels.instance_name), true); + // Don't return time series data, instead just return information about + // the metrics that match the filter + view: `HEADERS`, + }); + const output = await exec(`${cmd} read-fields`); + assert.match(output, /Found data points for the following instances/); + timeSeries.forEach(data => { + assert.match(output, new RegExp(data.metric.labels.instance_name)); + }); }); -}); -it(`should read time series data aggregated`, async () => { - const [timeSeries] = await client.listTimeSeries({ - name: client.projectPath(projectId), - filter: filter, - interval: { - startTime: { - // Limit results to the last 20 minutes - seconds: Date.now() / 1000 - 60 * 20, + it('should read time series data aggregated', async () => { + const [timeSeries] = await client.listTimeSeries({ + name: client.projectPath(projectId), + filter: filter, + interval: { + startTime: { + // Limit results to the last 20 minutes + seconds: Date.now() / 1000 - 60 * 20, + }, + endTime: { + seconds: Date.now() / 1000, + }, }, - endTime: { - seconds: Date.now() / 1000, + // Aggregate results per matching instance + aggregation: { + alignmentPeriod: { + seconds: 600, + }, + perSeriesAligner: `ALIGN_MEAN`, }, - }, - // Aggregate results per matching instance - aggregation: { - alignmentPeriod: { - seconds: 600, - }, - perSeriesAligner: `ALIGN_MEAN`, - }, - }); - const output = await tools.runAsync(`${cmd} read-aggregate`, cwd); - assert.strictEqual(output.includes('CPU utilization:'), true); - timeSeries.forEach(data => { - assert.strictEqual( - new RegExp(data.metric.labels.instance_name).test(output), - true - ); - assert.strictEqual(output.includes(' Now: 0.'), true); - assert.strictEqual(output.includes(' 10 min ago: 0.'), true); + }); + const output = await exec(`${cmd} read-aggregate`); + assert.match(output, /CPU utilization:/); + timeSeries.forEach(data => { + assert.match(output, new RegExp(data.metric.labels.instance_name)); + assert.match(output, / Now: 0./); + assert.match(output, / 10 min ago: 0./); + }); }); -}); -it(`should read time series data reduced`, async () => { - await client.listTimeSeries({ - name: client.projectPath(projectId), - filter: filter, - interval: { - startTime: { - // Limit results to the last 20 minutes - seconds: Date.now() / 1000 - 60 * 20, - }, - endTime: { - seconds: Date.now() / 1000, + it('should read time series data reduced', async () => { + await client.listTimeSeries({ + name: client.projectPath(projectId), + filter: filter, + interval: { + startTime: { + // Limit results to the last 20 minutes + seconds: Date.now() / 1000 - 60 * 20, + }, + endTime: { + seconds: Date.now() / 1000, + }, }, - }, - // Aggregate results per matching instance - aggregation: { - alignmentPeriod: { - seconds: 600, + // Aggregate results per matching instance + aggregation: { + alignmentPeriod: { + seconds: 600, + }, + crossSeriesReducer: `REDUCE_MEAN`, + perSeriesAligner: `ALIGN_MEAN`, }, - crossSeriesReducer: `REDUCE_MEAN`, - perSeriesAligner: `ALIGN_MEAN`, - }, + }); + const output = await exec(`${cmd} read-reduce`); + // Special case: No output. + if (output === 'No data') { + assert.match(output, /No data/); + } else { + assert.match(output, /Average CPU utilization across all GCE instances:/); + assert.match(output, / {2}Last 10 min/); + assert.match(output, / {2}10-20 min ago/); + } }); - const output = await tools.runAsync(`${cmd} read-reduce`, cwd); - // Special case: No output. - if (output === 'No data') { - assert.strictEqual(output.includes('No data'), true); - } else { - assert.strictEqual( - output.includes(`Average CPU utilization across all GCE instances:`), - true - ); - assert.strictEqual(output.includes(` Last 10 min`), true); - assert.strictEqual(output.includes(` 10-20 min ago`), true); - } }); diff --git a/samples/system-test/quickstart.test.js b/samples/system-test/quickstart.test.js index 388761e2..fe570fb9 100644 --- a/samples/system-test/quickstart.test.js +++ b/samples/system-test/quickstart.test.js @@ -15,41 +15,24 @@ 'use strict'; -const proxyquire = require(`proxyquire`).noPreserveCache(); -const sinon = require(`sinon`); -const assert = require('assert'); +const {assert} = require('chai'); +const execa = require('execa'); +const retry = require('p-retry'); -const monitoring = proxyquire(`@google-cloud/monitoring`, {}); -const client = new monitoring.MetricServiceClient(); - -it(`should list time series`, async () => { - const clientMock = { - projectPath: projectId => client.projectPath(projectId), - createTimeSeries: async _request => { - _request.name = client.projectPath(process.env.GCLOUD_PROJECT); - _request.timeSeries[0].resource.labels.project_id = - process.env.GCLOUD_PROJECT; - - const result = await client.createTimeSeries(_request); - setTimeout(() => { - try { - assert.strictEqual(console.log.callCount, 1); - assert.deepStrictEqual(console.log.getCall(0).args, [ - `Done writing time series data.`, - {}, - ]); - } catch (err) { - // ignore error - } - }, 200); - - return result; - }, - }; - - proxyquire(`../quickstart`, { - '@google-cloud/monitoring': { - MetricServiceClient: sinon.stub().returns(clientMock), - }, +describe('quickstart', () => { + it('should run the quickstart', async () => { + // The write in the quickstart appears to be very, very flaky. + // This should not be needed. The tracking bug is here: + // https://github.com/googleapis/nodejs-monitoring/issues/191 + await retry( + async () => { + const result = await execa.shell('node quickstart'); + assert.match(result.stdout, /Done writing time series data/); + }, + { + retries: 10, + onFailedAttempt: () => console.warn('Write failed, retrying...'), + } + ); }); }); diff --git a/samples/system-test/uptime.test.js b/samples/system-test/uptime.test.js index 7a4a4a44..a7505a03 100644 --- a/samples/system-test/uptime.test.js +++ b/samples/system-test/uptime.test.js @@ -15,14 +15,13 @@ 'use strict'; -const path = require(`path`); -const assert = require('assert'); -const tools = require(`@google-cloud/nodejs-repo-tools`); +const {assert} = require('chai'); +const execa = require('execa'); -const cmd = `node uptime.js`; -const cwd = path.join(__dirname, `..`); +const cmd = 'node uptime.js'; const projectId = process.env.GCLOUD_PROJECT; const hostname = 'mydomain.com'; +const exec = async cmd => (await execa.shell(cmd)).stdout; function getResourceObjects(output) { const regex = new RegExp(/^\s*Resource: (.*)$/gm); @@ -34,98 +33,79 @@ function getResourceObjects(output) { return result; } -before(tools.checkCredentials); +describe('uptime', () => { + it('should list uptime-check ips', async () => { + const output = await exec(`${cmd} list-ips`); + assert.match(output, /USA/); + }); -it(`should list uptime-check ips`, async () => { - assert.strictEqual( - (await tools.runAsync(`${cmd} list-ips`, cwd)).includes('USA'), - true - ); -}); - -let id; + let id; -it(`should create an uptime check`, async () => { - const results = await tools.runAsyncWithIO(`${cmd} create ${hostname}`, cwd); - const output = results.stdout + results.stderr; - const matches = output.match( - new RegExp(`ID: projects/${projectId}/uptimeCheckConfigs/(.+)`) - ); - id = matches[1]; - assert.strictEqual(output.includes('Uptime check created:'), true); - const resources = getResourceObjects(output); - assert.strictEqual(resources[0]['type'], 'uptime_url'); - assert.strictEqual(resources[0]['labels']['host'], hostname); - assert.strictEqual(output.includes('Display Name: My Uptime Check'), true); -}); + it('should create an uptime check', async () => { + const output = await exec(`${cmd} create ${hostname}`); + const matches = output.match( + new RegExp(`ID: projects/${projectId}/uptimeCheckConfigs/(.+)`) + ); + id = matches[1]; + assert.match(output, /Uptime check created:/); + const resources = getResourceObjects(output); + assert.strictEqual(resources[0]['type'], 'uptime_url'); + assert.strictEqual(resources[0]['labels']['host'], hostname); + assert.match(output, /Display Name: My Uptime Check/); + }); -it(`should get an uptime check`, async () => { - const results = await tools.runAsyncWithIO(`${cmd} get ${id}`, cwd); - const output = results.stdout + results.stderr; - assert.strictEqual( - new RegExp( - `Retrieving projects/${projectId}/uptimeCheckConfigs/${id}` - ).test(output), - true - ); - const resources = getResourceObjects(output); - assert.strictEqual(resources[0]['type'], 'uptime_url'); - assert.strictEqual(resources[0]['labels']['host'], hostname); -}); + it('should get an uptime check', async () => { + const output = await exec(`${cmd} get ${id}`); + assert.match( + output, + new RegExp(`Retrieving projects/${projectId}/uptimeCheckConfigs/${id}`) + ); + const resources = getResourceObjects(output); + assert.strictEqual(resources[0]['type'], 'uptime_url'); + assert.strictEqual(resources[0]['labels']['host'], hostname); + }); -it(`should list uptime checks`, async () => { - await tools - .tryTest(async assert => { - const results = await tools.runAsyncWithIO(`${cmd} list`, cwd); - const output = results.stdout + results.stderr; - const resources = getResourceObjects(output); - assert( - resources.filter( - resource => - resource['type'] === 'uptime_url' && - resource['labels']['host'] === hostname - ).length > 0 - ); - assert(/Display Name: My Uptime Check/.test(output)); - }) - .start(); -}); + it('should list uptime checks', async () => { + const output = await exec(`${cmd} list`); + const resources = getResourceObjects(output); + const resourceCount = resources.filter( + resource => + resource['type'] === 'uptime_url' && + resource['labels']['host'] === hostname + ).length; + assert.isAbove(resourceCount, 0); + assert.match(output, /Display Name: My Uptime Check/); + }); -it(`should update an uptime check`, async () => { - const newDisplayName = 'My New Display'; - const path = '/'; - const results = await tools.runAsyncWithIO( - `${cmd} update ${id} "${newDisplayName}" ${path}`, - cwd - ); - const output = results.stdout + results.stderr; - assert.strictEqual( - new RegExp( - `Updating projects/${projectId}/uptimeCheckConfigs/${id} to ${newDisplayName}` - ).test(output), - true - ); - assert.strictEqual( - new RegExp( - `projects/${projectId}/uptimeCheckConfigs/${id} config updated.` - ).test(output), - true - ); -}); + it('should update an uptime check', async () => { + const newDisplayName = 'My New Display'; + const path = '/'; + const output = await exec( + `${cmd} update ${id} "${newDisplayName}" ${path}` + ); + assert.match( + output, + new RegExp( + `Updating projects/${projectId}/uptimeCheckConfigs/${id} to ${newDisplayName}` + ) + ); + assert.match( + output, + new RegExp( + `projects/${projectId}/uptimeCheckConfigs/${id} config updated.` + ) + ); + }); -it(`should delete an uptime check`, async () => { - const results = await tools.runAsyncWithIO(`${cmd} delete ${id}`, cwd); - const output = results.stdout + results.stderr; - assert.strictEqual( - new RegExp(`Deleting projects/${projectId}/uptimeCheckConfigs/${id}`).test( - output - ), - true - ); - assert.strictEqual( - new RegExp(`projects/${projectId}/uptimeCheckConfigs/${id} deleted.`).test( - output - ), - true - ); + it('should delete an uptime check', async () => { + const output = await exec(`${cmd} delete ${id}`); + assert.match( + output, + new RegExp(`Deleting projects/${projectId}/uptimeCheckConfigs/${id}`) + ); + assert.match( + output, + new RegExp(`projects/${projectId}/uptimeCheckConfigs/${id} deleted.`) + ); + }); });