diff --git a/translate/package.json b/translate/package.json index b7b1f938050..ef36037b91b 100644 --- a/translate/package.json +++ b/translate/package.json @@ -5,16 +5,12 @@ "license": "Apache Version 2.0", "author": "Google Inc.", "scripts": { - "test": "mocha -R spec --require intelli-espower-loader ../test/_setup.js test/*.test.js", - "system-test": "mocha -R spec --require intelli-espower-loader ../system-test/_setup.js system-test/*.test.js" + "test": "cd ..; npm run st -- translate/system-test/*.test.js" }, "dependencies": { - "@google-cloud/translate": "^0.4.0", + "@google-cloud/translate": "^0.5.0", "yargs": "^6.4.0" }, - "devDependencies": { - "mocha": "^3.1.2" - }, "engines": { "node": ">=4.3.2" } diff --git a/translate/quickstart.js b/translate/quickstart.js index 2ed38c9ba57..7bb0715b24b 100644 --- a/translate/quickstart.js +++ b/translate/quickstart.js @@ -19,12 +19,12 @@ // Imports the Google Cloud client library const Translate = require('@google-cloud/translate'); -// Your Translate API key -const apiKey = 'YOUR_API_KEY'; +// Your Google Cloud Platform project ID +const projectId = 'YOUR_PROJECT_ID'; // Instantiates a client const translateClient = Translate({ - key: apiKey + projectId: projectId }); // The text to translate @@ -33,13 +33,11 @@ const text = 'Hello, world!'; const target = 'ru'; // Translates some text into Russian -translateClient.translate(text, target, (err, translation) => { - if (err) { - console.error(err); - return; - } +translateClient.translate(text, target) + .then((results) => { + const translation = results[0]; - console.log(`Text: ${text}`); - console.log(`Translation: ${translation}`); -}); + console.log(`Text: ${text}`); + console.log(`Translation: ${translation}`); + }); // [END translate_quickstart] diff --git a/translate/system-test/quickstart.test.js b/translate/system-test/quickstart.test.js index 640b1afeb78..d41753da339 100644 --- a/translate/system-test/quickstart.test.js +++ b/translate/system-test/quickstart.test.js @@ -16,39 +16,37 @@ 'use strict'; const proxyquire = require(`proxyquire`).noPreserveCache(); -const translate = proxyquire(`@google-cloud/translate`, {})({ - key: process.env.TRANSLATE_API_KEY -}); -const string = `Hello, world!`; -const expectedTranslation = `Привет мир!`; -const targetLanguage = `ru`; +const translate = proxyquire(`@google-cloud/translate`, {})(); describe(`translate:quickstart`, () => { - let translateMock, TranslateMock; - it(`should translate a string`, (done) => { - translateMock = { - translate: (_string, _targetLanguage, _callback) => { + const string = `Hello, world!`; + const expectedTranslation = `Привет мир!`; + const targetLanguage = `ru`; + const translateMock = { + translate: (_string, _targetLanguage) => { assert.equal(_string, string); assert.equal(_targetLanguage, targetLanguage); - assert.equal(typeof _callback, 'function'); - translate.translate(_string, _targetLanguage, (err, translation, apiResponse) => { - _callback(err, translation, apiResponse); - assert.ifError(err); - assert.equal(translation, expectedTranslation); - assert.notEqual(apiResponse, undefined); - assert.equal(console.log.calledTwice, true); - assert.deepEqual(console.log.firstCall.args, [`Text: ${string}`]); - assert.deepEqual(console.log.secondCall.args, [`Translation: ${expectedTranslation}`]); - done(); - }); + return translate.translate(_string, _targetLanguage) + .then((results) => { + const translation = results[0]; + assert.equal(translation, expectedTranslation); + + setTimeout(() => { + assert.equal(console.log.callCount, 2); + assert.deepEqual(console.log.getCall(0).args, [`Text: ${string}`]); + assert.deepEqual(console.log.getCall(1).args, [`Translation: ${expectedTranslation}`]); + done(); + }, 200); + + return results; + }); } }; - TranslateMock = sinon.stub().returns(translateMock); proxyquire(`../quickstart`, { - '@google-cloud/translate': TranslateMock + '@google-cloud/translate': sinon.stub().returns(translateMock) }); }); }); diff --git a/translate/system-test/translate.test.js b/translate/system-test/translate.test.js index acfb60678d9..8d49dd92f38 100644 --- a/translate/system-test/translate.test.js +++ b/translate/system-test/translate.test.js @@ -22,45 +22,57 @@ const run = require(`../../utils`).run; const cwd = path.join(__dirname, `..`); const cmd = `node translate.js`; const text = `Hello world!`; +const text2 = `Goodbye!`; const toLang = `ru`; describe(`translate:translate`, () => { - const translate = Translate({ - key: process.env.TRANSLATE_API_KEY - }); - if (!process.env.TRANSLATE_API_KEY) { - process.stdout.write(`Skipping Translate API tests...\n`); - return; - } + const translate = Translate(); - it(`should detect language`, (done) => { + it(`should detect language of a single string`, () => { const output = run(`${cmd} detect "${text}"`, cwd); - translate.detect(text, (err, result) => { - assert.ifError(err); - assert.equal(output, `Detected: ${JSON.stringify(result)}`); - done(); - }); + return translate.detect(text) + .then((results) => { + const expected = `Detections:\n${text} => ${results[0].language}`; + assert.equal(output, expected); + }); + }); + + it(`should detect language of multiple strings`, () => { + const output = run(`${cmd} detect "${text}" "${text2}"`, cwd); + return translate.detect([text, text2]) + .then((results) => { + const expected = `Detections:\n${text} => ${results[0][0].language}\n${text2} => ${results[0][1].language}`; + assert.equal(output, expected); + }); }); it(`should list languages`, () => { const output = run(`${cmd} list`, cwd); - assert.notEqual(output.indexOf(`Languages:`), -1); - assert.notEqual(output.indexOf(`{ code: 'af', name: 'Afrikaans' }`), -1); + assert.equal(output.includes(`Languages:`), true); + assert.equal(output.includes(`{ code: 'af', name: 'Afrikaans' }`), true); }); it(`should list languages with a target`, () => { const output = run(`${cmd} list es`, cwd); - assert.notEqual(output.indexOf(`Languages:`), -1); - assert.notEqual(output.indexOf(`{ code: 'af', name: 'afrikáans' }`), -1); + assert.equal(output.includes(`Languages:`), true); + assert.equal(output.includes(`{ code: 'af', name: 'afrikáans' }`), true); }); - it(`should translate text`, (done) => { + it(`should translate a single string`, () => { const output = run(`${cmd} translate ${toLang} "${text}"`, cwd); - translate.translate(text, toLang, (err, translation) => { - assert.ifError(err); - assert.notEqual(output.indexOf(`Text: ["${text}"]`), -1); - assert.notEqual(output.indexOf(`Translation: "${translation}"`), -1); - done(); - }); + return translate.translate(text, toLang) + .then((results) => { + const expected = `Translations:\n${text} => (${toLang}) ${results[0]}`; + assert.equal(output, expected); + }); + }); + + it(`should translate multiple strings`, () => { + const output = run(`${cmd} translate ${toLang} "${text}" "${text2}"`, cwd); + return translate.translate([text, text2], toLang) + .then((results) => { + const expected = `Translations:\n${text} => (${toLang}) ${results[0][0]}\n${text2} => (${toLang}) ${results[0][1]}`; + assert.equal(output, expected); + }); }); }); diff --git a/translate/test/quickstart.test.js b/translate/test/quickstart.test.js deleted file mode 100644 index e9c3dd683d2..00000000000 --- a/translate/test/quickstart.test.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright 2016, Google, Inc. - * 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. - */ - -'use strict'; - -const proxyquire = require(`proxyquire`).noCallThru(); - -describe(`translate:quickstart`, () => { - let translateMock, TranslateMock; - const error = new Error(`error`); - - before(() => { - translateMock = { - translate: sinon.stub().yields(error) - }; - TranslateMock = sinon.stub().returns(translateMock); - }); - - it(`should handle error`, () => { - proxyquire(`../quickstart`, { - '@google-cloud/translate': TranslateMock - }); - - assert.equal(TranslateMock.calledOnce, true); - assert.deepEqual(TranslateMock.firstCall.args, [{ key: 'YOUR_API_KEY' }]); - assert.equal(translateMock.translate.calledOnce, true); - assert.deepEqual(translateMock.translate.firstCall.args.slice(0, -1), ['Hello, world!', 'ru']); - assert.equal(console.error.calledOnce, true); - assert.deepEqual(console.error.firstCall.args, [error]); - }); -}); diff --git a/translate/test/translate.test.js b/translate/test/translate.test.js deleted file mode 100644 index 91b296c3c05..00000000000 --- a/translate/test/translate.test.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright 2016, Google, Inc. - * 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. - */ - -'use strict'; - -const proxyquire = require(`proxyquire`).noCallThru(); - -describe(`translate:translate`, () => { - it(`should handle errors`, () => { - const error = new Error(`error`); - const text = `Hello world!`; - const toLang = `ru`; - const callback = sinon.spy(); - const translateMock = { - getLanguages: sinon.stub().yields(error), - detect: sinon.stub().yields(error), - translate: sinon.stub().yields(error) - }; - const TranslateMock = sinon.stub().returns(translateMock); - const program = proxyquire(`../translate`, { - '@google-cloud/translate': TranslateMock - }); - - program.detectLanguage(text, callback); - program.listLanguages(callback); - program.listLanguagesWithTarget(toLang, callback); - program.translateText(text, toLang, callback); - - assert.equal(callback.callCount, 4); - assert.equal(callback.alwaysCalledWithExactly(error), true); - }); -}); diff --git a/translate/translate.js b/translate/translate.js index bc3e1087024..1f7b3166544 100644 --- a/translate/translate.js +++ b/translate/translate.js @@ -18,156 +18,130 @@ const Translate = require('@google-cloud/translate'); // [START translate_detect_language] -function detectLanguage (input, callback) { +function detectLanguage (input) { // Instantiates a client - const translate = Translate({ - // The Translate API uses an API key for authentication. This sample looks - // for the key in an environment variable. - key: process.env.TRANSLATE_API_KEY - }); + const translate = Translate(); // Detects the language. "input" can be a string for detecting the language of // a single piece of text, or an array of strings for detecting the languages // of multiple texts. - translate.detect(input, (err, result) => { - if (err) { - callback(err); - return; - } + return translate.detect(input) + .then((results) => { + let detections = results[0]; + + if (!Array.isArray(detections)) { + detections = [detections]; + } + + console.log('Detections:'); + detections.forEach((detection) => { + console.log(`${detection.input} => ${detection.language}`); + }); - console.log('Detected: %j', result); - callback(); - }); + return detections; + }); } // [END translate_detect_language] // [START translate_list_codes] -function listLanguages (callback) { +function listLanguages () { // Instantiates a client - const translate = Translate({ - // The Translate API uses an API key for authentication. This sample looks - // for the key in an environment variable. - key: process.env.TRANSLATE_API_KEY - }); + const translate = Translate(); // Lists available translation language with their names in English (the default). - translate.getLanguages((err, languages) => { - if (err) { - callback(err); - return; - } + return translate.getLanguages() + .then((results) => { + const languages = results[0]; + + console.log('Languages:'); + languages.forEach((language) => console.log(language)); - console.log('Languages:'); - languages.forEach((language) => console.log(language)); - callback(); - }); + return languages; + }); } // [END translate_list_codes] // [START translate_list_language_names] -function listLanguagesWithTarget (target, callback) { +function listLanguagesWithTarget (target) { // Instantiates a client - const translate = Translate({ - // The Translate API uses an API key for authentication. This sample looks - // for the key in an environment variable. - key: process.env.TRANSLATE_API_KEY - }); - - // Lists available translation language with their names in a target language - translate.getLanguages(target, (err, languages) => { - if (err) { - callback(err); - return; - } + const translate = Translate(); + + // Lists available translation language with their names in a target language, + // e.g. "ru" + return translate.getLanguages(target) + .then((results) => { + const languages = results[0]; + + console.log('Languages:'); + languages.forEach((language) => console.log(language)); - console.log('Languages:'); - languages.forEach((language) => console.log(language)); - callback(); - }); + return languages; + }); } // [END translate_list_language_names] // [START translate_translate_text] -function translateText (input, target, callback) { +function translateText (input, target) { + if (!Array.isArray(input)) { + input = [input]; + } + // Instantiates a client - const translate = Translate({ - // The Translate API uses an API key for authentication. This sample looks - // for the key in an environment variable. - key: process.env.TRANSLATE_API_KEY - }); + const translate = Translate(); // Translates the text into the target language. "input" can be a string for // translating a single piece of text, or an array of strings for translating // multiple texts. - translate.translate(input, target, (err, translation) => { - if (err) { - callback(err); - return; - } - - console.log('Text: %j', input); - console.log('Translation: %j', translation); - callback(); - }); + return translate.translate(input, target) + .then((results) => { + let translations = results[0]; + translations = Array.isArray(translations) ? translations : [translations]; + + console.log('Translations:'); + translations.forEach((translation, i) => { + console.log(`${input[i]} => (${target}) ${translation}`); + }); + + return translations; + }); } // [END translate_translate_text] -// The command-line program -const cli = require(`yargs`); -const noop = require(`../utils`).noop; - -const program = module.exports = { - detectLanguage: detectLanguage, - listLanguages: listLanguages, - listLanguagesWithTarget: listLanguagesWithTarget, - translateText: translateText, - main: (args) => { - // Run the command-line program - cli.help().strict().parse(args).argv; - } -}; - -cli +require(`yargs`) .demand(1) - .command(`detect `, `Detects the language of the provided text or texts`, {}, (opts) => { - if (!process.env.TRANSLATE_API_KEY) { - process.env.TRANSLATE_API_KEY = opts.apiKey; - } - program.detectLanguage(opts.input, noop); - }) - .command(`list [target]`, `Lists available translation languages. To return language names in a language other than English, specify a target language.`, {}, (opts) => { - if (!process.env.TRANSLATE_API_KEY) { - process.env.TRANSLATE_API_KEY = opts.apiKey; + .command( + `detect `, + `Detects the language of one or more strings.`, + {}, + (opts) => detectLanguage(opts.input) + ) + .command( + `list [target]`, + `Lists available translation languages. To return language names in a language other than English, specify a target language.`, + {}, + (opts) => { + if (opts.target) { + listLanguagesWithTarget(opts.target); + } else { + listLanguages(); + } } - if (opts.target) { - program.listLanguagesWithTarget(opts.target, noop); - } else { - program.listLanguages(noop); - } - }) - .command(`translate `, `Translates the provided text or texts to the target language.`, {}, (opts) => { - if (!process.env.TRANSLATE_API_KEY) { - process.env.TRANSLATE_API_KEY = opts.apiKey; - } - program.translateText(opts.input, opts.toLang, noop); - }) - .option(`apiKey`, { - alias: `k`, - global: true, - requiresArg: true, - default: process.env.TRANSLATE_API_KEY, - type: `string`, - description: `Your Translate API key. Defaults to the value of the TRANSLATE_API_KEY environment variable.` - }) - .example(`node $0 detect "Hello world!"`, `Detects the language of "Hello world!".`) - .example(`node $0 detect -k YOUR_API_KEY "Hello world!" "Goodbye"`, `Detects the language of "Hello world!" and "Goodbye", supplying the API key inline.`) - .example(`node $0 list -k YOUR_API_KEY`, `Lists available translation languages with names in English, supplying the API key inline.`) + ) + .command( + `translate `, + `Translates one or more strings into the target language.`, + {}, + (opts) => translateText(opts.input, opts.toLang) + ) + .example(`node $0 detect "Hello world!"`, `Detects the language of a string.`) + .example(`node $0 detect "Hello world!" "Goodbye"`, `Detects the languages of multiple strings.`) + .example(`node $0 list`, `Lists available translation languages with names in English.`) .example(`node $0 list es`, `Lists available translation languages with names in Spanish.`) - .example(`node $0 translate ru "Good morning!"`, `Translates "Good morning!" to Russian, auto-detecting the source language.`) + .example(`node $0 translate ru "Good morning!"`, `Translates a string into Russian.`) + .example(`node $0 translate ru "Good morning!" "Good night!"`, `Translates multiple strings into Russian.`) .wrap(120) .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/translate/docs`); - -if (module === require.main) { - program.main(process.argv.slice(2)); -} + .epilogue(`For more information, see https://cloud.google.com/translate/docs`) + .help() + .strict() + .argv;