From a63ebb797a359b58475224065173a4ece2f790de Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Wed, 12 Dec 2018 14:38:45 -0800 Subject: [PATCH] fix: improve the samples and tests (#236) --- compute/package.json | 6 +- compute/startup-script/index.js | 70 +++++++++++-------- .../startup-script/system-test/index.test.js | 26 +++---- compute/system-test/vms.test.js | 13 ++-- compute/system-test/vms_api.test.js | 13 ++-- compute/vms_api.js | 43 ++++-------- 6 files changed, 79 insertions(+), 92 deletions(-) diff --git a/compute/package.json b/compute/package.json index 94f63598f1..cca1f5d12b 100644 --- a/compute/package.json +++ b/compute/package.json @@ -5,7 +5,9 @@ "license": "Apache-2.0", "author": "Google Inc.", "repository": "googleapis/nodejs-compute", - "files": [ "*.js" ], + "files": [ + "*.js" + ], "engines": { "node": ">=8" }, @@ -25,6 +27,8 @@ }, "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" } diff --git a/compute/startup-script/index.js b/compute/startup-script/index.js index b3b9e2836a..4f09b3d830 100644 --- a/compute/startup-script/index.js +++ b/compute/startup-script/index.js @@ -19,10 +19,13 @@ const Compute = require('@google-cloud/compute'); const fetch = require('node-fetch'); const compute = new Compute(); - const zone = compute.zone('us-central1-a'); -async function createVm(name) { +/** + * Create a new virtual machine with Ubuntu and Apache + * @param {string} name Name of the virtual machine + */ +async function createVM(name) { // Create a new VM, using default ubuntu image. The startup script // installs apache and a custom homepage. @@ -34,7 +37,7 @@ async function createVm(name) { { key: 'startup-script', value: `#! /bin/bash - + # Installs apache and a custom homepage apt-get update apt-get install -y apache2 @@ -46,21 +49,35 @@ async function createVm(name) { ], }, }; - const vmObj = zone.vm(name); - console.log('Creating VM ...'); - const [vm, operation] = await vmObj.create(config); + + const vm = zone.vm(name); + + console.log(`Creating VM ${name}...`); + const [, operation] = await vm.create(config); + + console.log(`Polling operation ${operation.id}...`); await operation.promise(); + + console.log('Acquiring VM metadata...'); const [metadata] = await vm.getMetadata(); + console.log(metadata); // External IP of the VM. const ip = metadata.networkInterfaces[0].accessConfigs[0].natIP; console.log(`Booting new VM with IP http://${ip}...`); // Ping the VM to determine when the HTTP server is ready. + console.log(`Operation complete. Waiting for IP ...`); await pingVM(ip); + + console.log(`${name} created succesfully`); return ip; } +/** + * Poll a given IP address until it returns a result. + * @param {string} ip IP address to poll + */ async function pingVM(ip) { let waiting = true; while (waiting) { @@ -80,10 +97,12 @@ async function pingVM(ip) { } } } -// List all VMs and their external IPs in a given zone. -async function listVms() { +/** + * List all VMs and their external IPs in a given zone. + */ +async function listVMs() { const [vms] = await zone.getVMs(); - return await Promise.all( + const results = await Promise.all( vms.map(async vm => { const [metadata] = await vm.getMetadata(); return { @@ -94,31 +113,26 @@ async function listVms() { }; }) ); + console.log(results); + return results; } -async function deleteVm(name) { +/** + * Delete a VM with a given name. + * @param {string} name + */ +async function deleteVM(name) { const vm = zone.vm(name); - console.log('Deleting ...'); + console.log(`Deleting ${name} ...`); const [operation] = await vm.delete(); + console.log(`Polling operation ${operation.id} ...`); await operation.promise(); - // VM deleted + console.log(`${name} deleted succesfully!`); return name; } -exports.create = async name => { - const ip = await createVm(name); - console.log(`${name} created succesfully`); - return ip; -}; - -exports.list = async () => { - const vms = await listVms(); - console.log(vms); - return vms; -}; - -exports.delete = async name => { - const result = await deleteVm(name); - console.log(`${name} deleted succesfully`); - return result; +module.exports = { + createVM, + deleteVM, + listVMs, }; diff --git a/compute/startup-script/system-test/index.test.js b/compute/startup-script/system-test/index.test.js index 824106322d..e6eadacb98 100644 --- a/compute/startup-script/system-test/index.test.js +++ b/compute/startup-script/system-test/index.test.js @@ -15,36 +15,26 @@ 'use strict'; -const tools = require(`@google-cloud/nodejs-repo-tools`); const uuid = require('uuid'); const assert = require('assert'); -const example = require(`../index`); +const example = require('../index'); +const name = `gcloud-apache-${uuid.v4().split('-')[0]}`; describe('start-up script', async () => { - before(tools.checkCredentials); - beforeEach(tools.stubConsole); - afterEach(tools.restoreConsole); - - const TESTS_PREFIX = 'gcloud-tests-'; - const name = generateName('vm-with-apache'); - - function generateName(customPrefix) { - return [TESTS_PREFIX, customPrefix + '-', uuid.v4().replace('-', '')] - .join('') - .substr(0, 61); - } it('should create vm', async () => { - const ip = await example.create(name); + const ip = await example.createVM(name); assert.ok(ip); }); + it('should list vms', async () => { - const vms = await example.list(); + const vms = await example.listVMs(); assert.ok(vms); - assert.strictEqual(Array.isArray(vms), true); + assert.ok(Array.isArray(vms)); }); + it('should delete vm', async () => { - const result = await example.delete(name); + const result = await example.deleteVM(name); assert.strictEqual(result, name); }); }); diff --git a/compute/system-test/vms.test.js b/compute/system-test/vms.test.js index 16a5365647..ff6a6d859f 100644 --- a/compute/system-test/vms.test.js +++ b/compute/system-test/vms.test.js @@ -15,17 +15,16 @@ 'use strict'; -const tools = require(`@google-cloud/nodejs-repo-tools`); +const execa = require('execa'); const path = require(`path`); -const assert = require('assert'); +const {assert} = require('chai'); const cmd = `node vms.js`; const cwd = path.join(__dirname, `..`); -describe('should retrieve list of vms', function() { - it('vms_inspect_string', async function() { - const output = await tools.runAsync(cmd, cwd); - - assert.strictEqual(output.includes('VMs:'), true); +describe('should retrieve list of vms', () => { + it('vms_inspect_string', async () => { + const {stdout} = await execa.shell(cmd, {cwd}); + assert.match(stdout, /^VMs:/); }); }); diff --git a/compute/system-test/vms_api.test.js b/compute/system-test/vms_api.test.js index 026ee14965..b53e60af1d 100644 --- a/compute/system-test/vms_api.test.js +++ b/compute/system-test/vms_api.test.js @@ -15,17 +15,16 @@ 'use strict'; -const tools = require(`@google-cloud/nodejs-repo-tools`); +const execa = require(`execa`); const path = require(`path`); -const assert = require('assert'); +const {assert} = require('chai'); const cmd = `node vms_api.js`; const cwd = path.join(__dirname, `..`); -describe('should retrieve list of vms via api', function() { - it('vms_api_inspect_string', async function() { - const output = await tools.runAsync(cmd, cwd); - - assert.strictEqual(output.includes('VMs:'), true); +describe('should retrieve list of vms via api', () => { + it('vms_api_inspect_string', async () => { + const {stdout} = await execa.shell(cmd, {cwd}); + assert.match(stdout, /^VMs:/); }); }); diff --git a/compute/vms_api.js b/compute/vms_api.js index c92b16f1d9..ea9ab7fed5 100644 --- a/compute/vms_api.js +++ b/compute/vms_api.js @@ -17,51 +17,32 @@ // [START complete] // [START initialize] -const google = require('googleapis').google; +const {google} = require('googleapis'); const compute = google.compute('v1'); // [END initialize] -// [START auth] -async function auth() { - const data = await google.auth.getApplicationDefault(); - let authClient = data.credential; - const projectId = authClient.projectId; - - // The createScopedRequired method returns true when running on GAE or a - // local developer machine. In that case, the desired scopes must be passed - // in manually. When the code is running in GCE or GAE Flexible, the scopes - // are pulled from the GCE metadata server. - // See https://cloud.google.com/compute/docs/authentication for more - // information. - if (authClient.createScopedRequired && authClient.createScopedRequired()) { - // Scopes can be specified either as an array or as a single, - // space-delimited string. - authClient = authClient.createScoped([ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/compute', - 'https://www.googleapis.com/auth/compute.readonly', - ]); - authClient.projectId = projectId; - } - - return authClient; -} -// [END auth] - // [START list] /** * @param {Function} callback Callback function. */ async function getVmsExample() { - const authClient = await auth(); + const authClient = await google.auth.getClient({ + scopes: [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/compute', + 'https://www.googleapis.com/auth/compute.readonly', + ], + }); + const projectId = await google.auth.getProjectId(); // Retrieve the vms - const vms = await compute.instances.aggregatedList({ + const result = await compute.instances.aggregatedList({ auth: authClient, - project: authClient.projectId, + project: projectId, // In this example we only want one VM per page maxResults: 1, }); + const vms = result.data; console.log('VMs:', vms); return vms; }