Skip to content

Commit

Permalink
fix: improve the samples and tests (#236)
Browse files Browse the repository at this point in the history
  • Loading branch information
JustinBeckwith authored and Ace Nassri committed Nov 21, 2022
1 parent 55a5655 commit b4cea9d
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 92 deletions.
6 changes: 5 additions & 1 deletion compute/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
"license": "Apache-2.0",
"author": "Google Inc.",
"repository": "googleapis/nodejs-compute",
"files": [ "*.js" ],
"files": [
"*.js"
],
"engines": {
"node": ">=8"
},
Expand All @@ -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"
}
Expand Down
70 changes: 42 additions & 28 deletions compute/startup-script/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
Expand All @@ -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) {
Expand All @@ -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 {
Expand All @@ -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,
};
26 changes: 8 additions & 18 deletions compute/startup-script/system-test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
13 changes: 6 additions & 7 deletions compute/system-test/vms.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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:/);
});
});
13 changes: 6 additions & 7 deletions compute/system-test/vms_api.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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:/);
});
});
43 changes: 12 additions & 31 deletions compute/vms_api.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down

0 comments on commit b4cea9d

Please sign in to comment.