Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: improve samples and add tests #576

Merged
merged 4 commits into from
Jan 3, 2019
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
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
},
"main": "./build/src/index.js",
"types": "./build/src/index.d.ts",
"repository": "google/google-auth-library-nodejs.git",
"repository": "googleapis/google-auth-library-nodejs.git",
"keywords": [
"google",
"api",
Expand Down Expand Up @@ -77,8 +77,8 @@
"license-check": "jsgl --local .",
"docs": "compodoc src/ && touch docs/.nojekyll",
"publish-docs": "gh-pages -d docs --remote upstream && git push upstream gh-pages",
"samples-test": "mocha samples/system-test",
"system-test": "mocha build/system-test",
"samples-test": "cd samples/ && npm link ../ && npm test && cd ../",
"system-test": "mocha build/system-test --timeout 60000",
"presystem-test": "npm run compile"
},
"license": "Apache-2.0"
Expand Down
1 change: 1 addition & 0 deletions samples/.eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
rules:
no-console: off
node/no-missing-require: off
node/no-unpublished-require: off
5 changes: 4 additions & 1 deletion samples/adc.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@ const {auth} = require('google-auth-library');
* Acquire a client, and make a request to an API that's enabled by default.
*/
async function main() {
const client = await auth.getClient();
const client = await auth.getClient({
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
const projectId = await auth.getProjectId();
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({url});
console.log('DNS Info:');
console.log(res.data);
}

Expand Down
8 changes: 5 additions & 3 deletions samples/compute.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,20 @@

'use strict';

const {Compute} = require('google-auth-library');
const {auth, Compute} = require('google-auth-library');

/**
* Acquire a client, and make a request to an API that's enabled by default.
* This example directly instantiates a Compute client to acquire credentials.
* Generally, you wouldn't directly create this class, rather call the
* `auth.getClient()` method to automatically obtain credentials.
*/
async function main() {
const client = new Compute({
// Specifying the serviceAccountEmail is optional. It will use the default
// service account if one is not defined.
serviceAccountEmail: '[email protected]',
});
const projectId = 'el-gato';
const projectId = await auth.getProjectId();
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({url});
console.log(res.data);
Expand Down
19 changes: 17 additions & 2 deletions samples/creds.js → samples/credentials.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,31 @@
const {auth} = require('google-auth-library');

/**
* Acquire a client, and make a request to an API that's enabled by default.
* This sample demonstrates passing a `credentials` object directly into the
* `getClient` method. This is useful if you're storing the fields requiretd
* in environment variables. The original `client_email` and `private_key`
* values are obtained from a service account credential file.
*/
async function main() {
const clientEmail = process.env.CLIENT_EMAIL;
const privateKey = process.env.PRIVATE_KEY;
if (!clientEmail || !privateKey) {
throw new Error(`
The CLIENT_EMAIL and PRIVATE_KEY environment variables are required for
this sample.
`);
}
const client = await auth.getClient({
credentials: require('./jwt.keys.json'),
credentials: {
client_email: clientEmail,
private_key: privateKey,
},
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
const projectId = await auth.getProjectId();
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({url});
console.log('DNS Info:');
console.log(res.data);
}

Expand Down
57 changes: 0 additions & 57 deletions samples/fromJSON.js

This file was deleted.

25 changes: 20 additions & 5 deletions samples/authRequest.js → samples/headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,32 @@
* Import the GoogleAuth library, and create a new GoogleAuth client.
*/
const {auth} = require('google-auth-library');
const axios = require('axios');
const fetch = require('node-fetch');

/**
* Acquire a client, and make a request to an API that's enabled by default.
* This example shows obtaining authenticated HTTP request headers, and using
* those headers to construct your own authenticated request. This example uses
* node-fetch, but you could use any HTTP client you like.
*/
async function main() {
const projectId = await auth.getProjectId();
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const opts = await auth.authorizeRequest();
const res = await axios.get(url, opts);
console.log(res.data);

// obtain an authenticated client
const client = await auth.getClient({
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});

// Use the client to get authenticated request headers
const headers = await client.getRequestHeaders();
console.log('Headers:');
console.log(headers);

// Attach those headers to another request, and use it to call a Google API
const res = await fetch(url, {headers});
const data = await res.json();
console.log('DNS Info:');
console.log(data);
}

main().catch(console.error);
18 changes: 12 additions & 6 deletions samples/jwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,31 @@

'use strict';

const {JWT} = require('google-auth-library');

/**
* The JWT authorization is ideal for performing server-to-server
* communication without asking for user consent.
* communication without asking for user consent. Usually, you aren't
* going to directly instantiate a JWT instance. Typically, this is acquired
* by using the `auth.getClient()` method.
*
* Suggested reading for Admin SDK users using service accounts:
* https://developers.google.com/admin-sdk/directory/v1/guides/delegation
**/

const keys = require('./jwt.keys.json');
const {JWT} = require('google-auth-library');

async function main() {
async function main(
// Full path to the sevice account credential
keyFile = process.env.GOOGLE_APPLICATION_CREDENTIALS
) {
const keys = require(keyFile);
const client = new JWT({
email: keys.client_email,
key: keys.private_key,
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const url = `https://www.googleapis.com/dns/v1/projects/${keys.project_id}`;
const res = await client.request({url});
console.log('DNS Info:');
console.log(res.data);

// After acquiring an access_token, you may want to check on the audience, expiration,
Expand All @@ -41,4 +46,5 @@ async function main() {
console.log(tokenInfo);
}

main().catch(console.error);
const args = process.argv.slice(2);
main(...args).catch(console.error);
11 changes: 8 additions & 3 deletions samples/keyfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,20 @@ const {auth} = require('google-auth-library');
/**
* Acquire a client, and make a request to an API that's enabled by default.
*/
async function main() {
async function main(
// Full path to the sevice account credential
keyFile = process.env.GOOGLE_APPLICATION_CREDENTIALS
) {
const client = await auth.getClient({
keyFilename: 'jwt.keys.json',
keyFile: keyFile,
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
const projectId = await auth.getProjectId();
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({url});
console.log('DNS Info:');
console.log(res.data);
}

main().catch(console.error);
const args = process.argv.slice(2);
main(...args).catch(console.error);
11 changes: 8 additions & 3 deletions samples/package.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
{
"name": "google-auth-library-samples",
"description": "A set of samples for the google-auth-library npm module.",
"files": [
"*.js"
],
"scripts": {
"test": "mocha system-test"
"test": "mocha --timeout 60000"
},
"engines": {
"node": ">=8"
"node": ">=10"
},
"license": "Apache-2.0",
"dependencies": {
"axios": "^0.18.0",
"google-auth-library": "^2.0.2",
"node-fetch": "^2.3.0",
"opn": "^5.3.0",
"server-destroy": "^1.0.1"
},
"devDependencies": {
"chai": "^4.2.0",
"execa": "^1.0.0",
"mocha": "^5.2.0"
}
}
17 changes: 0 additions & 17 deletions samples/system-test/samples.js

This file was deleted.

3 changes: 3 additions & 0 deletions samples/test/.eslintrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---
env:
mocha: true
71 changes: 71 additions & 0 deletions samples/test/jwt.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* Copyright 2018 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

const execa = require('execa');
const {assert} = require('chai');
const fs = require('fs');
const {promisify} = require('util');

const readFile = promisify(fs.readFile);

const exec = async cmd => {
const res = await execa.shell(cmd);
assert.isEmpty(res.stderr);
return res.stdout;
};

const keyFile = process.env.GOOGLE_APPLICATION_CREDENTIALS;

describe('samples', () => {
it('should acquire application default credentials', async () => {
const output = await exec('node adc');
assert.match(output, /DNS Info:/);
});

it.skip('should acquire compute credentials', async () => {
// TODO: need to figure out deploying to GCF for this to work
const output = await exec('node compute');
assert.match(output, /DNS Info:/);
});

it('should create a JWT', async () => {
const output = await exec('node jwt');
assert.match(output, /DNS Info:/);
});

it('should read from a keyfile', async () => {
const output = await exec('node keyfile');
assert.match(output, /DNS Info:/);
});

it('should allow directly passing creds', async () => {
const keys = JSON.parse(await readFile(keyFile, 'utf8'));
const res = await execa('node', ['credentials'], {
env: {
CLIENT_EMAIL: keys.client_email,
PRIVATE_KEY: keys.private_key,
},
});
assert.isEmpty(res.stderr);
assert.match(res.stdout, /DNS Info:/);
});

it('should obtain headers for a request', async () => {
const output = await exec('node headers');
assert.match(output, /Headers:/);
assert.match(output, /DNS Info:/);
});
});
Loading