Skip to content

Commit 48b4df1

Browse files
fix: improve the samples and tests (#236)
1 parent 07d6b98 commit 48b4df1

File tree

6 files changed

+79
-92
lines changed

6 files changed

+79
-92
lines changed

compute/package.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
"license": "Apache-2.0",
66
"author": "Google Inc.",
77
"repository": "googleapis/nodejs-compute",
8-
"files": [ "*.js" ],
8+
"files": [
9+
"*.js"
10+
],
911
"engines": {
1012
"node": ">=8"
1113
},
@@ -25,6 +27,8 @@
2527
},
2628
"devDependencies": {
2729
"@google-cloud/nodejs-repo-tools": "^3.0.0",
30+
"chai": "^4.2.0",
31+
"execa": "^1.0.0",
2832
"mocha": "^5.0.0",
2933
"proxyquire": "^2.0.1"
3034
}

compute/startup-script/index.js

Lines changed: 42 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,13 @@ const Compute = require('@google-cloud/compute');
1919
const fetch = require('node-fetch');
2020

2121
const compute = new Compute();
22-
2322
const zone = compute.zone('us-central1-a');
2423

25-
async function createVm(name) {
24+
/**
25+
* Create a new virtual machine with Ubuntu and Apache
26+
* @param {string} name Name of the virtual machine
27+
*/
28+
async function createVM(name) {
2629
// Create a new VM, using default ubuntu image. The startup script
2730
// installs apache and a custom homepage.
2831

@@ -34,7 +37,7 @@ async function createVm(name) {
3437
{
3538
key: 'startup-script',
3639
value: `#! /bin/bash
37-
40+
3841
# Installs apache and a custom homepage
3942
apt-get update
4043
apt-get install -y apache2
@@ -46,21 +49,35 @@ async function createVm(name) {
4649
],
4750
},
4851
};
49-
const vmObj = zone.vm(name);
50-
console.log('Creating VM ...');
51-
const [vm, operation] = await vmObj.create(config);
52+
53+
const vm = zone.vm(name);
54+
55+
console.log(`Creating VM ${name}...`);
56+
const [, operation] = await vm.create(config);
57+
58+
console.log(`Polling operation ${operation.id}...`);
5259
await operation.promise();
60+
61+
console.log('Acquiring VM metadata...');
5362
const [metadata] = await vm.getMetadata();
63+
console.log(metadata);
5464

5565
// External IP of the VM.
5666
const ip = metadata.networkInterfaces[0].accessConfigs[0].natIP;
5767
console.log(`Booting new VM with IP http://${ip}...`);
5868

5969
// Ping the VM to determine when the HTTP server is ready.
70+
console.log(`Operation complete. Waiting for IP ...`);
6071
await pingVM(ip);
72+
73+
console.log(`${name} created succesfully`);
6174
return ip;
6275
}
6376

77+
/**
78+
* Poll a given IP address until it returns a result.
79+
* @param {string} ip IP address to poll
80+
*/
6481
async function pingVM(ip) {
6582
let waiting = true;
6683
while (waiting) {
@@ -80,10 +97,12 @@ async function pingVM(ip) {
8097
}
8198
}
8299
}
83-
// List all VMs and their external IPs in a given zone.
84-
async function listVms() {
100+
/**
101+
* List all VMs and their external IPs in a given zone.
102+
*/
103+
async function listVMs() {
85104
const [vms] = await zone.getVMs();
86-
return await Promise.all(
105+
const results = await Promise.all(
87106
vms.map(async vm => {
88107
const [metadata] = await vm.getMetadata();
89108
return {
@@ -94,31 +113,26 @@ async function listVms() {
94113
};
95114
})
96115
);
116+
console.log(results);
117+
return results;
97118
}
98119

99-
async function deleteVm(name) {
120+
/**
121+
* Delete a VM with a given name.
122+
* @param {string} name
123+
*/
124+
async function deleteVM(name) {
100125
const vm = zone.vm(name);
101-
console.log('Deleting ...');
126+
console.log(`Deleting ${name} ...`);
102127
const [operation] = await vm.delete();
128+
console.log(`Polling operation ${operation.id} ...`);
103129
await operation.promise();
104-
// VM deleted
130+
console.log(`${name} deleted succesfully!`);
105131
return name;
106132
}
107133

108-
exports.create = async name => {
109-
const ip = await createVm(name);
110-
console.log(`${name} created succesfully`);
111-
return ip;
112-
};
113-
114-
exports.list = async () => {
115-
const vms = await listVms();
116-
console.log(vms);
117-
return vms;
118-
};
119-
120-
exports.delete = async name => {
121-
const result = await deleteVm(name);
122-
console.log(`${name} deleted succesfully`);
123-
return result;
134+
module.exports = {
135+
createVM,
136+
deleteVM,
137+
listVMs,
124138
};

compute/startup-script/system-test/index.test.js

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,36 +15,26 @@
1515

1616
'use strict';
1717

18-
const tools = require(`@google-cloud/nodejs-repo-tools`);
1918
const uuid = require('uuid');
2019
const assert = require('assert');
2120

22-
const example = require(`../index`);
21+
const example = require('../index');
22+
const name = `gcloud-apache-${uuid.v4().split('-')[0]}`;
2323

2424
describe('start-up script', async () => {
25-
before(tools.checkCredentials);
26-
beforeEach(tools.stubConsole);
27-
afterEach(tools.restoreConsole);
28-
29-
const TESTS_PREFIX = 'gcloud-tests-';
30-
const name = generateName('vm-with-apache');
31-
32-
function generateName(customPrefix) {
33-
return [TESTS_PREFIX, customPrefix + '-', uuid.v4().replace('-', '')]
34-
.join('')
35-
.substr(0, 61);
36-
}
3725
it('should create vm', async () => {
38-
const ip = await example.create(name);
26+
const ip = await example.createVM(name);
3927
assert.ok(ip);
4028
});
29+
4130
it('should list vms', async () => {
42-
const vms = await example.list();
31+
const vms = await example.listVMs();
4332
assert.ok(vms);
44-
assert.strictEqual(Array.isArray(vms), true);
33+
assert.ok(Array.isArray(vms));
4534
});
35+
4636
it('should delete vm', async () => {
47-
const result = await example.delete(name);
37+
const result = await example.deleteVM(name);
4838
assert.strictEqual(result, name);
4939
});
5040
});

compute/system-test/vms.test.js

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,16 @@
1515

1616
'use strict';
1717

18-
const tools = require(`@google-cloud/nodejs-repo-tools`);
18+
const execa = require('execa');
1919
const path = require(`path`);
20-
const assert = require('assert');
20+
const {assert} = require('chai');
2121

2222
const cmd = `node vms.js`;
2323
const cwd = path.join(__dirname, `..`);
2424

25-
describe('should retrieve list of vms', function() {
26-
it('vms_inspect_string', async function() {
27-
const output = await tools.runAsync(cmd, cwd);
28-
29-
assert.strictEqual(output.includes('VMs:'), true);
25+
describe('should retrieve list of vms', () => {
26+
it('vms_inspect_string', async () => {
27+
const {stdout} = await execa.shell(cmd, {cwd});
28+
assert.match(stdout, /^VMs:/);
3029
});
3130
});

compute/system-test/vms_api.test.js

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,16 @@
1515

1616
'use strict';
1717

18-
const tools = require(`@google-cloud/nodejs-repo-tools`);
18+
const execa = require(`execa`);
1919
const path = require(`path`);
20-
const assert = require('assert');
20+
const {assert} = require('chai');
2121

2222
const cmd = `node vms_api.js`;
2323
const cwd = path.join(__dirname, `..`);
2424

25-
describe('should retrieve list of vms via api', function() {
26-
it('vms_api_inspect_string', async function() {
27-
const output = await tools.runAsync(cmd, cwd);
28-
29-
assert.strictEqual(output.includes('VMs:'), true);
25+
describe('should retrieve list of vms via api', () => {
26+
it('vms_api_inspect_string', async () => {
27+
const {stdout} = await execa.shell(cmd, {cwd});
28+
assert.match(stdout, /^VMs:/);
3029
});
3130
});

compute/vms_api.js

Lines changed: 12 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -17,51 +17,32 @@
1717

1818
// [START complete]
1919
// [START initialize]
20-
const google = require('googleapis').google;
20+
const {google} = require('googleapis');
2121
const compute = google.compute('v1');
2222
// [END initialize]
2323

24-
// [START auth]
25-
async function auth() {
26-
const data = await google.auth.getApplicationDefault();
27-
let authClient = data.credential;
28-
const projectId = authClient.projectId;
29-
30-
// The createScopedRequired method returns true when running on GAE or a
31-
// local developer machine. In that case, the desired scopes must be passed
32-
// in manually. When the code is running in GCE or GAE Flexible, the scopes
33-
// are pulled from the GCE metadata server.
34-
// See https://cloud.google.com/compute/docs/authentication for more
35-
// information.
36-
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
37-
// Scopes can be specified either as an array or as a single,
38-
// space-delimited string.
39-
authClient = authClient.createScoped([
40-
'https://www.googleapis.com/auth/cloud-platform',
41-
'https://www.googleapis.com/auth/compute',
42-
'https://www.googleapis.com/auth/compute.readonly',
43-
]);
44-
authClient.projectId = projectId;
45-
}
46-
47-
return authClient;
48-
}
49-
// [END auth]
50-
5124
// [START list]
5225
/**
5326
* @param {Function} callback Callback function.
5427
*/
5528
async function getVmsExample() {
56-
const authClient = await auth();
29+
const authClient = await google.auth.getClient({
30+
scopes: [
31+
'https://www.googleapis.com/auth/cloud-platform',
32+
'https://www.googleapis.com/auth/compute',
33+
'https://www.googleapis.com/auth/compute.readonly',
34+
],
35+
});
36+
const projectId = await google.auth.getProjectId();
5737

5838
// Retrieve the vms
59-
const vms = await compute.instances.aggregatedList({
39+
const result = await compute.instances.aggregatedList({
6040
auth: authClient,
61-
project: authClient.projectId,
41+
project: projectId,
6242
// In this example we only want one VM per page
6343
maxResults: 1,
6444
});
45+
const vms = result.data;
6546
console.log('VMs:', vms);
6647
return vms;
6748
}

0 commit comments

Comments
 (0)