use eslint autofix to start fixing violations
This commit is contained in:
@ -14,3 +14,4 @@ rules:
|
|||||||
no-empty: warn
|
no-empty: warn
|
||||||
space-before-function-paren: warn
|
space-before-function-paren: warn
|
||||||
no-restricted-globals: warn
|
no-restricted-globals: warn
|
||||||
|
prefer-const: warn
|
||||||
@ -1,14 +1,14 @@
|
|||||||
var get = require('lodash.get');
|
const get = require('lodash.get');
|
||||||
var utils = require('../utils');
|
const utils = require('../utils');
|
||||||
var fromRoot = require('path').join.bind(null, __dirname, '..', '..');
|
const fromRoot = require('path').join.bind(null, __dirname, '..', '..');
|
||||||
|
|
||||||
var release = process.env.ES_RELEASE;
|
const release = process.env.ES_RELEASE;
|
||||||
var ref = process.env.ES_REF;
|
const ref = process.env.ES_REF;
|
||||||
var port = parseFloat(get(process.env, 'ES_PORT', 9400));
|
const port = parseFloat(get(process.env, 'ES_PORT', 9400));
|
||||||
var host = get(process.env, 'ES_HOST', 'localhost');
|
const host = get(process.env, 'ES_HOST', 'localhost');
|
||||||
|
|
||||||
var Version = require('../../scripts/Version');
|
const Version = require('../../scripts/Version');
|
||||||
var versionedOpts = [
|
const versionedOpts = [
|
||||||
{
|
{
|
||||||
version: '*',
|
version: '*',
|
||||||
directory: fromRoot('esvm'),
|
directory: fromRoot('esvm'),
|
||||||
@ -90,8 +90,8 @@ utils.branches.forEach(function (branch) {
|
|||||||
|
|
||||||
// ci target, based on env variables
|
// ci target, based on env variables
|
||||||
(function () {
|
(function () {
|
||||||
var v;
|
let v;
|
||||||
var opts = {
|
const opts = {
|
||||||
config: {
|
config: {
|
||||||
'http.port': port
|
'http.port': port
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
var root = require('find-root')(__dirname);
|
const root = require('find-root')(__dirname);
|
||||||
var rel = require('path').resolve.bind(null, root);
|
const rel = require('path').resolve.bind(null, root);
|
||||||
var rootReq = function (p) { return require(rel(p)); };
|
const rootReq = function (p) { return require(rel(p)); };
|
||||||
var _ = rootReq('src/lib/utils');
|
const _ = rootReq('src/lib/utils');
|
||||||
var grunt = require('grunt');
|
const grunt = require('grunt');
|
||||||
|
|
||||||
var JENKINS_REPORTER = rel('test/utils/jenkins-reporter.js');
|
const JENKINS_REPORTER = rel('test/utils/jenkins-reporter.js');
|
||||||
|
|
||||||
var config = {
|
const config = {
|
||||||
unit: {
|
unit: {
|
||||||
src: 'test/unit/index.js',
|
src: 'test/unit/index.js',
|
||||||
options: {
|
options: {
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
var utils = require('../utils');
|
const utils = require('../utils');
|
||||||
|
|
||||||
var config = {
|
const config = {
|
||||||
generate: {
|
generate: {
|
||||||
exec: 'node ./scripts/generate/index.js',
|
exec: 'node ./scripts/generate/index.js',
|
||||||
options: {
|
options: {
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
var config = {};
|
let config = {};
|
||||||
try {
|
try {
|
||||||
config = require('../../.aws-config.json');
|
config = require('../../.aws-config.json');
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
var slk = require('../../test/utils/slk');
|
const slk = require('../../test/utils/slk');
|
||||||
module.exports = {
|
module.exports = {
|
||||||
all: {
|
all: {
|
||||||
options: {
|
options: {
|
||||||
|
|||||||
@ -4,4 +4,4 @@ module.exports = {
|
|||||||
require('../../webpack_config/angular'),
|
require('../../webpack_config/angular'),
|
||||||
require('../../webpack_config/jquery'),
|
require('../../webpack_config/jquery'),
|
||||||
]
|
]
|
||||||
}
|
};
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
module.exports = function (grunt) {
|
module.exports = function (grunt) {
|
||||||
var Promise = require('bluebird');
|
const Promise = require('bluebird');
|
||||||
var utils = require('./utils');
|
const utils = require('./utils');
|
||||||
var readFile = Promise.promisify(require('fs').readFile);
|
const readFile = Promise.promisify(require('fs').readFile);
|
||||||
var writeFile = Promise.promisify(require('fs').writeFile);
|
const writeFile = Promise.promisify(require('fs').writeFile);
|
||||||
|
|
||||||
|
|
||||||
// Default task runs the build process.
|
// Default task runs the build process.
|
||||||
@ -11,12 +11,12 @@ module.exports = function (grunt) {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
grunt.registerTask('test', function (branch) {
|
grunt.registerTask('test', function (branch) {
|
||||||
var tasks = [
|
const tasks = [
|
||||||
branch ? 'run:generate_' + branch : 'run:generate',
|
branch ? 'run:generate_' + branch : 'run:generate',
|
||||||
'mochacov:unit'
|
'mochacov:unit'
|
||||||
];
|
];
|
||||||
|
|
||||||
var branches = branch ? [branch] : utils.branches;
|
const branches = branch ? [branch] : utils.branches;
|
||||||
|
|
||||||
process.env.ES_PORT = process.env.ES_PORT || 9400;
|
process.env.ES_PORT = process.env.ES_PORT || 9400;
|
||||||
process.env.ES_HOST = process.env.ES_HOST || 'localhost';
|
process.env.ES_HOST = process.env.ES_HOST || 'localhost';
|
||||||
@ -38,10 +38,10 @@ module.exports = function (grunt) {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
grunt.registerTask('version', function (nextVersion) {
|
grunt.registerTask('version', function (nextVersion) {
|
||||||
var root = require('path').join.bind(null, __dirname, '..');
|
const root = require('path').join.bind(null, __dirname, '..');
|
||||||
var readmePath = root('README.md');
|
const readmePath = root('README.md');
|
||||||
var packagePath = root('package.json');
|
const packagePath = root('package.json');
|
||||||
var browserBuildsPath = root('docs/browser_builds.asciidoc');
|
const browserBuildsPath = root('docs/browser_builds.asciidoc');
|
||||||
|
|
||||||
Promise.all([
|
Promise.all([
|
||||||
require(packagePath),
|
require(packagePath),
|
||||||
@ -49,7 +49,7 @@ module.exports = function (grunt) {
|
|||||||
readFile(browserBuildsPath, 'utf8')
|
readFile(browserBuildsPath, 'utf8')
|
||||||
])
|
])
|
||||||
.spread(function (pkg, readme, browserBuilds) {
|
.spread(function (pkg, readme, browserBuilds) {
|
||||||
var current = pkg.version;
|
const current = pkg.version;
|
||||||
|
|
||||||
pkg.version = nextVersion;
|
pkg.version = nextVersion;
|
||||||
browserBuilds = utils.replaceAll(browserBuilds, current, nextVersion);
|
browserBuilds = utils.replaceAll(browserBuilds, current, nextVersion);
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
var _ = require('../src/lib/utils');
|
const _ = require('../src/lib/utils');
|
||||||
|
|
||||||
var root = require('find-root')(__dirname);
|
const root = require('find-root')(__dirname);
|
||||||
var pkg = require(root + '/package.json');
|
const pkg = require(root + '/package.json');
|
||||||
var stable = pkg.config.supported_es_branches;
|
const stable = pkg.config.supported_es_branches;
|
||||||
var unstable = pkg.config.unstable_es_branches;
|
const unstable = pkg.config.unstable_es_branches;
|
||||||
var branches = [].concat(stable, unstable);
|
const branches = [].concat(stable, unstable);
|
||||||
|
|
||||||
var utils = {
|
var utils = {
|
||||||
branchSuffix: function (branch) {
|
branchSuffix: function (branch) {
|
||||||
@ -29,7 +29,7 @@ utils.minorVersion = function (version) {
|
|||||||
* increment the version based on the release "type"
|
* increment the version based on the release "type"
|
||||||
*/
|
*/
|
||||||
utils.increaseVersion = function (version, type) {
|
utils.increaseVersion = function (version, type) {
|
||||||
var i;
|
let i;
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case 'major':
|
case 'major':
|
||||||
i = 0;
|
i = 0;
|
||||||
@ -47,7 +47,7 @@ utils.increaseVersion = function (version, type) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// breakout the current version
|
// breakout the current version
|
||||||
var next = version.split('.').map(function (n) {
|
const next = version.split('.').map(function (n) {
|
||||||
return parseInt(n, 10);
|
return parseInt(n, 10);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -63,9 +63,9 @@ utils.increaseVersion = function (version, type) {
|
|||||||
* replace all instances of `replace` with `replacement` without creating a regexp object
|
* replace all instances of `replace` with `replacement` without creating a regexp object
|
||||||
*/
|
*/
|
||||||
utils.replaceAll = function (str, replace, replacement) {
|
utils.replaceAll = function (str, replace, replacement) {
|
||||||
var out = '';
|
let out = '';
|
||||||
var remaining = str;
|
let remaining = str;
|
||||||
var i = 0;
|
let i = 0;
|
||||||
|
|
||||||
while (~(i = remaining.indexOf(replace))) {
|
while (~(i = remaining.indexOf(replace))) {
|
||||||
out += remaining.substring(0, i) + replacement;
|
out += remaining.substring(0, i) + replacement;
|
||||||
|
|||||||
@ -1,16 +1,16 @@
|
|||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var pkg = require('../package.json');
|
const pkg = require('../package.json');
|
||||||
var branches = [...pkg.config.supported_es_branches, ...pkg.config.unstable_es_branches];
|
const branches = [...pkg.config.supported_es_branches, ...pkg.config.unstable_es_branches];
|
||||||
var semver = require('semver');
|
const semver = require('semver');
|
||||||
|
|
||||||
function nextMajorVersion() {
|
function nextMajorVersion() {
|
||||||
const largestMajor = branches
|
const largestMajor = branches
|
||||||
.map(v => parseFloat(v.split('.')[0]))
|
.map(v => parseFloat(v.split('.')[0]))
|
||||||
.filter(n => !isNaN(n))
|
.filter(n => !isNaN(n))
|
||||||
.sort((a, b) => b - a)
|
.sort((a, b) => b - a)
|
||||||
.shift()
|
.shift();
|
||||||
|
|
||||||
return new Version(`${largestMajor + 1}.0.0`)
|
return new Version(`${largestMajor + 1}.0.0`);
|
||||||
}
|
}
|
||||||
|
|
||||||
function nextMinorVersion(major) {
|
function nextMinorVersion(major) {
|
||||||
@ -42,11 +42,11 @@ Version.fromBranch = function (branch) {
|
|||||||
if (/^\d+\.\d+$/.test(branch)) return new Version(branch + '.0');
|
if (/^\d+\.\d+$/.test(branch)) return new Version(branch + '.0');
|
||||||
|
|
||||||
// n.x -> n.(maxVersion + 1).0
|
// n.x -> n.(maxVersion + 1).0
|
||||||
const match = branch.match(/^(\d+)\.x$/i)
|
const match = branch.match(/^(\d+)\.x$/i);
|
||||||
if (match) return nextMinorVersion(match[1]);
|
if (match) return nextMinorVersion(match[1]);
|
||||||
|
|
||||||
// master => (maxMajorVersion + 1).0.0
|
// master => (maxMajorVersion + 1).0.0
|
||||||
if (branch === 'master') return nextMajorVersion()
|
if (branch === 'master') return nextMajorVersion();
|
||||||
|
|
||||||
throw new Error('unable to convert branch "' + branch + '" to semver');
|
throw new Error('unable to convert branch "' + branch + '" to semver');
|
||||||
};
|
};
|
||||||
@ -66,9 +66,9 @@ Version.prototype.mergeOpts = function (versioned, overrides) {
|
|||||||
|
|
||||||
const candidates = versioned
|
const candidates = versioned
|
||||||
.filter(o => this.satisfies(o.version))
|
.filter(o => this.satisfies(o.version))
|
||||||
.map(o => _.omit(o, 'version'))
|
.map(o => _.omit(o, 'version'));
|
||||||
|
|
||||||
return _.merge({}, overrides || {}, ...candidates)
|
return _.merge({}, overrides || {}, ...candidates);
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = Version;
|
module.exports = Version;
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
module.exports = _spawn;
|
module.exports = _spawn;
|
||||||
|
|
||||||
var map = require('through2-map');
|
const map = require('through2-map');
|
||||||
var split = require('split');
|
const split = require('split');
|
||||||
var chalk = require('chalk');
|
const chalk = require('chalk');
|
||||||
var spawn = require('child_process').spawn;
|
const spawn = require('child_process').spawn;
|
||||||
var path = require('path');
|
const path = require('path');
|
||||||
var root = path.resolve(__dirname, '../');
|
const root = path.resolve(__dirname, '../');
|
||||||
|
|
||||||
function indent(line) {
|
function indent(line) {
|
||||||
line = String(line).trim();
|
line = String(line).trim();
|
||||||
@ -26,7 +26,7 @@ function _spawn(cmd, args, opts, cb) {
|
|||||||
opts.verbose = false;
|
opts.verbose = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
var conf = {
|
const conf = {
|
||||||
stdio: [
|
stdio: [
|
||||||
'ignore',
|
'ignore',
|
||||||
opts.verbose ? 'pipe' : 'ignore',
|
opts.verbose ? 'pipe' : 'ignore',
|
||||||
@ -34,7 +34,7 @@ function _spawn(cmd, args, opts, cb) {
|
|||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
var subdir;
|
let subdir;
|
||||||
|
|
||||||
if (opts.cwd) {
|
if (opts.cwd) {
|
||||||
conf.cwd = opts.cwd;
|
conf.cwd = opts.cwd;
|
||||||
@ -43,7 +43,7 @@ function _spawn(cmd, args, opts, cb) {
|
|||||||
|
|
||||||
console.log(chalk.white.bold((subdir ? subdir + ' ' : '') + '$ ') + cmd + ' ' + args.join(' '));
|
console.log(chalk.white.bold((subdir ? subdir + ' ' : '') + '$ ') + cmd + ' ' + args.join(' '));
|
||||||
|
|
||||||
var cp = spawn(cmd, args, conf);
|
const cp = spawn(cmd, args, conf);
|
||||||
|
|
||||||
if (opts.verbose) {
|
if (opts.verbose) {
|
||||||
consume(cp.stdout);
|
consume(cp.stdout);
|
||||||
|
|||||||
@ -17,25 +17,25 @@
|
|||||||
*
|
*
|
||||||
*******/
|
*******/
|
||||||
|
|
||||||
var Promise = require('bluebird');
|
const Promise = require('bluebird');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var through2 = require('through2');
|
const through2 = require('through2');
|
||||||
var map = require('through2-map');
|
const map = require('through2-map');
|
||||||
var split = require('split');
|
const split = require('split');
|
||||||
var join = require('path').join;
|
const join = require('path').join;
|
||||||
var cp = require('child_process');
|
const cp = require('child_process');
|
||||||
var chalk = require('chalk');
|
const chalk = require('chalk');
|
||||||
var format = require('util').format;
|
const format = require('util').format;
|
||||||
|
|
||||||
var NL_RE = /(\r?\n)/g;
|
const NL_RE = /(\r?\n)/g;
|
||||||
var ROOT = join(__dirname, '..');
|
const ROOT = join(__dirname, '..');
|
||||||
var GRUNT = join(ROOT, 'node_modules', '.bin', 'grunt');
|
const GRUNT = join(ROOT, 'node_modules', '.bin', 'grunt');
|
||||||
var ENV = _.clone(process.env);
|
const ENV = _.clone(process.env);
|
||||||
var JENKINS = !!ENV.JENKINS_HOME;
|
const JENKINS = !!ENV.JENKINS_HOME;
|
||||||
var TASKS = [];
|
const TASKS = [];
|
||||||
|
|
||||||
var output; // main output stream
|
let output; // main output stream
|
||||||
var taskOut; // task output stream
|
let taskOut; // task output stream
|
||||||
|
|
||||||
task('NODE_UNIT', true, function () {
|
task('NODE_UNIT', true, function () {
|
||||||
if (!JENKINS) {
|
if (!JENKINS) {
|
||||||
@ -46,11 +46,11 @@ task('NODE_UNIT', true, function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
task('NODE_INTEGRATION', true, function () {
|
task('NODE_INTEGRATION', true, function () {
|
||||||
var branch = ENV.ES_REF;
|
const branch = ENV.ES_REF;
|
||||||
|
|
||||||
return node('scripts/generate', '--no-api', '--branch', branch)
|
return node('scripts/generate', '--no-api', '--branch', branch)
|
||||||
.then(function () {
|
.then(function () {
|
||||||
var target = (JENKINS ? 'jenkins_' : '') + 'integration:' + branch;
|
const target = (JENKINS ? 'jenkins_' : '') + 'integration:' + branch;
|
||||||
return grunt('esvm:ci_env', 'mocha_' + target, 'esvm_shutdown:ci_env');
|
return grunt('esvm:ci_env', 'mocha_' + target, 'esvm_shutdown:ci_env');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -58,9 +58,9 @@ task('NODE_INTEGRATION', true, function () {
|
|||||||
task('SAUCE_LABS', false, function () {
|
task('SAUCE_LABS', false, function () {
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
// build the clients and start the server, once the server is ready call trySaucelabs()
|
// build the clients and start the server, once the server is ready call trySaucelabs()
|
||||||
var serverTasks = ['browser_clients:build', 'run:browser_test_server:keepalive'];
|
const serverTasks = ['browser_clients:build', 'run:browser_test_server:keepalive'];
|
||||||
spawn(GRUNT, serverTasks, function (proc) {
|
spawn(GRUNT, serverTasks, function (proc) {
|
||||||
var toLines = split();
|
const toLines = split();
|
||||||
|
|
||||||
proc.stdout
|
proc.stdout
|
||||||
.pipe(toLines)
|
.pipe(toLines)
|
||||||
@ -83,14 +83,14 @@ task('SAUCE_LABS', false, function () {
|
|||||||
.catch(_.noop);
|
.catch(_.noop);
|
||||||
|
|
||||||
// attempt to run tests on saucelabs and retry if it fails
|
// attempt to run tests on saucelabs and retry if it fails
|
||||||
var saucelabsAttempts = 0;
|
let saucelabsAttempts = 0;
|
||||||
function trySaucelabs() {
|
function trySaucelabs() {
|
||||||
saucelabsAttempts++;
|
saucelabsAttempts++;
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
log(chalk.green('saucelabs attempt #', saucelabsAttempts));
|
log(chalk.green('saucelabs attempt #', saucelabsAttempts));
|
||||||
spawn(GRUNT, ['saucelabs-mocha'], function (cp) {
|
spawn(GRUNT, ['saucelabs-mocha'], function (cp) {
|
||||||
|
|
||||||
var failedTests = 0;
|
let failedTests = 0;
|
||||||
cp.stdout
|
cp.stdout
|
||||||
.pipe(split())
|
.pipe(split())
|
||||||
.pipe(map(function (line) {
|
.pipe(map(function (line) {
|
||||||
@ -141,7 +141,7 @@ execTask('SETUP', function () {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var match;
|
let match;
|
||||||
if (match = ENV.ES_V.match(/^(.*)_nightly$/)) {
|
if (match = ENV.ES_V.match(/^(.*)_nightly$/)) {
|
||||||
return [match[1], null];
|
return [match[1], null];
|
||||||
}
|
}
|
||||||
@ -206,7 +206,7 @@ execTask('SETUP', function () {
|
|||||||
* utils
|
* utils
|
||||||
******/
|
******/
|
||||||
function log() {
|
function log() {
|
||||||
var chunk = format.apply(null, arguments);
|
const chunk = format.apply(null, arguments);
|
||||||
(taskOut || output || process.stdout).write(chunk + '\n');
|
(taskOut || output || process.stdout).write(chunk + '\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -218,15 +218,15 @@ function logImportant(text) {
|
|||||||
|
|
||||||
function push(m) {
|
function push(m) {
|
||||||
return function () {
|
return function () {
|
||||||
var args = _.toArray(arguments);
|
const args = _.toArray(arguments);
|
||||||
var cb = args.pop();
|
const cb = args.pop();
|
||||||
this.push(m.apply(this, args));
|
this.push(m.apply(this, args));
|
||||||
cb();
|
cb();
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function indent() {
|
function indent() {
|
||||||
var str = through2(
|
const str = through2(
|
||||||
push(function (chunk) { return String(chunk).replace(NL_RE, '$1 '); }),
|
push(function (chunk) { return String(chunk).replace(NL_RE, '$1 '); }),
|
||||||
push(function () { return '\n'; })
|
push(function () { return '\n'; })
|
||||||
);
|
);
|
||||||
@ -281,7 +281,7 @@ function execTask(name, task) {
|
|||||||
|
|
||||||
function spawn(file, args, block) {
|
function spawn(file, args, block) {
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
var proc = cp.spawn(file, args, {
|
const proc = cp.spawn(file, args, {
|
||||||
cwd: ROOT,
|
cwd: ROOT,
|
||||||
env: ENV,
|
env: ENV,
|
||||||
stdio: [0, 'pipe', 'pipe']
|
stdio: [0, 'pipe', 'pipe']
|
||||||
@ -290,7 +290,7 @@ function spawn(file, args, block) {
|
|||||||
proc.stdout.pipe(taskOut, { end: false });
|
proc.stdout.pipe(taskOut, { end: false });
|
||||||
proc.stderr.pipe(taskOut, { end: false });
|
proc.stderr.pipe(taskOut, { end: false });
|
||||||
|
|
||||||
var stdout = '';
|
let stdout = '';
|
||||||
proc.stdout
|
proc.stdout
|
||||||
.pipe(through2(function (chunk, enc, cb) {
|
.pipe(through2(function (chunk, enc, cb) {
|
||||||
stdout += chunk;
|
stdout += chunk;
|
||||||
|
|||||||
@ -1,13 +1,13 @@
|
|||||||
module.exports = function (done) {
|
module.exports = function (done) {
|
||||||
var _ = require('../../src/lib/utils');
|
const _ = require('../../src/lib/utils');
|
||||||
var utils = require('../../grunt/utils');
|
const utils = require('../../grunt/utils');
|
||||||
|
|
||||||
var chalk = require('chalk');
|
const chalk = require('chalk');
|
||||||
var fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
|
const fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
|
||||||
var write = require('fs').writeFileSync;
|
const write = require('fs').writeFileSync;
|
||||||
|
|
||||||
var nodeApiIndex = fromRoot('src/lib/apis/index.js');
|
const nodeApiIndex = fromRoot('src/lib/apis/index.js');
|
||||||
var browserApiIndex = fromRoot('src/lib/apis/browser_index.js');
|
const browserApiIndex = fromRoot('src/lib/apis/browser_index.js');
|
||||||
|
|
||||||
write(nodeApiIndex, require('./templates').apiIndex({
|
write(nodeApiIndex, require('./templates').apiIndex({
|
||||||
branches: utils.branches
|
branches: utils.branches
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
module.exports = function (done) {
|
module.exports = function (done) {
|
||||||
var _ = require('../../src/lib/utils');
|
const _ = require('../../src/lib/utils');
|
||||||
|
|
||||||
var chalk = require('chalk');
|
const chalk = require('chalk');
|
||||||
var fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
|
const fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
|
||||||
var write = require('fs').writeFile;
|
const write = require('fs').writeFile;
|
||||||
|
|
||||||
var outputPath = fromRoot('docs/configuration.asciidoc');
|
const outputPath = fromRoot('docs/configuration.asciidoc');
|
||||||
write(outputPath, require('./templates').configurationDocs(), 'utf8', done);
|
write(outputPath, require('./templates').configurationDocs(), 'utf8', done);
|
||||||
console.log(chalk.white.bold('wrote'), 'configuration docs to', outputPath);
|
console.log(chalk.white.bold('wrote'), 'configuration docs to', outputPath);
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
module.exports = function (done) {
|
module.exports = function (done) {
|
||||||
var _ = require('../../src/lib/utils');
|
const _ = require('../../src/lib/utils');
|
||||||
var utils = require('../../grunt/utils');
|
const utils = require('../../grunt/utils');
|
||||||
|
|
||||||
var chalk = require('chalk');
|
const chalk = require('chalk');
|
||||||
var fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
|
const fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
|
||||||
var write = require('fs').writeFile;
|
const write = require('fs').writeFile;
|
||||||
|
|
||||||
var outputPath = fromRoot('docs/index.asciidoc');
|
const outputPath = fromRoot('docs/index.asciidoc');
|
||||||
|
|
||||||
write(outputPath, require('./templates').docsIndex({
|
write(outputPath, require('./templates').docsIndex({
|
||||||
apiFiles: utils.stableBranches.map(function (branch) {
|
apiFiles: utils.stableBranches.map(function (branch) {
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
/* jshint curly: false */
|
/* jshint curly: false */
|
||||||
var async = require('async');
|
const async = require('async');
|
||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
var spawn = require('../_spawn');
|
const spawn = require('../_spawn');
|
||||||
var argv = require('optimist')
|
let argv = require('optimist')
|
||||||
.options({
|
.options({
|
||||||
verbose: {
|
verbose: {
|
||||||
alias: 'v',
|
alias: 'v',
|
||||||
@ -27,15 +27,15 @@ var argv = require('optimist')
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
var path = require('path');
|
const path = require('path');
|
||||||
var fromRoot = path.join.bind(path, require('find-root')(__dirname));
|
const fromRoot = path.join.bind(path, require('find-root')(__dirname));
|
||||||
var utils = require(fromRoot('grunt/utils'));
|
const utils = require(fromRoot('grunt/utils'));
|
||||||
var _ = require(fromRoot('src/lib/utils'));
|
const _ = require(fromRoot('src/lib/utils'));
|
||||||
var esUrl = process.env.ES_REPO
|
const esUrl = process.env.ES_REPO
|
||||||
? path.resolve(process.cwd(), process.env.ES_REPO)
|
? path.resolve(process.cwd(), process.env.ES_REPO)
|
||||||
: 'https://github.com/elastic/elasticsearch.git';
|
: 'https://github.com/elastic/elasticsearch.git';
|
||||||
|
|
||||||
var branches;
|
let branches;
|
||||||
|
|
||||||
if (process.env.npm_config_argv) {
|
if (process.env.npm_config_argv) {
|
||||||
// when called by NPM
|
// when called by NPM
|
||||||
@ -51,7 +51,7 @@ if (argv.branch) {
|
|||||||
branches = utils.branches;
|
branches = utils.branches;
|
||||||
}
|
}
|
||||||
|
|
||||||
var paths = {
|
const paths = {
|
||||||
root: fromRoot('.'),
|
root: fromRoot('.'),
|
||||||
src: fromRoot('src'),
|
src: fromRoot('src'),
|
||||||
esSrc: fromRoot('src/_elasticsearch_'),
|
esSrc: fromRoot('src/_elasticsearch_'),
|
||||||
@ -70,7 +70,7 @@ var paths = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function isDirectory(dir) {
|
function isDirectory(dir) {
|
||||||
var stat;
|
let stat;
|
||||||
try { stat = fs.statSync(dir); } catch (e) {}
|
try { stat = fs.statSync(dir); } catch (e) {}
|
||||||
return (stat && stat.isDirectory());
|
return (stat && stat.isDirectory());
|
||||||
}
|
}
|
||||||
@ -129,15 +129,15 @@ function initStep() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function fetchBranchesStep() {
|
function fetchBranchesStep() {
|
||||||
var branchArgs = branches.map(function (b) { return b + ':' + b; });
|
const branchArgs = branches.map(function (b) { return b + ':' + b; });
|
||||||
return spawnStep('git', ['fetch', '--no-tags', '--force', 'origin'].concat(branchArgs), paths.esSrc);
|
return spawnStep('git', ['fetch', '--no-tags', '--force', 'origin'].concat(branchArgs), paths.esSrc);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function findGeneratedApiFiles() {
|
function findGeneratedApiFiles() {
|
||||||
var anyApiMethodDocs = /^(configuration|index|api_methods).*\.asciidoc$/;
|
const anyApiMethodDocs = /^(configuration|index|api_methods).*\.asciidoc$/;
|
||||||
var anyApiJsFiled = /^.+\.js$/;
|
const anyApiJsFiled = /^.+\.js$/;
|
||||||
var allBranches = _.isEqual(branches, utils.branches);
|
const allBranches = _.isEqual(branches, utils.branches);
|
||||||
|
|
||||||
if (allBranches) {
|
if (allBranches) {
|
||||||
return [
|
return [
|
||||||
@ -147,11 +147,11 @@ function findGeneratedApiFiles() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return branches.reduce(function (files, branch) {
|
return branches.reduce(function (files, branch) {
|
||||||
var b = _.snakeCase(branch);
|
const b = _.snakeCase(branch);
|
||||||
|
|
||||||
files.push(dirOpts(paths.docs, 'api_methods_' + b + '.asciidoc'));
|
files.push(dirOpts(paths.docs, 'api_methods_' + b + '.asciidoc'));
|
||||||
|
|
||||||
var isDefault = branch === utils.branches._default;
|
const isDefault = branch === utils.branches._default;
|
||||||
if (isDefault) {
|
if (isDefault) {
|
||||||
files.push(dirOpts(paths.docs, 'api_methods.asciidoc'));
|
files.push(dirOpts(paths.docs, 'api_methods.asciidoc'));
|
||||||
}
|
}
|
||||||
@ -164,8 +164,8 @@ function findGeneratedApiFiles() {
|
|||||||
|
|
||||||
|
|
||||||
function clearGeneratedFiles() {
|
function clearGeneratedFiles() {
|
||||||
var esArchives = /^_elasticsearch_(master|[\dx_]+|\.tar)$/;
|
const esArchives = /^_elasticsearch_(master|[\dx_]+|\.tar)$/;
|
||||||
var generatedFiles = [];
|
const generatedFiles = [];
|
||||||
|
|
||||||
if (argv.api) {
|
if (argv.api) {
|
||||||
generatedFiles.push(findGeneratedApiFiles());
|
generatedFiles.push(findGeneratedApiFiles());
|
||||||
@ -173,7 +173,7 @@ function clearGeneratedFiles() {
|
|||||||
|
|
||||||
generatedFiles.push(dirRegex(paths.src, esArchives));
|
generatedFiles.push(dirRegex(paths.src, esArchives));
|
||||||
|
|
||||||
var rmSteps = _.chain(generatedFiles)
|
const rmSteps = _.chain(generatedFiles)
|
||||||
.flatten()
|
.flatten()
|
||||||
.uniq()
|
.uniq()
|
||||||
.map(function (path) {
|
.map(function (path) {
|
||||||
@ -191,7 +191,7 @@ function clearGeneratedFiles() {
|
|||||||
function removePrevArchive(branch) {
|
function removePrevArchive(branch) {
|
||||||
if (!argv.update) return;
|
if (!argv.update) return;
|
||||||
|
|
||||||
var dir = paths.getArchiveDir(branch);
|
const dir = paths.getArchiveDir(branch);
|
||||||
if (!isDirectory(dir)) return;
|
if (!isDirectory(dir)) return;
|
||||||
|
|
||||||
return spawnStep('rm', ['-rf', dir], paths.root);
|
return spawnStep('rm', ['-rf', dir], paths.root);
|
||||||
@ -199,10 +199,10 @@ function removePrevArchive(branch) {
|
|||||||
|
|
||||||
function createArchive(branch) {
|
function createArchive(branch) {
|
||||||
return function (done) {
|
return function (done) {
|
||||||
var dir = paths.getArchiveDir(branch);
|
const dir = paths.getArchiveDir(branch);
|
||||||
var tarball = paths.getArchiveTarball(branch);
|
const tarball = paths.getArchiveTarball(branch);
|
||||||
var specPathInRepo = paths.getSpecPathInRepo(branch);
|
const specPathInRepo = paths.getSpecPathInRepo(branch);
|
||||||
var subDirCount = _.countBy(specPathInRepo, p => p === '/').true || 0;
|
const subDirCount = _.countBy(specPathInRepo, p => p === '/').true || 0;
|
||||||
|
|
||||||
if (isDirectory(dir)) {
|
if (isDirectory(dir)) {
|
||||||
console.log(branch + ' archive already exists');
|
console.log(branch + ' archive already exists');
|
||||||
@ -227,7 +227,7 @@ function generateStep(branch) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
var steps = [
|
const steps = [
|
||||||
initStep(),
|
initStep(),
|
||||||
clearGeneratedFiles(),
|
clearGeneratedFiles(),
|
||||||
fetchBranchesStep()
|
fetchBranchesStep()
|
||||||
|
|||||||
@ -3,26 +3,26 @@ module.exports = function (branch, done) {
|
|||||||
* Read the API actions form the rest-api-spec repo.
|
* Read the API actions form the rest-api-spec repo.
|
||||||
* @type {[type]}
|
* @type {[type]}
|
||||||
*/
|
*/
|
||||||
var _ = require('../../src/lib/utils');
|
const _ = require('../../src/lib/utils');
|
||||||
var utils = require('../../grunt/utils');
|
const utils = require('../../grunt/utils');
|
||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
var async = require('async');
|
const async = require('async');
|
||||||
var chalk = require('chalk');
|
const chalk = require('chalk');
|
||||||
var path = require('path');
|
const path = require('path');
|
||||||
var fromRoot = path.join.bind(path, require('find-root')(__dirname));
|
const fromRoot = path.join.bind(path, require('find-root')(__dirname));
|
||||||
var templates = require('./templates');
|
const templates = require('./templates');
|
||||||
var Version = require('../Version');
|
const Version = require('../Version');
|
||||||
var urlParamRE = /\{(\w+)\}/g;
|
const urlParamRE = /\{(\w+)\}/g;
|
||||||
|
|
||||||
var files; // populated in readSpecFiles
|
let files; // populated in readSpecFiles
|
||||||
var apiSpec; // populated by parseSpecFiles
|
let apiSpec; // populated by parseSpecFiles
|
||||||
var docVars; // slightly modified clone of apiSpec for the docs
|
let docVars; // slightly modified clone of apiSpec for the docs
|
||||||
|
|
||||||
var branchSuffix = utils.branchSuffix(branch);
|
const branchSuffix = utils.branchSuffix(branch);
|
||||||
var esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch));
|
const esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch));
|
||||||
|
|
||||||
var version = Version.fromBranch(branch);
|
const version = Version.fromBranch(branch);
|
||||||
var overrides = version.mergeOpts(require('./overrides'), {
|
const overrides = version.mergeOpts(require('./overrides'), {
|
||||||
aliases: {},
|
aliases: {},
|
||||||
mergeConcatParams: {},
|
mergeConcatParams: {},
|
||||||
paramAsBody: {},
|
paramAsBody: {},
|
||||||
@ -31,7 +31,7 @@ module.exports = function (branch, done) {
|
|||||||
descriptions: {},
|
descriptions: {},
|
||||||
});
|
});
|
||||||
|
|
||||||
var steps = [
|
const steps = [
|
||||||
readSpecFiles,
|
readSpecFiles,
|
||||||
parseSpecFiles,
|
parseSpecFiles,
|
||||||
writeApiFile
|
writeApiFile
|
||||||
@ -51,13 +51,13 @@ module.exports = function (branch, done) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
function readSpecFiles(done) {
|
function readSpecFiles(done) {
|
||||||
var apiDir = path.join(esDir, 'rest-api-spec/api/');
|
const apiDir = path.join(esDir, 'rest-api-spec/api/');
|
||||||
files = fs.readdirSync(apiDir)
|
files = fs.readdirSync(apiDir)
|
||||||
.filter(function (filename) {
|
.filter(function (filename) {
|
||||||
return filename[0] !== '_'
|
return filename[0] !== '_';
|
||||||
})
|
})
|
||||||
.map(function (filename) {
|
.map(function (filename) {
|
||||||
var module = require(apiDir + filename);
|
const module = require(apiDir + filename);
|
||||||
delete require.cache[apiDir + filename];
|
delete require.cache[apiDir + filename];
|
||||||
return module;
|
return module;
|
||||||
});
|
});
|
||||||
@ -65,7 +65,7 @@ module.exports = function (branch, done) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function parseSpecFiles(done) {
|
function parseSpecFiles(done) {
|
||||||
var actions = [];
|
const actions = [];
|
||||||
|
|
||||||
files.forEach(function (spec) {
|
files.forEach(function (spec) {
|
||||||
__puke__transformSpec(spec).forEach(function (action) {
|
__puke__transformSpec(spec).forEach(function (action) {
|
||||||
@ -74,16 +74,16 @@ module.exports = function (branch, done) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// collect the namespaces from the action locations
|
// collect the namespaces from the action locations
|
||||||
var namespaces = _.filter(_.map(actions, function (action) {
|
const namespaces = _.filter(_.map(actions, function (action) {
|
||||||
return action.location
|
return action.location
|
||||||
.split('.')
|
.split('.')
|
||||||
.slice(0, -1)
|
.slice(0, -1)
|
||||||
.filter(step => step !== 'prototype')
|
.filter(step => step !== 'prototype')
|
||||||
.join('.prototype.')
|
.join('.prototype.');
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// seperate the proxy actions
|
// seperate the proxy actions
|
||||||
var groups = _.groupBy(actions, function (action) {
|
const groups = _.groupBy(actions, function (action) {
|
||||||
return action.proxy ? 'proxies' : 'normal';
|
return action.proxy ? 'proxies' : 'normal';
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -95,7 +95,7 @@ module.exports = function (branch, done) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (!_.find(apiSpec.actions, { name: 'create' })) {
|
if (!_.find(apiSpec.actions, { name: 'create' })) {
|
||||||
var create = _.assign(
|
const create = _.assign(
|
||||||
{},
|
{},
|
||||||
_.cloneDeep(_.find(apiSpec.actions, { name: 'index' })),
|
_.cloneDeep(_.find(apiSpec.actions, { name: 'index' })),
|
||||||
{
|
{
|
||||||
@ -115,8 +115,8 @@ module.exports = function (branch, done) {
|
|||||||
|
|
||||||
[].concat(apiSpec.actions, apiSpec.proxies)
|
[].concat(apiSpec.actions, apiSpec.proxies)
|
||||||
.forEach(function (action) {
|
.forEach(function (action) {
|
||||||
var examplePath = overrides.examples[action.name] || action.name + '.asciidoc';
|
const examplePath = overrides.examples[action.name] || action.name + '.asciidoc';
|
||||||
var descriptionPath = overrides.descriptions[action.name] || action.name + '.asciidoc';
|
const descriptionPath = overrides.descriptions[action.name] || action.name + '.asciidoc';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
action.examples = fs.readFileSync(fromRoot('docs/_examples', examplePath), 'utf8');
|
action.examples = fs.readFileSync(fromRoot('docs/_examples', examplePath), 'utf8');
|
||||||
@ -129,13 +129,13 @@ module.exports = function (branch, done) {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
action.description = '// no description';
|
action.description = '// no description';
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
done();
|
done();
|
||||||
}
|
}
|
||||||
|
|
||||||
function writeApiFile(done) {
|
function writeApiFile(done) {
|
||||||
var outputPath = fromRoot('src/lib/apis/' + _.snakeCase(branch) + '.js');
|
const outputPath = fromRoot('src/lib/apis/' + _.snakeCase(branch) + '.js');
|
||||||
fs.writeFileSync(outputPath, templates.apiFile(apiSpec));
|
fs.writeFileSync(outputPath, templates.apiFile(apiSpec));
|
||||||
console.log(chalk.white.bold('wrote'), apiSpec.actions.length, 'api actions to', outputPath);
|
console.log(chalk.white.bold('wrote'), apiSpec.actions.length, 'api actions to', outputPath);
|
||||||
done();
|
done();
|
||||||
@ -173,7 +173,7 @@ module.exports = function (branch, done) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function writeMethodDocs(done) {
|
function writeMethodDocs(done) {
|
||||||
var filename = fromRoot('docs/api_methods' + branchSuffix + '.asciidoc');
|
const filename = fromRoot('docs/api_methods' + branchSuffix + '.asciidoc');
|
||||||
fs.writeFile(
|
fs.writeFile(
|
||||||
filename,
|
filename,
|
||||||
templates.apiMethods(docVars),
|
templates.apiMethods(docVars),
|
||||||
@ -187,7 +187,7 @@ module.exports = function (branch, done) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function __puke__transformSpec(spec) { // eslint-disable-line
|
function __puke__transformSpec(spec) { // eslint-disable-line
|
||||||
var actions = [];
|
const actions = [];
|
||||||
|
|
||||||
// itterate all of the specs within the file, should only be one
|
// itterate all of the specs within the file, should only be one
|
||||||
_.each(spec, function (def, name) {
|
_.each(spec, function (def, name) {
|
||||||
@ -198,10 +198,10 @@ module.exports = function (branch, done) {
|
|||||||
def.documentation = 'http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html';
|
def.documentation = 'http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html';
|
||||||
}
|
}
|
||||||
|
|
||||||
var steps = name.split('.');
|
const steps = name.split('.');
|
||||||
|
|
||||||
function transformParamKeys(note, param, key) {
|
function transformParamKeys(note, param, key) {
|
||||||
var cmlKey = _.camelCase(key);
|
const cmlKey = _.camelCase(key);
|
||||||
if (cmlKey !== key) {
|
if (cmlKey !== key) {
|
||||||
param.name = key;
|
param.name = key;
|
||||||
}
|
}
|
||||||
@ -211,24 +211,24 @@ module.exports = function (branch, done) {
|
|||||||
def.url.params = _.transform(def.url.params, transformParamKeys, {});
|
def.url.params = _.transform(def.url.params, transformParamKeys, {});
|
||||||
def.url.parts = _.transform(def.url.parts, transformParamKeys, {});
|
def.url.parts = _.transform(def.url.parts, transformParamKeys, {});
|
||||||
|
|
||||||
var allParams = _.extend({}, def.url.params, def.url.parts);
|
const allParams = _.extend({}, def.url.params, def.url.parts);
|
||||||
_.forOwn(allParams, (paramSpec, paramName) => {
|
_.forOwn(allParams, (paramSpec, paramName) => {
|
||||||
const toMerge = _.get(overrides, ['mergeConcatParams', name, paramName])
|
const toMerge = _.get(overrides, ['mergeConcatParams', name, paramName]);
|
||||||
if (toMerge) {
|
if (toMerge) {
|
||||||
_.merge(paramSpec, toMerge, (dest, src) => {
|
_.merge(paramSpec, toMerge, (dest, src) => {
|
||||||
if (_.isArray(dest) && _.isArray(src)) {
|
if (_.isArray(dest) && _.isArray(src)) {
|
||||||
return dest.concat(src)
|
return dest.concat(src);
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (paramSpec.options) {
|
if (paramSpec.options) {
|
||||||
const invalidOpts = paramSpec.options.some(opt => typeof opt !== 'string')
|
const invalidOpts = paramSpec.options.some(opt => typeof opt !== 'string');
|
||||||
if (invalidOpts) throw new Error(`${name} has options that are not strings...`)
|
if (invalidOpts) throw new Error(`${name} has options that are not strings...`);
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
var spec = {
|
const spec = {
|
||||||
name: name,
|
name: name,
|
||||||
methods: _.map(def.methods, function (m) { return m.toUpperCase(); }),
|
methods: _.map(def.methods, function (m) { return m.toUpperCase(); }),
|
||||||
params: def.url.params,
|
params: def.url.params,
|
||||||
@ -248,15 +248,15 @@ module.exports = function (branch, done) {
|
|||||||
spec.requestTimeout = 3000;
|
spec.requestTimeout = 3000;
|
||||||
}
|
}
|
||||||
|
|
||||||
var urls = _.difference(def.url.paths, overrides.aliases[name]);
|
let urls = _.difference(def.url.paths, overrides.aliases[name]);
|
||||||
var urlSignatures = [];
|
const urlSignatures = [];
|
||||||
urls = _.map(urls, function (url) {
|
urls = _.map(urls, function (url) {
|
||||||
var optionalVars = {};
|
const optionalVars = {};
|
||||||
var requiredVars = {};
|
const requiredVars = {};
|
||||||
var param;
|
let param;
|
||||||
var name;
|
let name;
|
||||||
var target;
|
let target;
|
||||||
var match;
|
let match;
|
||||||
|
|
||||||
if (url.charAt(0) !== '/') {
|
if (url.charAt(0) !== '/') {
|
||||||
url = '/' + url;
|
url = '/' + url;
|
||||||
@ -317,10 +317,10 @@ module.exports = function (branch, done) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// escape method names with "special" keywords
|
// escape method names with "special" keywords
|
||||||
var location = spec.name.split('.').join('.prototype.')
|
const location = spec.name.split('.').join('.prototype.')
|
||||||
.replace(/(^|\.)(delete|default)(\.|$)/g, '[\'$2\']');
|
.replace(/(^|\.)(delete|default)(\.|$)/g, '[\'$2\']');
|
||||||
|
|
||||||
var action = {
|
const action = {
|
||||||
_methods: spec.methods,
|
_methods: spec.methods,
|
||||||
spec: _.pick(spec, [
|
spec: _.pick(spec, [
|
||||||
'params',
|
'params',
|
||||||
@ -339,7 +339,7 @@ module.exports = function (branch, done) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function hasMethod(/* ...methods */) {
|
function hasMethod(/* ...methods */) {
|
||||||
for (var i = 0; i < arguments.length; i++) {
|
for (let i = 0; i < arguments.length; i++) {
|
||||||
if (~action._methods.indexOf(arguments[i])) {
|
if (~action._methods.indexOf(arguments[i])) {
|
||||||
continue;
|
continue;
|
||||||
} else {
|
} else {
|
||||||
@ -352,7 +352,7 @@ module.exports = function (branch, done) {
|
|||||||
return hasMethod.apply(null, arguments) && arguments.length === action._methods.length;
|
return hasMethod.apply(null, arguments) && arguments.length === action._methods.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
var method;
|
let method;
|
||||||
|
|
||||||
if (action._methods.length === 1) {
|
if (action._methods.length === 1) {
|
||||||
method = action._methods[0];
|
method = action._methods[0];
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
|
|
||||||
var _ = require('../../../src/lib/utils');
|
const _ = require('../../../src/lib/utils');
|
||||||
var utils = require('../../../grunt/utils');
|
const utils = require('../../../grunt/utils');
|
||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
var path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -31,20 +31,20 @@ function stringify(thing, pretty) {
|
|||||||
* We'll collect the templates here
|
* We'll collect the templates here
|
||||||
* @type {Object}
|
* @type {Object}
|
||||||
*/
|
*/
|
||||||
var templates = {};
|
const templates = {};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* These keys will be available as local variables to each template
|
* These keys will be available as local variables to each template
|
||||||
* @type {Object}
|
* @type {Object}
|
||||||
*/
|
*/
|
||||||
var templateGlobals = {
|
const templateGlobals = {
|
||||||
|
|
||||||
stringify: stringify,
|
stringify: stringify,
|
||||||
|
|
||||||
_: _,
|
_: _,
|
||||||
|
|
||||||
indent: function (block, spaces) {
|
indent: function (block, spaces) {
|
||||||
var indent = _.repeat(' ', spaces);
|
const indent = _.repeat(' ', spaces);
|
||||||
return block.split('\n').map(function (line) {
|
return block.split('\n').map(function (line) {
|
||||||
return indent + line;
|
return indent + line;
|
||||||
}).join('\n');
|
}).join('\n');
|
||||||
@ -58,7 +58,7 @@ var templateGlobals = {
|
|||||||
switch (type && type.toLowerCase ? type.toLowerCase() : 'any') {
|
switch (type && type.toLowerCase ? type.toLowerCase() : 'any') {
|
||||||
case 'time':
|
case 'time':
|
||||||
case 'duration':
|
case 'duration':
|
||||||
if (paramName === 'timestamp') return 'Timestamp'
|
if (paramName === 'timestamp') return 'Timestamp';
|
||||||
return '<<api-param-type-duration-string,`DurationString`>>';
|
return '<<api-param-type-duration-string,`DurationString`>>';
|
||||||
case 'any':
|
case 'any':
|
||||||
return 'anything';
|
return 'anything';
|
||||||
@ -96,7 +96,7 @@ var templateGlobals = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
fs.readdirSync(path.resolve(__dirname)).forEach(function (filename) {
|
fs.readdirSync(path.resolve(__dirname)).forEach(function (filename) {
|
||||||
var name = filename.replace(/\..+$/, '');
|
const name = filename.replace(/\..+$/, '');
|
||||||
if (name !== 'index') {
|
if (name !== 'index') {
|
||||||
templates[name] = _.template(
|
templates[name] = _.template(
|
||||||
fs.readFileSync(path.resolve(__dirname, filename), 'utf8'),
|
fs.readFileSync(path.resolve(__dirname, filename), 'utf8'),
|
||||||
|
|||||||
@ -2,16 +2,16 @@ module.exports = function (branch, done) {
|
|||||||
/**
|
/**
|
||||||
* Creates a JSON version of the YAML test suite that can be simply bundled for use in the browser.
|
* Creates a JSON version of the YAML test suite that can be simply bundled for use in the browser.
|
||||||
*/
|
*/
|
||||||
var jsYaml = require('js-yaml');
|
const jsYaml = require('js-yaml');
|
||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
var async = require('async');
|
const async = require('async');
|
||||||
var chalk = require('chalk');
|
const chalk = require('chalk');
|
||||||
var path = require('path');
|
const path = require('path');
|
||||||
var fromRoot = path.join.bind(path, require('find-root')(__dirname));
|
const fromRoot = path.join.bind(path, require('find-root')(__dirname));
|
||||||
var _ = require(fromRoot('src/lib/utils'));
|
const _ = require(fromRoot('src/lib/utils'));
|
||||||
var tests = {}; // populated in readYamlTests
|
const tests = {}; // populated in readYamlTests
|
||||||
|
|
||||||
var esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch));
|
const esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch));
|
||||||
|
|
||||||
// generate the yaml tests
|
// generate the yaml tests
|
||||||
async.series([
|
async.series([
|
||||||
@ -21,16 +21,16 @@ module.exports = function (branch, done) {
|
|||||||
], done);
|
], done);
|
||||||
|
|
||||||
function readYamlTests(done) {
|
function readYamlTests(done) {
|
||||||
var testDir = path.join(esDir, 'rest-api-spec/test/');
|
const testDir = path.join(esDir, 'rest-api-spec/test/');
|
||||||
|
|
||||||
function readDirectories(dir) {
|
function readDirectories(dir) {
|
||||||
fs.readdirSync(dir).forEach(function (filename) {
|
fs.readdirSync(dir).forEach(function (filename) {
|
||||||
var filePath = path.join(dir, filename);
|
const filePath = path.join(dir, filename);
|
||||||
var stat = fs.statSync(filePath);
|
const stat = fs.statSync(filePath);
|
||||||
if (stat.isDirectory()) {
|
if (stat.isDirectory()) {
|
||||||
readDirectories(filePath);
|
readDirectories(filePath);
|
||||||
} else if (filename.match(/\.yaml$/)) {
|
} else if (filename.match(/\.yaml$/)) {
|
||||||
var file = tests[path.relative(testDir, filePath)] = [];
|
const file = tests[path.relative(testDir, filePath)] = [];
|
||||||
jsYaml.loadAll(fs.readFileSync(filePath, 'utf8'), function (doc) {
|
jsYaml.loadAll(fs.readFileSync(filePath, 'utf8'), function (doc) {
|
||||||
file.push(doc);
|
file.push(doc);
|
||||||
});
|
});
|
||||||
@ -43,14 +43,14 @@ module.exports = function (branch, done) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function writeYamlTests(done) {
|
function writeYamlTests(done) {
|
||||||
var testFile = fromRoot('test/integration/yaml_suite/yaml_tests_' + _.snakeCase(branch) + '.json');
|
const testFile = fromRoot('test/integration/yaml_suite/yaml_tests_' + _.snakeCase(branch) + '.json');
|
||||||
fs.writeFileSync(testFile, JSON.stringify(tests, null, ' '), 'utf8');
|
fs.writeFileSync(testFile, JSON.stringify(tests, null, ' '), 'utf8');
|
||||||
console.log(chalk.white.bold('wrote') + ' YAML tests as JSON to', testFile);
|
console.log(chalk.white.bold('wrote') + ' YAML tests as JSON to', testFile);
|
||||||
done();
|
done();
|
||||||
}
|
}
|
||||||
|
|
||||||
function writeTestIndex(done) {
|
function writeTestIndex(done) {
|
||||||
var file = fromRoot('test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js');
|
const file = fromRoot('test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js');
|
||||||
fs.writeFileSync(file, 'require(\'./run\')(\'' + branch + '\');\n', 'utf8');
|
fs.writeFileSync(file, 'require(\'./run\')(\'' + branch + '\');\n', 'utf8');
|
||||||
console.log(chalk.white.bold('wrote') + ' YAML index to', file);
|
console.log(chalk.white.bold('wrote') + ' YAML index to', file);
|
||||||
done();
|
done();
|
||||||
|
|||||||
@ -1,15 +1,15 @@
|
|||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
var spawn = require('../_spawn');
|
const spawn = require('../_spawn');
|
||||||
var async = require('async');
|
const async = require('async');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
|
|
||||||
var root = require('path').join(__dirname, '../..');
|
const root = require('path').join(__dirname, '../..');
|
||||||
var bowerDir = root + '/src/bower_es_js';
|
const bowerDir = root + '/src/bower_es_js';
|
||||||
|
|
||||||
// get both the bower and node package files
|
// get both the bower and node package files
|
||||||
var bowerJson = require(bowerDir + '/bower.json');
|
const bowerJson = require(bowerDir + '/bower.json');
|
||||||
var bowerPackageJson = require(bowerDir + '/package.json');
|
const bowerPackageJson = require(bowerDir + '/package.json');
|
||||||
var esjsJson = require(root + '/package.json');
|
const esjsJson = require(root + '/package.json');
|
||||||
|
|
||||||
// update the version to match the node version
|
// update the version to match the node version
|
||||||
bowerJson.version = esjsJson.version;
|
bowerJson.version = esjsJson.version;
|
||||||
|
|||||||
@ -4,8 +4,8 @@
|
|||||||
*
|
*
|
||||||
* It will also instruct the client to use Angular's $http service for it's ajax requests
|
* It will also instruct the client to use Angular's $http service for it's ajax requests
|
||||||
*/
|
*/
|
||||||
var AngularConnector = require('./lib/connectors/angular');
|
const AngularConnector = require('./lib/connectors/angular');
|
||||||
var Client = require('./lib/client');
|
const Client = require('./lib/client');
|
||||||
|
|
||||||
process.angular_build = true;
|
process.angular_build = true;
|
||||||
|
|
||||||
@ -13,7 +13,7 @@ process.angular_build = true;
|
|||||||
angular.module('elasticsearch', [])
|
angular.module('elasticsearch', [])
|
||||||
.factory('esFactory', ['$injector', '$q', function ($injector, $q) {
|
.factory('esFactory', ['$injector', '$q', function ($injector, $q) {
|
||||||
|
|
||||||
var factory = function (config) {
|
const factory = function (config) {
|
||||||
config = config || {};
|
config = config || {};
|
||||||
config.connectionClass = AngularConnector;
|
config.connectionClass = AngularConnector;
|
||||||
config.$injector = $injector;
|
config.$injector = $injector;
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
/* global jQuery */
|
/* global jQuery */
|
||||||
(function ($) {
|
(function ($) {
|
||||||
process.jquery_build = true;
|
process.jquery_build = true;
|
||||||
var es = require('./elasticsearch');
|
const es = require('./elasticsearch');
|
||||||
|
|
||||||
function defer() {
|
function defer() {
|
||||||
var def = $.Deferred();
|
const def = $.Deferred();
|
||||||
// def.promise is usually a property (in normal implementations)
|
// def.promise is usually a property (in normal implementations)
|
||||||
// we override the promise to keep things working
|
// we override the promise to keep things working
|
||||||
def.promise = def.promise();
|
def.promise = def.promise();
|
||||||
|
|||||||
@ -26,9 +26,9 @@
|
|||||||
|
|
||||||
module.exports = Client;
|
module.exports = Client;
|
||||||
|
|
||||||
var Transport = require('./transport');
|
const Transport = require('./transport');
|
||||||
var clientAction = require('./client_action');
|
const clientAction = require('./client_action');
|
||||||
var _ = require('./utils');
|
const _ = require('./utils');
|
||||||
|
|
||||||
function Client(config) {
|
function Client(config) {
|
||||||
config = config || {};
|
config = config || {};
|
||||||
@ -71,7 +71,7 @@ function Client(config) {
|
|||||||
config.sniffEndpoint = '/_cluster/nodes';
|
config.sniffEndpoint = '/_cluster/nodes';
|
||||||
}
|
}
|
||||||
|
|
||||||
var Constructor = EsApiClient;
|
let Constructor = EsApiClient;
|
||||||
|
|
||||||
if (config.plugins) {
|
if (config.plugins) {
|
||||||
Constructor.prototype = _.cloneDeep(Constructor.prototype);
|
Constructor.prototype = _.cloneDeep(Constructor.prototype);
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
|
|
||||||
var _ = require('./utils');
|
const _ = require('./utils');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a client action factory that uses specific defaults
|
* Constructs a client action factory that uses specific defaults
|
||||||
@ -37,7 +37,7 @@ exports.namespaceFactory = function () {
|
|||||||
function makeFactoryWithModifier(modifier) {
|
function makeFactoryWithModifier(modifier) {
|
||||||
modifier = modifier || _.identity;
|
modifier = modifier || _.identity;
|
||||||
|
|
||||||
var factory = function (spec) {
|
const factory = function (spec) {
|
||||||
spec = modifier(spec);
|
spec = modifier(spec);
|
||||||
|
|
||||||
if (!_.isPlainObject(spec.params)) {
|
if (!_.isPlainObject(spec.params)) {
|
||||||
@ -63,7 +63,7 @@ function makeFactoryWithModifier(modifier) {
|
|||||||
if (typeof cb === 'function') {
|
if (typeof cb === 'function') {
|
||||||
_.nextTick(cb, e);
|
_.nextTick(cb, e);
|
||||||
} else {
|
} else {
|
||||||
var def = this.transport.defer();
|
const def = this.transport.defer();
|
||||||
def.reject(e);
|
def.reject(e);
|
||||||
return def.promise;
|
return def.promise;
|
||||||
}
|
}
|
||||||
@ -96,7 +96,7 @@ function makeFactoryWithModifier(modifier) {
|
|||||||
return factory;
|
return factory;
|
||||||
}
|
}
|
||||||
|
|
||||||
var castType = {
|
const castType = {
|
||||||
'enum': function validSelection(param, val, name) {
|
'enum': function validSelection(param, val, name) {
|
||||||
if (_.isString(val) && val.indexOf(',') > -1) {
|
if (_.isString(val) && val.indexOf(',') > -1) {
|
||||||
val = commaSepList(val);
|
val = commaSepList(val);
|
||||||
@ -108,7 +108,7 @@ var castType = {
|
|||||||
}).join(',');
|
}).join(',');
|
||||||
}
|
}
|
||||||
|
|
||||||
for (var i = 0; i < param.options.length; i++) {
|
for (let i = 0; i < param.options.length; i++) {
|
||||||
if (param.options[i] === String(val)) {
|
if (param.options[i] === String(val)) {
|
||||||
return param.options[i];
|
return param.options[i];
|
||||||
}
|
}
|
||||||
@ -183,7 +183,7 @@ var castType = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function resolveUrl(url, params) {
|
function resolveUrl(url, params) {
|
||||||
var vars = {}, i, key;
|
let vars = {}, i, key;
|
||||||
|
|
||||||
if (url.req) {
|
if (url.req) {
|
||||||
// url has required params
|
// url has required params
|
||||||
@ -223,7 +223,7 @@ function resolveUrl(url, params) {
|
|||||||
vars[key] = params[key];
|
vars[key] = params[key];
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
vars[key] = url.opt[key]['default'];
|
vars[key] = url.opt[key].default;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -243,11 +243,11 @@ function resolveUrl(url, params) {
|
|||||||
|
|
||||||
|
|
||||||
function exec(transport, spec, params, cb) {
|
function exec(transport, spec, params, cb) {
|
||||||
var request = {
|
const request = {
|
||||||
method: spec.method
|
method: spec.method
|
||||||
};
|
};
|
||||||
var query = {};
|
const query = {};
|
||||||
var i;
|
let i;
|
||||||
|
|
||||||
// pass the timeout from the spec
|
// pass the timeout from the spec
|
||||||
if (spec.requestTimeout) {
|
if (spec.requestTimeout) {
|
||||||
@ -297,7 +297,7 @@ function exec(transport, spec, params, cb) {
|
|||||||
|
|
||||||
if (!request.path) {
|
if (!request.path) {
|
||||||
// there must have been some mimimun requirements that were not met
|
// there must have been some mimimun requirements that were not met
|
||||||
var minUrl = spec.url || spec.urls[spec.urls.length - 1];
|
const minUrl = spec.url || spec.urls[spec.urls.length - 1];
|
||||||
throw new TypeError('Unable to build a path with those params. Supply at least ' + _.keys(minUrl.req).join(', '));
|
throw new TypeError('Unable to build a path with those params. Supply at least ' + _.keys(minUrl.req).join(', '));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -312,7 +312,7 @@ function exec(transport, spec, params, cb) {
|
|||||||
}, []);
|
}, []);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (var key in params) {
|
for (const key in params) {
|
||||||
if (params.hasOwnProperty(key) && params[key] != null) {
|
if (params.hasOwnProperty(key) && params[key] != null) {
|
||||||
switch (key) {
|
switch (key) {
|
||||||
case 'body':
|
case 'body':
|
||||||
@ -339,7 +339,7 @@ function exec(transport, spec, params, cb) {
|
|||||||
query[paramSpec.name] = params[key];
|
query[paramSpec.name] = params[key];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (paramSpec['default'] && query[paramSpec.name] === paramSpec['default']) {
|
if (paramSpec.default && query[paramSpec.name] === paramSpec.default) {
|
||||||
delete query[paramSpec.name];
|
delete query[paramSpec.name];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
module.exports = ConnectionAbstract;
|
module.exports = ConnectionAbstract;
|
||||||
|
|
||||||
var _ = require('./utils');
|
const _ = require('./utils');
|
||||||
var EventEmitter = require('events').EventEmitter;
|
const EventEmitter = require('events').EventEmitter;
|
||||||
var Log = require('./log');
|
const Log = require('./log');
|
||||||
var Host = require('./host');
|
const Host = require('./host');
|
||||||
var errors = require('./errors');
|
const errors = require('./errors');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Abstract class used for Connection classes
|
* Abstract class used for Connection classes
|
||||||
@ -52,10 +52,10 @@ ConnectionAbstract.prototype.ping = function (params, cb) {
|
|||||||
cb = typeof cb === 'function' ? cb : null;
|
cb = typeof cb === 'function' ? cb : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var requestTimeout = this.pingTimeout;
|
let requestTimeout = this.pingTimeout;
|
||||||
var requestTimeoutId;
|
let requestTimeoutId;
|
||||||
var aborted;
|
let aborted;
|
||||||
var abort;
|
let abort;
|
||||||
|
|
||||||
if (params && params.hasOwnProperty('requestTimeout')) {
|
if (params && params.hasOwnProperty('requestTimeout')) {
|
||||||
requestTimeout = params.requestTimeout;
|
requestTimeout = params.requestTimeout;
|
||||||
@ -88,7 +88,7 @@ ConnectionAbstract.prototype.ping = function (params, cb) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
ConnectionAbstract.prototype.setStatus = function (status) {
|
ConnectionAbstract.prototype.setStatus = function (status) {
|
||||||
var origStatus = this.status;
|
const origStatus = this.status;
|
||||||
this.status = status;
|
this.status = status;
|
||||||
|
|
||||||
this.emit('status set', status, origStatus, this);
|
this.emit('status set', status, origStatus, this);
|
||||||
|
|||||||
@ -9,8 +9,8 @@
|
|||||||
|
|
||||||
module.exports = ConnectionPool;
|
module.exports = ConnectionPool;
|
||||||
|
|
||||||
var _ = require('./utils');
|
const _ = require('./utils');
|
||||||
var Log = require('./log');
|
const Log = require('./log');
|
||||||
|
|
||||||
function ConnectionPool(config) {
|
function ConnectionPool(config) {
|
||||||
config = config || {};
|
config = config || {};
|
||||||
@ -107,14 +107,14 @@ ConnectionPool.prototype.select = function (cb) {
|
|||||||
* @param {ConnectionAbstract} connection - the connection object itself
|
* @param {ConnectionAbstract} connection - the connection object itself
|
||||||
*/
|
*/
|
||||||
ConnectionPool.prototype.onStatusSet = _.handler(function (status, oldStatus, connection) {
|
ConnectionPool.prototype.onStatusSet = _.handler(function (status, oldStatus, connection) {
|
||||||
var index;
|
let index;
|
||||||
|
|
||||||
var died = (status === 'dead');
|
const died = (status === 'dead');
|
||||||
var wasAlreadyDead = (died && oldStatus === 'dead');
|
const wasAlreadyDead = (died && oldStatus === 'dead');
|
||||||
var revived = (!died && oldStatus === 'dead');
|
const revived = (!died && oldStatus === 'dead');
|
||||||
var noChange = (oldStatus === status);
|
const noChange = (oldStatus === status);
|
||||||
var from = this._conns[oldStatus];
|
const from = this._conns[oldStatus];
|
||||||
var to = this._conns[status];
|
const to = this._conns[status];
|
||||||
|
|
||||||
if (noChange && !died) {
|
if (noChange && !died) {
|
||||||
return true;
|
return true;
|
||||||
@ -150,8 +150,8 @@ ConnectionPool.prototype.onStatusSet = _.handler(function (status, oldStatus, co
|
|||||||
* @param {ConnectionAbstract} connection
|
* @param {ConnectionAbstract} connection
|
||||||
*/
|
*/
|
||||||
ConnectionPool.prototype._onConnectionRevived = function (connection) {
|
ConnectionPool.prototype._onConnectionRevived = function (connection) {
|
||||||
var timeout;
|
let timeout;
|
||||||
for (var i = 0; i < this._timeouts.length; i++) {
|
for (let i = 0; i < this._timeouts.length; i++) {
|
||||||
if (this._timeouts[i].conn === connection) {
|
if (this._timeouts[i].conn === connection) {
|
||||||
timeout = this._timeouts[i];
|
timeout = this._timeouts[i];
|
||||||
if (timeout.id) {
|
if (timeout.id) {
|
||||||
@ -169,9 +169,9 @@ ConnectionPool.prototype._onConnectionRevived = function (connection) {
|
|||||||
* @param {Boolean} alreadyWasDead - If the connection was preivously dead this must be set to true
|
* @param {Boolean} alreadyWasDead - If the connection was preivously dead this must be set to true
|
||||||
*/
|
*/
|
||||||
ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDead) {
|
ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDead) {
|
||||||
var timeout;
|
let timeout;
|
||||||
if (alreadyWasDead) {
|
if (alreadyWasDead) {
|
||||||
for (var i = 0; i < this._timeouts.length; i++) {
|
for (let i = 0; i < this._timeouts.length; i++) {
|
||||||
if (this._timeouts[i].conn === connection) {
|
if (this._timeouts[i].conn === connection) {
|
||||||
timeout = this._timeouts[i];
|
timeout = this._timeouts[i];
|
||||||
break;
|
break;
|
||||||
@ -198,17 +198,17 @@ ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDea
|
|||||||
clearTimeout(timeout.id);
|
clearTimeout(timeout.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
var ms = this.calcDeadTimeout(timeout.attempt, this.deadTimeout);
|
const ms = this.calcDeadTimeout(timeout.attempt, this.deadTimeout);
|
||||||
timeout.id = setTimeout(timeout.revive, ms);
|
timeout.id = setTimeout(timeout.revive, ms);
|
||||||
timeout.runAt = _.now() + ms;
|
timeout.runAt = _.now() + ms;
|
||||||
};
|
};
|
||||||
|
|
||||||
ConnectionPool.prototype._selectDeadConnection = function (cb) {
|
ConnectionPool.prototype._selectDeadConnection = function (cb) {
|
||||||
var orderedTimeouts = _.sortBy(this._timeouts, 'runAt');
|
const orderedTimeouts = _.sortBy(this._timeouts, 'runAt');
|
||||||
var log = this.log;
|
const log = this.log;
|
||||||
|
|
||||||
process.nextTick(function next() {
|
process.nextTick(function next() {
|
||||||
var timeout = orderedTimeouts.shift();
|
const timeout = orderedTimeouts.shift();
|
||||||
if (!timeout) {
|
if (!timeout) {
|
||||||
cb(void 0);
|
cb(void 0);
|
||||||
return;
|
return;
|
||||||
@ -247,7 +247,7 @@ ConnectionPool.prototype._selectDeadConnection = function (cb) {
|
|||||||
* @param {Number} [limit] - optional limit on the number of connections to return
|
* @param {Number} [limit] - optional limit on the number of connections to return
|
||||||
*/
|
*/
|
||||||
ConnectionPool.prototype.getConnections = function (status, limit) {
|
ConnectionPool.prototype.getConnections = function (status, limit) {
|
||||||
var list;
|
let list;
|
||||||
if (status) {
|
if (status) {
|
||||||
list = this._conns[status];
|
list = this._conns[status];
|
||||||
} else {
|
} else {
|
||||||
@ -304,11 +304,11 @@ ConnectionPool.prototype.removeConnection = function (connection) {
|
|||||||
* @param {Host[]} hosts - An array of Host instances.
|
* @param {Host[]} hosts - An array of Host instances.
|
||||||
*/
|
*/
|
||||||
ConnectionPool.prototype.setHosts = function (hosts) {
|
ConnectionPool.prototype.setHosts = function (hosts) {
|
||||||
var connection;
|
let connection;
|
||||||
var i;
|
let i;
|
||||||
var id;
|
let id;
|
||||||
var host;
|
let host;
|
||||||
var toRemove = _.clone(this.index);
|
const toRemove = _.clone(this.index);
|
||||||
|
|
||||||
for (i = 0; i < hosts.length; i++) {
|
for (i = 0; i < hosts.length; i++) {
|
||||||
host = hosts[i];
|
host = hosts[i];
|
||||||
@ -322,7 +322,7 @@ ConnectionPool.prototype.setHosts = function (hosts) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var removeIds = _.keys(toRemove);
|
const removeIds = _.keys(toRemove);
|
||||||
for (i = 0; i < removeIds.length; i++) {
|
for (i = 0; i < removeIds.length; i++) {
|
||||||
this.removeConnection(this.index[removeIds[i]]);
|
this.removeConnection(this.index[removeIds[i]]);
|
||||||
}
|
}
|
||||||
|
|||||||
10
src/lib/connectors/angular.js
vendored
10
src/lib/connectors/angular.js
vendored
@ -6,14 +6,14 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = AngularConnector;
|
module.exports = AngularConnector;
|
||||||
|
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
var ConnectionAbstract = require('../connection');
|
const ConnectionAbstract = require('../connection');
|
||||||
var ConnectionFault = require('../errors').ConnectionFault;
|
const ConnectionFault = require('../errors').ConnectionFault;
|
||||||
|
|
||||||
function AngularConnector(host, config) {
|
function AngularConnector(host, config) {
|
||||||
ConnectionAbstract.call(this, host, config);
|
ConnectionAbstract.call(this, host, config);
|
||||||
|
|
||||||
var self = this;
|
const self = this;
|
||||||
config.$injector.invoke(['$http', '$q', function ($http, $q) {
|
config.$injector.invoke(['$http', '$q', function ($http, $q) {
|
||||||
self.$q = $q;
|
self.$q = $q;
|
||||||
self.$http = $http;
|
self.$http = $http;
|
||||||
@ -23,7 +23,7 @@ function AngularConnector(host, config) {
|
|||||||
_.inherits(AngularConnector, ConnectionAbstract);
|
_.inherits(AngularConnector, ConnectionAbstract);
|
||||||
|
|
||||||
AngularConnector.prototype.request = function (params, cb) {
|
AngularConnector.prototype.request = function (params, cb) {
|
||||||
var abort = this.$q.defer();
|
const abort = this.$q.defer();
|
||||||
|
|
||||||
this.$http({
|
this.$http({
|
||||||
method: params.method,
|
method: params.method,
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
var opts = {
|
const opts = {
|
||||||
xhr: require('./xhr'),
|
xhr: require('./xhr'),
|
||||||
jquery: require('./jquery'),
|
jquery: require('./jquery'),
|
||||||
angular: require('./angular')
|
angular: require('./angular')
|
||||||
};
|
};
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
|
|
||||||
// remove modules that have been ignored by browserify
|
// remove modules that have been ignored by browserify
|
||||||
_.each(opts, function (conn, name) {
|
_.each(opts, function (conn, name) {
|
||||||
|
|||||||
@ -8,16 +8,16 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = HttpConnector;
|
module.exports = HttpConnector;
|
||||||
|
|
||||||
var handles = {
|
const handles = {
|
||||||
http: require('http'),
|
http: require('http'),
|
||||||
https: require('https')
|
https: require('https')
|
||||||
};
|
};
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
var parseUrl = require('url').parse;
|
const parseUrl = require('url').parse;
|
||||||
var qs = require('querystring');
|
const qs = require('querystring');
|
||||||
var AgentKeepAlive = require('agentkeepalive');
|
const AgentKeepAlive = require('agentkeepalive');
|
||||||
var ConnectionAbstract = require('../connection');
|
const ConnectionAbstract = require('../connection');
|
||||||
var zlib = require('zlib');
|
const zlib = require('zlib');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connector used to talk to an elasticsearch node via HTTP
|
* Connector used to talk to an elasticsearch node via HTTP
|
||||||
@ -51,9 +51,9 @@ _.inherits(HttpConnector, ConnectionAbstract);
|
|||||||
|
|
||||||
HttpConnector.prototype.onStatusSet = _.handler(function (status) {
|
HttpConnector.prototype.onStatusSet = _.handler(function (status) {
|
||||||
if (status === 'closed') {
|
if (status === 'closed') {
|
||||||
var agent = this.agent;
|
const agent = this.agent;
|
||||||
var toRemove = [];
|
const toRemove = [];
|
||||||
var collectSockets = function (sockets, host) {
|
const collectSockets = function (sockets, host) {
|
||||||
_.each(sockets, function (s) {
|
_.each(sockets, function (s) {
|
||||||
if (s) toRemove.push([host, s]);
|
if (s) toRemove.push([host, s]);
|
||||||
});
|
});
|
||||||
@ -65,7 +65,7 @@ HttpConnector.prototype.onStatusSet = _.handler(function (status) {
|
|||||||
_.each(agent.sockets, collectSockets);
|
_.each(agent.sockets, collectSockets);
|
||||||
_.each(agent.freeSockets, collectSockets);
|
_.each(agent.freeSockets, collectSockets);
|
||||||
_.each(toRemove, function (args) {
|
_.each(toRemove, function (args) {
|
||||||
var host = args[0], socket = args[1];
|
let host = args[0], socket = args[1];
|
||||||
agent.removeSocket(socket, parseUrl(host));
|
agent.removeSocket(socket, parseUrl(host));
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
});
|
});
|
||||||
@ -73,7 +73,7 @@ HttpConnector.prototype.onStatusSet = _.handler(function (status) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
HttpConnector.prototype.createAgent = function (config) {
|
HttpConnector.prototype.createAgent = function (config) {
|
||||||
var Agent = this.hand.Agent; // the class
|
let Agent = this.hand.Agent; // the class
|
||||||
|
|
||||||
if (config.forever) {
|
if (config.forever) {
|
||||||
config.keepAlive = config.forever;
|
config.keepAlive = config.forever;
|
||||||
@ -88,7 +88,7 @@ HttpConnector.prototype.createAgent = function (config) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
HttpConnector.prototype.makeAgentConfig = function (config) {
|
HttpConnector.prototype.makeAgentConfig = function (config) {
|
||||||
var agentConfig = {
|
const agentConfig = {
|
||||||
keepAlive: config.keepAlive,
|
keepAlive: config.keepAlive,
|
||||||
keepAliveMsecs: config.keepAliveInterval,
|
keepAliveMsecs: config.keepAliveInterval,
|
||||||
maxSockets: config.maxSockets,
|
maxSockets: config.maxSockets,
|
||||||
@ -105,9 +105,9 @@ HttpConnector.prototype.makeAgentConfig = function (config) {
|
|||||||
|
|
||||||
HttpConnector.prototype.makeReqParams = function (params) {
|
HttpConnector.prototype.makeReqParams = function (params) {
|
||||||
params = params || {};
|
params = params || {};
|
||||||
var host = this.host;
|
const host = this.host;
|
||||||
|
|
||||||
var reqParams = {
|
const reqParams = {
|
||||||
method: params.method || 'GET',
|
method: params.method || 'GET',
|
||||||
protocol: host.protocol + ':',
|
protocol: host.protocol + ':',
|
||||||
hostname: host.host,
|
hostname: host.host,
|
||||||
@ -121,7 +121,7 @@ HttpConnector.prototype.makeReqParams = function (params) {
|
|||||||
reqParams.path = '/';
|
reqParams.path = '/';
|
||||||
}
|
}
|
||||||
|
|
||||||
var query = host.getQuery(params.query);
|
const query = host.getQuery(params.query);
|
||||||
if (query) {
|
if (query) {
|
||||||
reqParams.path = reqParams.path + '?' + qs.stringify(query);
|
reqParams.path = reqParams.path + '?' + qs.stringify(query);
|
||||||
}
|
}
|
||||||
@ -130,19 +130,19 @@ HttpConnector.prototype.makeReqParams = function (params) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
HttpConnector.prototype.request = function (params, cb) {
|
HttpConnector.prototype.request = function (params, cb) {
|
||||||
var incoming;
|
let incoming;
|
||||||
var timeoutId;
|
let timeoutId;
|
||||||
var request;
|
let request;
|
||||||
var status = 0;
|
let status = 0;
|
||||||
var headers = {};
|
let headers = {};
|
||||||
var log = this.log;
|
const log = this.log;
|
||||||
var response;
|
let response;
|
||||||
|
|
||||||
var reqParams = this.makeReqParams(params);
|
const reqParams = this.makeReqParams(params);
|
||||||
|
|
||||||
// general clean-up procedure to run after the request
|
// general clean-up procedure to run after the request
|
||||||
// completes, has an error, or is aborted.
|
// completes, has an error, or is aborted.
|
||||||
var cleanUp = _.bind(function (err) {
|
const cleanUp = _.bind(function (err) {
|
||||||
clearTimeout(timeoutId);
|
clearTimeout(timeoutId);
|
||||||
|
|
||||||
request && request.removeAllListeners();
|
request && request.removeAllListeners();
|
||||||
@ -166,7 +166,7 @@ HttpConnector.prototype.request = function (params, cb) {
|
|||||||
headers = incoming.headers;
|
headers = incoming.headers;
|
||||||
response = '';
|
response = '';
|
||||||
|
|
||||||
var encoding = (headers['content-encoding'] || '').toLowerCase();
|
const encoding = (headers['content-encoding'] || '').toLowerCase();
|
||||||
if (encoding === 'gzip' || encoding === 'deflate') {
|
if (encoding === 'gzip' || encoding === 'deflate') {
|
||||||
incoming = incoming.pipe(zlib.createUnzip());
|
incoming = incoming.pipe(zlib.createUnzip());
|
||||||
}
|
}
|
||||||
|
|||||||
8
src/lib/connectors/jquery.js
vendored
8
src/lib/connectors/jquery.js
vendored
@ -7,9 +7,9 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = JqueryConnector;
|
module.exports = JqueryConnector;
|
||||||
|
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
var ConnectionAbstract = require('../connection');
|
const ConnectionAbstract = require('../connection');
|
||||||
var ConnectionFault = require('../errors').ConnectionFault;
|
const ConnectionFault = require('../errors').ConnectionFault;
|
||||||
|
|
||||||
function JqueryConnector(host, config) {
|
function JqueryConnector(host, config) {
|
||||||
ConnectionAbstract.call(this, host, config);
|
ConnectionAbstract.call(this, host, config);
|
||||||
@ -17,7 +17,7 @@ function JqueryConnector(host, config) {
|
|||||||
_.inherits(JqueryConnector, ConnectionAbstract);
|
_.inherits(JqueryConnector, ConnectionAbstract);
|
||||||
|
|
||||||
JqueryConnector.prototype.request = function (params, cb) {
|
JqueryConnector.prototype.request = function (params, cb) {
|
||||||
var ajax = {
|
const ajax = {
|
||||||
url: this.host.makeUrl(params),
|
url: this.host.makeUrl(params),
|
||||||
data: params.body,
|
data: params.body,
|
||||||
type: params.method,
|
type: params.method,
|
||||||
|
|||||||
@ -7,10 +7,10 @@ module.exports = XhrConnector;
|
|||||||
|
|
||||||
/* jshint browser:true */
|
/* jshint browser:true */
|
||||||
|
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
var ConnectionAbstract = require('../connection');
|
const ConnectionAbstract = require('../connection');
|
||||||
var ConnectionFault = require('../errors').ConnectionFault;
|
const ConnectionFault = require('../errors').ConnectionFault;
|
||||||
var asyncDefault = !(navigator && /PhantomJS/i.test(navigator.userAgent));
|
const asyncDefault = !(navigator && /PhantomJS/i.test(navigator.userAgent));
|
||||||
|
|
||||||
function XhrConnector(host, config) {
|
function XhrConnector(host, config) {
|
||||||
ConnectionAbstract.call(this, host, config);
|
ConnectionAbstract.call(this, host, config);
|
||||||
@ -21,7 +21,7 @@ _.inherits(XhrConnector, ConnectionAbstract);
|
|||||||
* Simply returns an XHR object cross browser
|
* Simply returns an XHR object cross browser
|
||||||
* @type {Function}
|
* @type {Function}
|
||||||
*/
|
*/
|
||||||
var getXhr = _.noop;
|
let getXhr = _.noop;
|
||||||
|
|
||||||
if (typeof XMLHttpRequest !== 'undefined') {
|
if (typeof XMLHttpRequest !== 'undefined') {
|
||||||
// rewrite the getXhr method to always return the native implementation
|
// rewrite the getXhr method to always return the native implementation
|
||||||
@ -34,7 +34,7 @@ if (typeof XMLHttpRequest !== 'undefined') {
|
|||||||
.map(function (appName) {
|
.map(function (appName) {
|
||||||
/* jshint unused: false */
|
/* jshint unused: false */
|
||||||
try {
|
try {
|
||||||
var test = new window.ActiveXObject(appName); // eslint-disable-line no-unused-vars
|
const test = new window.ActiveXObject(appName); // eslint-disable-line no-unused-vars
|
||||||
return function () {
|
return function () {
|
||||||
return new window.ActiveXObject(appName);
|
return new window.ActiveXObject(appName);
|
||||||
};
|
};
|
||||||
@ -51,19 +51,19 @@ if (!getXhr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
XhrConnector.prototype.request = function (params, cb) {
|
XhrConnector.prototype.request = function (params, cb) {
|
||||||
var xhr = getXhr();
|
const xhr = getXhr();
|
||||||
var timeoutId;
|
let timeoutId;
|
||||||
var host = this.host;
|
const host = this.host;
|
||||||
var log = this.log;
|
const log = this.log;
|
||||||
|
|
||||||
var url = host.makeUrl(params);
|
const url = host.makeUrl(params);
|
||||||
var headers = host.getHeaders(params.headers);
|
const headers = host.getHeaders(params.headers);
|
||||||
var async = params.async === false ? false : asyncDefault;
|
const async = params.async === false ? false : asyncDefault;
|
||||||
|
|
||||||
xhr.open(params.method || 'GET', url, async);
|
xhr.open(params.method || 'GET', url, async);
|
||||||
|
|
||||||
if (headers) {
|
if (headers) {
|
||||||
for (var key in headers) {
|
for (const key in headers) {
|
||||||
if (headers[key] !== void 0) {
|
if (headers[key] !== void 0) {
|
||||||
xhr.setRequestHeader(key, headers[key]);
|
xhr.setRequestHeader(key, headers[key]);
|
||||||
}
|
}
|
||||||
@ -74,7 +74,7 @@ XhrConnector.prototype.request = function (params, cb) {
|
|||||||
if (xhr.readyState === 4) {
|
if (xhr.readyState === 4) {
|
||||||
clearTimeout(timeoutId);
|
clearTimeout(timeoutId);
|
||||||
log.trace(params.method, url, params.body, xhr.responseText, xhr.status);
|
log.trace(params.method, url, params.body, xhr.responseText, xhr.status);
|
||||||
var err = xhr.status ? void 0 : new ConnectionFault(xhr.statusText || 'Request failed to complete.');
|
const err = xhr.status ? void 0 : new ConnectionFault(xhr.statusText || 'Request failed to complete.');
|
||||||
cb(err, xhr.responseText, xhr.status);
|
cb(err, xhr.responseText, xhr.status);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
var _ = require('./utils');
|
const _ = require('./utils');
|
||||||
var errors = module.exports;
|
const errors = module.exports;
|
||||||
|
|
||||||
var canCapture = (typeof Error.captureStackTrace === 'function');
|
const canCapture = (typeof Error.captureStackTrace === 'function');
|
||||||
var canStack = !!(new Error()).stack;
|
const canStack = !!(new Error()).stack;
|
||||||
|
|
||||||
function ErrorAbstract(msg, constructor, metadata) {
|
function ErrorAbstract(msg, constructor, metadata) {
|
||||||
this.message = msg;
|
this.message = msg;
|
||||||
@ -91,7 +91,7 @@ errors.RequestTypeError = function RequestTypeError(feature) {
|
|||||||
};
|
};
|
||||||
_.inherits(errors.RequestTypeError, ErrorAbstract);
|
_.inherits(errors.RequestTypeError, ErrorAbstract);
|
||||||
|
|
||||||
var statusCodes = [
|
const statusCodes = [
|
||||||
[300, 'Multiple Choices'],
|
[300, 'Multiple Choices'],
|
||||||
[301, 'Moved Permanently'],
|
[301, 'Moved Permanently'],
|
||||||
[302, 'Found'],
|
[302, 'Found'],
|
||||||
@ -137,18 +137,18 @@ var statusCodes = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
_.each(statusCodes, function createStatusCodeError(tuple) {
|
_.each(statusCodes, function createStatusCodeError(tuple) {
|
||||||
var status = tuple[0];
|
const status = tuple[0];
|
||||||
var names = tuple[1];
|
const names = tuple[1];
|
||||||
var allNames = [].concat(names, status);
|
let allNames = [].concat(names, status);
|
||||||
var primaryName = allNames[0];
|
const primaryName = allNames[0];
|
||||||
var className = _.studlyCase(primaryName);
|
const className = _.studlyCase(primaryName);
|
||||||
allNames = _.uniq(allNames.concat(className));
|
allNames = _.uniq(allNames.concat(className));
|
||||||
|
|
||||||
function StatusCodeError(msg, metadata) {
|
function StatusCodeError(msg, metadata) {
|
||||||
this.status = status;
|
this.status = status;
|
||||||
this.displayName = className;
|
this.displayName = className;
|
||||||
|
|
||||||
var esErrObject = null;
|
let esErrObject = null;
|
||||||
if (_.isPlainObject(msg)) {
|
if (_.isPlainObject(msg)) {
|
||||||
esErrObject = msg;
|
esErrObject = msg;
|
||||||
msg = null;
|
msg = null;
|
||||||
@ -167,7 +167,7 @@ _.each(statusCodes, function createStatusCodeError(tuple) {
|
|||||||
|
|
||||||
memo += '[' + cause.type + '] ' + cause.reason;
|
memo += '[' + cause.type + '] ' + cause.reason;
|
||||||
|
|
||||||
var extraData = _.omit(cause, ['type', 'reason']);
|
const extraData = _.omit(cause, ['type', 'reason']);
|
||||||
if (_.size(extraData)) {
|
if (_.size(extraData)) {
|
||||||
memo += ', with ' + prettyPrint(extraData);
|
memo += ', with ' + prettyPrint(extraData);
|
||||||
}
|
}
|
||||||
@ -192,20 +192,20 @@ _.each(statusCodes, function createStatusCodeError(tuple) {
|
|||||||
|
|
||||||
|
|
||||||
function prettyPrint(data) {
|
function prettyPrint(data) {
|
||||||
const path = []
|
const path = [];
|
||||||
return (function print(v) {
|
return (function print(v) {
|
||||||
if (typeof v === 'object') {
|
if (typeof v === 'object') {
|
||||||
if (path.indexOf(v) > -1) return '[circular]'
|
if (path.indexOf(v) > -1) return '[circular]';
|
||||||
path.push(v)
|
path.push(v);
|
||||||
try {
|
try {
|
||||||
return '{ ' + _.map(v, function (subv, name) {
|
return '{ ' + _.map(v, function (subv, name) {
|
||||||
return name + '=' + print(subv)
|
return name + '=' + print(subv);
|
||||||
}).join(' & ') + ' }'
|
}).join(' & ') + ' }';
|
||||||
} finally {
|
} finally {
|
||||||
path.pop()
|
path.pop();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return JSON.stringify(v)
|
return JSON.stringify(v);
|
||||||
}
|
}
|
||||||
}(data))
|
}(data));
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,13 +4,13 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = Host;
|
module.exports = Host;
|
||||||
|
|
||||||
var url = require('url');
|
const url = require('url');
|
||||||
var qs = require('querystring');
|
const qs = require('querystring');
|
||||||
var _ = require('./utils');
|
const _ = require('./utils');
|
||||||
|
|
||||||
var startsWithProtocolRE = /^([a-z]+:)?\/\//;
|
const startsWithProtocolRE = /^([a-z]+:)?\/\//;
|
||||||
var defaultProto = 'http:';
|
let defaultProto = 'http:';
|
||||||
var btoa;
|
let btoa;
|
||||||
|
|
||||||
if (typeof window !== 'undefined' && typeof window.location !== 'undefined') {
|
if (typeof window !== 'undefined' && typeof window.location !== 'undefined') {
|
||||||
defaultProto = window.location.protocol;
|
defaultProto = window.location.protocol;
|
||||||
@ -21,13 +21,13 @@ btoa = btoa || function (data) {
|
|||||||
return (new Buffer(data, 'utf8')).toString('base64');
|
return (new Buffer(data, 'utf8')).toString('base64');
|
||||||
};
|
};
|
||||||
|
|
||||||
var urlParseFields = [
|
const urlParseFields = [
|
||||||
'protocol', 'hostname', 'pathname', 'port', 'auth', 'query'
|
'protocol', 'hostname', 'pathname', 'port', 'auth', 'query'
|
||||||
];
|
];
|
||||||
|
|
||||||
var simplify = ['host', 'path'];
|
const simplify = ['host', 'path'];
|
||||||
|
|
||||||
var sslDefaults = {
|
const sslDefaults = {
|
||||||
pfx: null,
|
pfx: null,
|
||||||
key: null,
|
key: null,
|
||||||
passphrase: null,
|
passphrase: null,
|
||||||
@ -61,11 +61,11 @@ function Host(config, globalConfig) {
|
|||||||
this.ssl = _.defaults({}, config.ssl || {}, globalConfig.ssl || {}, sslDefaults);
|
this.ssl = _.defaults({}, config.ssl || {}, globalConfig.ssl || {}, sslDefaults);
|
||||||
|
|
||||||
if (typeof config === 'string') {
|
if (typeof config === 'string') {
|
||||||
var firstColon = config.indexOf(':');
|
const firstColon = config.indexOf(':');
|
||||||
var firstSlash = config.indexOf('/');
|
const firstSlash = config.indexOf('/');
|
||||||
var noSlash = firstSlash === -1;
|
const noSlash = firstSlash === -1;
|
||||||
var portNoPath = firstColon > -1 && noSlash;
|
const portNoPath = firstColon > -1 && noSlash;
|
||||||
var portWithPath = !portNoPath && firstColon < firstSlash;
|
const portWithPath = !portNoPath && firstColon < firstSlash;
|
||||||
if ((noSlash || portNoPath || portWithPath) && !startsWithProtocolRE.test(config)) {
|
if ((noSlash || portNoPath || portWithPath) && !startsWithProtocolRE.test(config)) {
|
||||||
config = defaultProto + '//' + config;
|
config = defaultProto + '//' + config;
|
||||||
}
|
}
|
||||||
@ -73,7 +73,7 @@ function Host(config, globalConfig) {
|
|||||||
// default logic for the port is to use 9200 for the default. When a string is specified though,
|
// default logic for the port is to use 9200 for the default. When a string is specified though,
|
||||||
// we will use the default from the protocol of the string.
|
// we will use the default from the protocol of the string.
|
||||||
if (!config.port) {
|
if (!config.port) {
|
||||||
var proto = config.protocol || 'http';
|
let proto = config.protocol || 'http';
|
||||||
if (proto.charAt(proto.length - 1) === ':') {
|
if (proto.charAt(proto.length - 1) === ':') {
|
||||||
proto = proto.substring(0, proto.length - 1);
|
proto = proto.substring(0, proto.length - 1);
|
||||||
}
|
}
|
||||||
@ -86,7 +86,7 @@ function Host(config, globalConfig) {
|
|||||||
if (_.isObject(config)) {
|
if (_.isObject(config)) {
|
||||||
// move hostname/portname to host/port semi-intelligently.
|
// move hostname/portname to host/port semi-intelligently.
|
||||||
_.each(simplify, function (to) {
|
_.each(simplify, function (to) {
|
||||||
var from = to + 'name';
|
const from = to + 'name';
|
||||||
if (config[from] && config[to]) {
|
if (config[from] && config[to]) {
|
||||||
if (config[to].indexOf(config[from]) === 0) {
|
if (config[to].indexOf(config[from]) === 0) {
|
||||||
config[to] = config[from];
|
config[to] = config[from];
|
||||||
@ -101,7 +101,7 @@ function Host(config, globalConfig) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!config.auth && globalConfig.httpAuth) {
|
if (!config.auth && globalConfig.httpAuth) {
|
||||||
config.auth = globalConfig.httpAuth
|
config.auth = globalConfig.httpAuth;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (config.auth) {
|
if (config.auth) {
|
||||||
@ -145,14 +145,14 @@ function Host(config, globalConfig) {
|
|||||||
Host.prototype.makeUrl = function (params) {
|
Host.prototype.makeUrl = function (params) {
|
||||||
params = params || {};
|
params = params || {};
|
||||||
// build the port
|
// build the port
|
||||||
var port = '';
|
let port = '';
|
||||||
if (this.port !== Host.defaultPorts[this.protocol]) {
|
if (this.port !== Host.defaultPorts[this.protocol]) {
|
||||||
// add an actual port
|
// add an actual port
|
||||||
port = ':' + this.port;
|
port = ':' + this.port;
|
||||||
}
|
}
|
||||||
|
|
||||||
// build the path
|
// build the path
|
||||||
var path = '' + (this.path || '') + (params.path || '');
|
let path = '' + (this.path || '') + (params.path || '');
|
||||||
|
|
||||||
// if path doesn't start with '/' add it.
|
// if path doesn't start with '/' add it.
|
||||||
if (path.charAt(0) !== '/') {
|
if (path.charAt(0) !== '/') {
|
||||||
@ -160,7 +160,7 @@ Host.prototype.makeUrl = function (params) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// build the query string
|
// build the query string
|
||||||
var query = qs.stringify(this.getQuery(params.query));
|
const query = qs.stringify(this.getQuery(params.query));
|
||||||
|
|
||||||
if (this.host) {
|
if (this.host) {
|
||||||
return this.protocol + '://' + this.host + port + path + (query ? '?' + query : '');
|
return this.protocol + '://' + this.host + port + path + (query ? '?' + query : '');
|
||||||
@ -175,7 +175,7 @@ function objectPropertyGetter(prop, preOverride) {
|
|||||||
overrides = preOverride.call(this, overrides);
|
overrides = preOverride.call(this, overrides);
|
||||||
}
|
}
|
||||||
|
|
||||||
var obj = this[prop];
|
let obj = this[prop];
|
||||||
if (!obj && !overrides) {
|
if (!obj && !overrides) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
var _ = require('./utils');
|
const _ = require('./utils');
|
||||||
var url = require('url');
|
const url = require('url');
|
||||||
var EventEmitter = require('events').EventEmitter;
|
const EventEmitter = require('events').EventEmitter;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log bridge, which is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)
|
* Log bridge, which is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)
|
||||||
@ -21,8 +21,8 @@ function Log(config) {
|
|||||||
config = config || {};
|
config = config || {};
|
||||||
if (!config.log) return;
|
if (!config.log) return;
|
||||||
|
|
||||||
var i;
|
let i;
|
||||||
var outputs;
|
let outputs;
|
||||||
|
|
||||||
if (_.isArrayOfStrings(config.log)) {
|
if (_.isArrayOfStrings(config.log)) {
|
||||||
outputs = [{
|
outputs = [{
|
||||||
@ -158,7 +158,7 @@ Log.parseLevels = function (input) {
|
|||||||
/* fall through */
|
/* fall through */
|
||||||
case 'object':
|
case 'object':
|
||||||
if (_.isArray(input)) {
|
if (_.isArray(input)) {
|
||||||
var valid = _.intersection(input, Log.levels);
|
const valid = _.intersection(input, Log.levels);
|
||||||
if (valid.length === input.length) {
|
if (valid.length === input.length) {
|
||||||
return valid;
|
return valid;
|
||||||
}
|
}
|
||||||
@ -209,7 +209,7 @@ Log.prototype.addOutput = function (config) {
|
|||||||
config.levels = Log.parseLevels(config.levels || config.level || 'warning');
|
config.levels = Log.parseLevels(config.levels || config.level || 'warning');
|
||||||
delete config.level;
|
delete config.level;
|
||||||
|
|
||||||
var Logger = _.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio');
|
const Logger = _.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio');
|
||||||
return new Logger(this, config);
|
return new Logger(this, config);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
var _ = require('./utils');
|
const _ = require('./utils');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Abstract class providing common functionality to loggers
|
* Abstract class providing common functionality to loggers
|
||||||
@ -27,7 +27,7 @@ function padNumToTen(n) {
|
|||||||
* @return {String} - Timestamp in ISO 8601 UTC
|
* @return {String} - Timestamp in ISO 8601 UTC
|
||||||
*/
|
*/
|
||||||
LoggerAbstract.prototype.timestamp = function () {
|
LoggerAbstract.prototype.timestamp = function () {
|
||||||
var d = new Date();
|
const d = new Date();
|
||||||
return d.getUTCFullYear() + '-' +
|
return d.getUTCFullYear() + '-' +
|
||||||
padNumToTen(d.getUTCMonth() + 1) + '-' +
|
padNumToTen(d.getUTCMonth() + 1) + '-' +
|
||||||
padNumToTen(d.getUTCDate()) + 'T' +
|
padNumToTen(d.getUTCDate()) + 'T' +
|
||||||
@ -37,7 +37,7 @@ LoggerAbstract.prototype.timestamp = function () {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function indent(text, spaces) {
|
function indent(text, spaces) {
|
||||||
var space = _.repeat(' ', spaces || 2);
|
const space = _.repeat(' ', spaces || 2);
|
||||||
return (text || '').split(/\r?\n/).map(function (line) {
|
return (text || '').split(/\r?\n/).map(function (line) {
|
||||||
return space + line;
|
return space + line;
|
||||||
}).join('\n');
|
}).join('\n');
|
||||||
@ -65,7 +65,7 @@ LoggerAbstract.prototype.setupListeners = function (levels) {
|
|||||||
this.listeningLevels = [];
|
this.listeningLevels = [];
|
||||||
|
|
||||||
_.each(levels, _.bind(function (level) {
|
_.each(levels, _.bind(function (level) {
|
||||||
var fnName = 'on' + _.ucfirst(level);
|
const fnName = 'on' + _.ucfirst(level);
|
||||||
if (this.bound[fnName]) {
|
if (this.bound[fnName]) {
|
||||||
this.listeningLevels.push(level);
|
this.listeningLevels.push(level);
|
||||||
this.log.on(level, this.bound[fnName]);
|
this.log.on(level, this.bound[fnName]);
|
||||||
|
|||||||
@ -12,8 +12,8 @@
|
|||||||
|
|
||||||
module.exports = Console;
|
module.exports = Console;
|
||||||
|
|
||||||
var LoggerAbstract = require('../logger');
|
const LoggerAbstract = require('../logger');
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
|
|
||||||
function Console(log, config) {
|
function Console(log, config) {
|
||||||
LoggerAbstract.call(this, log, config);
|
LoggerAbstract.call(this, log, config);
|
||||||
@ -48,7 +48,7 @@ Console.prototype.write = function (label, message, to) {
|
|||||||
* @return {undefined}
|
* @return {undefined}
|
||||||
*/
|
*/
|
||||||
Console.prototype.onError = _.handler(function (e) {
|
Console.prototype.onError = _.handler(function (e) {
|
||||||
var to = console.error ? 'error' : 'log';
|
const to = console.error ? 'error' : 'log';
|
||||||
this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack || e.message, to);
|
this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack || e.message, to);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -11,9 +11,9 @@
|
|||||||
|
|
||||||
module.exports = File;
|
module.exports = File;
|
||||||
|
|
||||||
var StreamLogger = require('./stream');
|
const StreamLogger = require('./stream');
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
|
|
||||||
function File(log, config) {
|
function File(log, config) {
|
||||||
config = config || {};
|
config = config || {};
|
||||||
@ -32,7 +32,7 @@ function File(log, config) {
|
|||||||
_.inherits(File, StreamLogger);
|
_.inherits(File, StreamLogger);
|
||||||
|
|
||||||
File.prototype.onProcessExit = _.handler(function () {
|
File.prototype.onProcessExit = _.handler(function () {
|
||||||
var toWrite = _.getUnwrittenFromStream(this.stream);
|
const toWrite = _.getUnwrittenFromStream(this.stream);
|
||||||
if (toWrite) {
|
if (toWrite) {
|
||||||
fs.appendFileSync(this.path, toWrite);
|
fs.appendFileSync(this.path, toWrite);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -12,14 +12,14 @@
|
|||||||
|
|
||||||
module.exports = Stdio;
|
module.exports = Stdio;
|
||||||
|
|
||||||
var chalk = require('chalk');
|
const chalk = require('chalk');
|
||||||
// let the user define if they want color in the client config.
|
// let the user define if they want color in the client config.
|
||||||
chalk.enabled = true;
|
chalk.enabled = true;
|
||||||
|
|
||||||
var LoggerAbstract = require('../logger');
|
const LoggerAbstract = require('../logger');
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
|
|
||||||
var defaultColors = {
|
const defaultColors = {
|
||||||
error: chalk.red.bold,
|
error: chalk.red.bold,
|
||||||
warning: chalk.yellow.bold,
|
warning: chalk.yellow.bold,
|
||||||
info: chalk.cyan.bold,
|
info: chalk.cyan.bold,
|
||||||
|
|||||||
@ -12,8 +12,8 @@
|
|||||||
|
|
||||||
module.exports = Stream;
|
module.exports = Stream;
|
||||||
|
|
||||||
var LoggerAbstract = require('../logger');
|
const LoggerAbstract = require('../logger');
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
|
|
||||||
function Stream(log, config) {
|
function Stream(log, config) {
|
||||||
LoggerAbstract.call(this, log, config);
|
LoggerAbstract.call(this, log, config);
|
||||||
@ -36,7 +36,7 @@ Stream.prototype.cleanUpListeners = _.handler(function () {
|
|||||||
// flush the write buffer to stderr synchronously
|
// flush the write buffer to stderr synchronously
|
||||||
Stream.prototype.onProcessExit = _.handler(function () {
|
Stream.prototype.onProcessExit = _.handler(function () {
|
||||||
// process is dying, lets manually flush the buffer synchronously to stderr.
|
// process is dying, lets manually flush the buffer synchronously to stderr.
|
||||||
var unwritten = _.getUnwrittenFromStream(this.stream);
|
const unwritten = _.getUnwrittenFromStream(this.stream);
|
||||||
if (unwritten) {
|
if (unwritten) {
|
||||||
console.error('Log stream did not get to finish writing. Flushing to stderr');
|
console.error('Log stream did not get to finish writing. Flushing to stderr');
|
||||||
console.error(unwritten);
|
console.error(unwritten);
|
||||||
|
|||||||
@ -12,10 +12,10 @@
|
|||||||
|
|
||||||
module.exports = Tracer;
|
module.exports = Tracer;
|
||||||
|
|
||||||
var StreamLogger = require('./stream');
|
const StreamLogger = require('./stream');
|
||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
var url = require('url');
|
const url = require('url');
|
||||||
|
|
||||||
function Tracer(log, config) {
|
function Tracer(log, config) {
|
||||||
if (config.path === false) {
|
if (config.path === false) {
|
||||||
@ -31,22 +31,22 @@ function Tracer(log, config) {
|
|||||||
}
|
}
|
||||||
_.inherits(Tracer, StreamLogger);
|
_.inherits(Tracer, StreamLogger);
|
||||||
|
|
||||||
var usefulUrlFields = ['protocol', 'slashes', 'port', 'hostname', 'pathname', 'query'];
|
const usefulUrlFields = ['protocol', 'slashes', 'port', 'hostname', 'pathname', 'query'];
|
||||||
|
|
||||||
Tracer.prototype._formatTraceMessage = function (req) {
|
Tracer.prototype._formatTraceMessage = function (req) {
|
||||||
var reqUrl = _.pick(url.parse(req.url, true, false), usefulUrlFields);
|
const reqUrl = _.pick(url.parse(req.url, true, false), usefulUrlFields);
|
||||||
|
|
||||||
var originalHost = url.format(_.pick(reqUrl, 'protocol', 'hostname', 'port'));
|
const originalHost = url.format(_.pick(reqUrl, 'protocol', 'hostname', 'port'));
|
||||||
|
|
||||||
reqUrl.port = this.curlPort;
|
reqUrl.port = this.curlPort;
|
||||||
reqUrl.hostname = this.curlHost;
|
reqUrl.hostname = this.curlHost;
|
||||||
reqUrl.query = _.defaults(reqUrl.query || {}, { pretty: true });
|
reqUrl.query = _.defaults(reqUrl.query || {}, { pretty: true });
|
||||||
|
|
||||||
/* jshint quotmark: double */
|
/* jshint quotmark: double */
|
||||||
var curlCall =
|
const curlCall =
|
||||||
'# ' + originalHost + '\n' +
|
'# ' + originalHost + '\n' +
|
||||||
"curl '" + url.format(reqUrl).replace(/'/g, "\\'") + "' -X" + req.method.toUpperCase() +
|
'curl \'' + url.format(reqUrl).replace(/'/g, '\\\'') + '\' -X' + req.method.toUpperCase() +
|
||||||
(req.body ? " -d '" + this._prettyJson(req.body) + "'" : '');
|
(req.body ? ' -d \'' + this._prettyJson(req.body) + '\'' : '');
|
||||||
/* jshint quotmark: single */
|
/* jshint quotmark: single */
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -62,7 +62,7 @@ function comment(str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Tracer.prototype.write = function (label, msg) {
|
Tracer.prototype.write = function (label, msg) {
|
||||||
var lead = comment(label + ': ' + this.timestamp()) + '\n';
|
const lead = comment(label + ': ' + this.timestamp()) + '\n';
|
||||||
if (typeof msg === 'string') {
|
if (typeof msg === 'string') {
|
||||||
this.stream.write(lead + comment(msg) + '\n\n', 'utf8');
|
this.stream.write(lead + comment(msg) + '\n\n', 'utf8');
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@ -1,14 +1,14 @@
|
|||||||
var _ = require('./utils');
|
const _ = require('./utils');
|
||||||
|
|
||||||
var extractHostPartsRE1x = /\[(?:(.*)\/)?(.+?):(\d+)\]/;
|
const extractHostPartsRE1x = /\[(?:(.*)\/)?(.+?):(\d+)\]/;
|
||||||
|
|
||||||
function makeNodeParser(hostProp) {
|
function makeNodeParser(hostProp) {
|
||||||
return function (nodes) {
|
return function (nodes) {
|
||||||
return _.transform(nodes, function (hosts, node, id) {
|
return _.transform(nodes, function (hosts, node, id) {
|
||||||
var address = _.get(node, hostProp)
|
let address = _.get(node, hostProp);
|
||||||
if (!address) return;
|
if (!address) return;
|
||||||
|
|
||||||
var host = {
|
const host = {
|
||||||
host: undefined,
|
host: undefined,
|
||||||
port: undefined,
|
port: undefined,
|
||||||
_meta: {
|
_meta: {
|
||||||
@ -18,13 +18,13 @@ function makeNodeParser(hostProp) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var malformedError = new Error(
|
const malformedError = new Error(
|
||||||
'Malformed ' + hostProp + '.' +
|
'Malformed ' + hostProp + '.' +
|
||||||
' Got ' + JSON.stringify(address) +
|
' Got ' + JSON.stringify(address) +
|
||||||
' and expected it to match "{hostname?}/{ip}:{port}".'
|
' and expected it to match "{hostname?}/{ip}:{port}".'
|
||||||
);
|
);
|
||||||
|
|
||||||
var matches1x = extractHostPartsRE1x.exec(address);
|
const matches1x = extractHostPartsRE1x.exec(address);
|
||||||
if (matches1x) {
|
if (matches1x) {
|
||||||
host.host = matches1x[1] || matches1x[2];
|
host.host = matches1x[1] || matches1x[2];
|
||||||
host.port = parseInt(matches1x[3], 10);
|
host.port = parseInt(matches1x[3], 10);
|
||||||
@ -33,7 +33,7 @@ function makeNodeParser(hostProp) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (address.indexOf('/') > -1) {
|
if (address.indexOf('/') > -1) {
|
||||||
var withHostParts = address.split('/');
|
const withHostParts = address.split('/');
|
||||||
if (withHostParts.length !== 2) throw malformedError;
|
if (withHostParts.length !== 2) throw malformedError;
|
||||||
|
|
||||||
host.host = withHostParts.shift();
|
host.host = withHostParts.shift();
|
||||||
@ -44,7 +44,7 @@ function makeNodeParser(hostProp) {
|
|||||||
throw malformedError;
|
throw malformedError;
|
||||||
}
|
}
|
||||||
|
|
||||||
var addressParts = address.split(':');
|
const addressParts = address.split(':');
|
||||||
if (addressParts.length !== 2) {
|
if (addressParts.length !== 2) {
|
||||||
throw malformedError;
|
throw malformedError;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,7 +7,7 @@
|
|||||||
* @return {Connection} - The selected connection
|
* @return {Connection} - The selected connection
|
||||||
*/
|
*/
|
||||||
module.exports = function (connections) {
|
module.exports = function (connections) {
|
||||||
var connection = connections[0];
|
const connection = connections[0];
|
||||||
connections.push(connections.shift());
|
connections.push(connections.shift());
|
||||||
return connection;
|
return connection;
|
||||||
};
|
};
|
||||||
|
|||||||
4
src/lib/serializers/angular.js
vendored
4
src/lib/serializers/angular.js
vendored
@ -1,6 +1,6 @@
|
|||||||
/* global angular */
|
/* global angular */
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
var JsonSerializer = require('../serializers/json');
|
const JsonSerializer = require('../serializers/json');
|
||||||
|
|
||||||
function AngularSerializer() {}
|
function AngularSerializer() {}
|
||||||
_.inherits(AngularSerializer, JsonSerializer);
|
_.inherits(AngularSerializer, JsonSerializer);
|
||||||
|
|||||||
@ -4,7 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = Json;
|
module.exports = Json;
|
||||||
|
|
||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
|
|
||||||
function Json() {}
|
function Json() {}
|
||||||
|
|
||||||
@ -44,7 +44,7 @@ Json.prototype.deserialize = function (str) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
Json.prototype.bulkBody = function (val) {
|
Json.prototype.bulkBody = function (val) {
|
||||||
var body = '', i;
|
let body = '', i;
|
||||||
|
|
||||||
if (_.isArray(val)) {
|
if (_.isArray(val)) {
|
||||||
for (i = 0; i < val.length; i++) {
|
for (i = 0; i < val.length; i++) {
|
||||||
|
|||||||
@ -4,25 +4,25 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = Transport;
|
module.exports = Transport;
|
||||||
|
|
||||||
var _ = require('./utils');
|
const _ = require('./utils');
|
||||||
var errors = require('./errors');
|
const errors = require('./errors');
|
||||||
var Host = require('./host');
|
const Host = require('./host');
|
||||||
var patchSniffOnConnectionFault = require('./transport/sniff_on_connection_fault');
|
const patchSniffOnConnectionFault = require('./transport/sniff_on_connection_fault');
|
||||||
var findCommonProtocol = require('./transport/find_common_protocol');
|
const findCommonProtocol = require('./transport/find_common_protocol');
|
||||||
|
|
||||||
function Transport(config) {
|
function Transport(config) {
|
||||||
var self = this;
|
const self = this;
|
||||||
config = self._config = config || {};
|
config = self._config = config || {};
|
||||||
|
|
||||||
var LogClass = (typeof config.log === 'function') ? config.log : require('./log');
|
const LogClass = (typeof config.log === 'function') ? config.log : require('./log');
|
||||||
config.log = self.log = new LogClass(config);
|
config.log = self.log = new LogClass(config);
|
||||||
|
|
||||||
// setup the connection pool
|
// setup the connection pool
|
||||||
var ConnectionPool = _.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main');
|
const ConnectionPool = _.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main');
|
||||||
self.connectionPool = new ConnectionPool(config);
|
self.connectionPool = new ConnectionPool(config);
|
||||||
|
|
||||||
// setup the serializer
|
// setup the serializer
|
||||||
var Serializer = _.funcEnum(config, 'serializer', Transport.serializers, 'json');
|
const Serializer = _.funcEnum(config, 'serializer', Transport.serializers, 'json');
|
||||||
self.serializer = new Serializer(config);
|
self.serializer = new Serializer(config);
|
||||||
|
|
||||||
// setup the nodesToHostCallback
|
// setup the nodesToHostCallback
|
||||||
@ -42,14 +42,14 @@ function Transport(config) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// randomizeHosts option
|
// randomizeHosts option
|
||||||
var randomizeHosts = config.hasOwnProperty('randomizeHosts') ? !!config.randomizeHosts : true;
|
const randomizeHosts = config.hasOwnProperty('randomizeHosts') ? !!config.randomizeHosts : true;
|
||||||
|
|
||||||
if (config.host) {
|
if (config.host) {
|
||||||
config.hosts = config.host;
|
config.hosts = config.host;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (config.hosts) {
|
if (config.hosts) {
|
||||||
var hostsConfig = _.createArray(config.hosts, function (val) {
|
let hostsConfig = _.createArray(config.hosts, function (val) {
|
||||||
if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) {
|
if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) {
|
||||||
return val;
|
return val;
|
||||||
}
|
}
|
||||||
@ -104,10 +104,10 @@ Transport.prototype.defer = function () {
|
|||||||
throw new Error(
|
throw new Error(
|
||||||
'No Promise implementation found. In order for elasticsearch-js to create promises ' +
|
'No Promise implementation found. In order for elasticsearch-js to create promises ' +
|
||||||
'either specify the `defer` configuration or include a global Promise shim'
|
'either specify the `defer` configuration or include a global Promise shim'
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
var defer = {};
|
const defer = {};
|
||||||
defer.promise = new Promise(function (resolve, reject) {
|
defer.promise = new Promise(function (resolve, reject) {
|
||||||
defer.resolve = resolve;
|
defer.resolve = resolve;
|
||||||
defer.reject = reject;
|
defer.reject = reject;
|
||||||
@ -133,19 +133,19 @@ Transport.prototype.defer = function () {
|
|||||||
* @param {Function} cb - A function to call back with (error, responseBody, responseStatus)
|
* @param {Function} cb - A function to call back with (error, responseBody, responseStatus)
|
||||||
*/
|
*/
|
||||||
Transport.prototype.request = function (params, cb) {
|
Transport.prototype.request = function (params, cb) {
|
||||||
var self = this;
|
const self = this;
|
||||||
var remainingRetries = this.maxRetries;
|
let remainingRetries = this.maxRetries;
|
||||||
var requestTimeout = this.requestTimeout;
|
let requestTimeout = this.requestTimeout;
|
||||||
|
|
||||||
var connection; // set in sendReqWithConnection
|
let connection; // set in sendReqWithConnection
|
||||||
var aborted = false; // several connector will respond with an error when the request is aborted
|
let aborted = false; // several connector will respond with an error when the request is aborted
|
||||||
var requestAborter; // an abort function, returned by connection#request()
|
let requestAborter; // an abort function, returned by connection#request()
|
||||||
var requestTimeoutId; // the id of the ^timeout
|
let requestTimeoutId; // the id of the ^timeout
|
||||||
var ret; // the object returned to the user, might be a promise
|
let ret; // the object returned to the user, might be a promise
|
||||||
var defer; // the defer object, will be set when we are using promises.
|
let defer; // the defer object, will be set when we are using promises.
|
||||||
|
|
||||||
var body = params.body;
|
let body = params.body;
|
||||||
var headers = !params.headers ? {} : _.transform(params.headers, function (headers, val, name) {
|
const headers = !params.headers ? {} : _.transform(params.headers, function (headers, val, name) {
|
||||||
headers[String(name).toLowerCase()] = val;
|
headers[String(name).toLowerCase()] = val;
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -173,8 +173,8 @@ Transport.prototype.request = function (params, cb) {
|
|||||||
|
|
||||||
// serialize the body
|
// serialize the body
|
||||||
if (body) {
|
if (body) {
|
||||||
var serializer = self.serializer;
|
const serializer = self.serializer;
|
||||||
var serializeFn = serializer[params.bulkBody ? 'bulkBody' : 'serialize'];
|
const serializeFn = serializer[params.bulkBody ? 'bulkBody' : 'serialize'];
|
||||||
|
|
||||||
body = serializeFn.call(serializer, body);
|
body = serializeFn.call(serializer, body);
|
||||||
if (!headers['content-type']) {
|
if (!headers['content-type']) {
|
||||||
@ -230,7 +230,7 @@ Transport.prototype.request = function (params, cb) {
|
|||||||
if (err) {
|
if (err) {
|
||||||
connection.setStatus('dead');
|
connection.setStatus('dead');
|
||||||
|
|
||||||
var errMsg = err.message || '';
|
let errMsg = err.message || '';
|
||||||
|
|
||||||
errMsg =
|
errMsg =
|
||||||
'\n' +
|
'\n' +
|
||||||
@ -261,8 +261,8 @@ Transport.prototype.request = function (params, cb) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self._timeout(requestTimeoutId);
|
self._timeout(requestTimeoutId);
|
||||||
var parsedBody;
|
let parsedBody;
|
||||||
var isJson = !headers || (headers['content-type'] && ~headers['content-type'].indexOf('application/json'));
|
const isJson = !headers || (headers['content-type'] && ~headers['content-type'].indexOf('application/json'));
|
||||||
|
|
||||||
if (!err && body) {
|
if (!err && body) {
|
||||||
if (isJson) {
|
if (isJson) {
|
||||||
@ -283,7 +283,7 @@ Transport.prototype.request = function (params, cb) {
|
|||||||
&& (!params.ignore || !_.include(params.ignore, status))
|
&& (!params.ignore || !_.include(params.ignore, status))
|
||||||
) {
|
) {
|
||||||
|
|
||||||
var errorMetadata = _.pick(params.req, ['path', 'query', 'body']);
|
const errorMetadata = _.pick(params.req, ['path', 'query', 'body']);
|
||||||
errorMetadata.statusCode = status;
|
errorMetadata.statusCode = status;
|
||||||
errorMetadata.response = body;
|
errorMetadata.response = body;
|
||||||
|
|
||||||
@ -356,8 +356,8 @@ Transport.prototype.request = function (params, cb) {
|
|||||||
Transport.prototype._timeout = function (cb, delay) {
|
Transport.prototype._timeout = function (cb, delay) {
|
||||||
if (this.closed) return;
|
if (this.closed) return;
|
||||||
|
|
||||||
var id;
|
let id;
|
||||||
var timers = this._timers || (this._timers = []);
|
const timers = this._timers || (this._timers = []);
|
||||||
|
|
||||||
if ('function' !== typeof cb) {
|
if ('function' !== typeof cb) {
|
||||||
id = cb;
|
id = cb;
|
||||||
@ -378,7 +378,7 @@ Transport.prototype._timeout = function (cb, delay) {
|
|||||||
if (id) {
|
if (id) {
|
||||||
clearTimeout(id);
|
clearTimeout(id);
|
||||||
|
|
||||||
var i = this._timers.indexOf(id);
|
const i = this._timers.indexOf(id);
|
||||||
if (i !== -1) {
|
if (i !== -1) {
|
||||||
this._timers.splice(i, 1);
|
this._timers.splice(i, 1);
|
||||||
}
|
}
|
||||||
@ -392,10 +392,10 @@ Transport.prototype._timeout = function (cb, delay) {
|
|||||||
* @param {Function} cb - Function to call back once complete
|
* @param {Function} cb - Function to call back once complete
|
||||||
*/
|
*/
|
||||||
Transport.prototype.sniff = function (cb) {
|
Transport.prototype.sniff = function (cb) {
|
||||||
var self = this;
|
const self = this;
|
||||||
var nodesToHostCallback = this.nodesToHostCallback;
|
const nodesToHostCallback = this.nodesToHostCallback;
|
||||||
var log = this.log;
|
const log = this.log;
|
||||||
var sniffedNodesProtocol = this.sniffedNodesProtocol;
|
const sniffedNodesProtocol = this.sniffedNodesProtocol;
|
||||||
|
|
||||||
// make cb a function if it isn't
|
// make cb a function if it isn't
|
||||||
cb = typeof cb === 'function' ? cb : _.noop;
|
cb = typeof cb === 'function' ? cb : _.noop;
|
||||||
@ -414,7 +414,7 @@ Transport.prototype.sniff = function (cb) {
|
|||||||
method: 'GET'
|
method: 'GET'
|
||||||
}, function (err, resp, status) {
|
}, function (err, resp, status) {
|
||||||
if (!err && resp && resp.nodes) {
|
if (!err && resp && resp.nodes) {
|
||||||
var hostsConfigs;
|
let hostsConfigs;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
hostsConfigs = nodesToHostCallback(resp.nodes);
|
hostsConfigs = nodesToHostCallback(resp.nodes);
|
||||||
@ -441,7 +441,7 @@ Transport.prototype.sniff = function (cb) {
|
|||||||
* that will be used to create Host objects.
|
* that will be used to create Host objects.
|
||||||
*/
|
*/
|
||||||
Transport.prototype.setHosts = function (hostsConfigs) {
|
Transport.prototype.setHosts = function (hostsConfigs) {
|
||||||
var globalConfig = this._config;
|
const globalConfig = this._config;
|
||||||
this.connectionPool.setHosts(_.map(hostsConfigs, function (conf) {
|
this.connectionPool.setHosts(_.map(hostsConfigs, function (conf) {
|
||||||
return (conf instanceof Host) ? conf : new Host(conf, globalConfig);
|
return (conf instanceof Host) ? conf : new Host(conf, globalConfig);
|
||||||
}));
|
}));
|
||||||
|
|||||||
@ -1,14 +1,14 @@
|
|||||||
var isEmpty = require('lodash.isempty');
|
const isEmpty = require('lodash.isempty');
|
||||||
|
|
||||||
module.exports = function (hosts) {
|
module.exports = function (hosts) {
|
||||||
if (isEmpty(hosts)) return false;
|
if (isEmpty(hosts)) return false;
|
||||||
|
|
||||||
var commonProtocol = hosts.shift().protocol;
|
const commonProtocol = hosts.shift().protocol;
|
||||||
for (var i = 0; i < hosts.length; i++) {
|
for (let i = 0; i < hosts.length; i++) {
|
||||||
if (commonProtocol !== hosts[i].protocol) {
|
if (commonProtocol !== hosts[i].protocol) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return commonProtocol;
|
return commonProtocol;
|
||||||
}
|
};
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
var _ = require('../utils');
|
const _ = require('../utils');
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -11,9 +11,9 @@ var _ = require('../utils');
|
|||||||
* @return {undefined}
|
* @return {undefined}
|
||||||
*/
|
*/
|
||||||
module.exports = function setupSniffOnConnectionFault(transport) {
|
module.exports = function setupSniffOnConnectionFault(transport) {
|
||||||
var failures = 0;
|
let failures = 0;
|
||||||
var pool = transport.connectionPool;
|
const pool = transport.connectionPool;
|
||||||
var originalOnDied = pool._onConnectionDied;
|
const originalOnDied = pool._onConnectionDied;
|
||||||
|
|
||||||
// do the actual sniff, if the sniff is unable to
|
// do the actual sniff, if the sniff is unable to
|
||||||
// connect to a node this function will be called again by the connectionPool
|
// connect to a node this function will be called again by the connectionPool
|
||||||
@ -24,8 +24,8 @@ module.exports = function setupSniffOnConnectionFault(transport) {
|
|||||||
|
|
||||||
// create a function that will count down to a
|
// create a function that will count down to a
|
||||||
// point n milliseconds into the future
|
// point n milliseconds into the future
|
||||||
var countdownTo = function (ms) {
|
const countdownTo = function (ms) {
|
||||||
var start = _.now();
|
const start = _.now();
|
||||||
return function () {
|
return function () {
|
||||||
return start - ms;
|
return start - ms;
|
||||||
};
|
};
|
||||||
@ -33,12 +33,12 @@ module.exports = function setupSniffOnConnectionFault(transport) {
|
|||||||
|
|
||||||
// overwrite the function, but still call it
|
// overwrite the function, but still call it
|
||||||
pool._onConnectionDied = function (connection, wasAlreadyDead) {
|
pool._onConnectionDied = function (connection, wasAlreadyDead) {
|
||||||
var ret = originalOnDied.call(pool, connection, wasAlreadyDead);
|
const ret = originalOnDied.call(pool, connection, wasAlreadyDead);
|
||||||
|
|
||||||
// clear the failures if this is the first failure we have seen
|
// clear the failures if this is the first failure we have seen
|
||||||
failures = work.timerId ? failures + 1 : 0;
|
failures = work.timerId ? failures + 1 : 0;
|
||||||
|
|
||||||
var ms = pool.calcDeadTimeout(failures, 1000);
|
const ms = pool.calcDeadTimeout(failures, 1000);
|
||||||
|
|
||||||
if (work.timerId && ms < work.timerId && work.countdown()) {
|
if (work.timerId && ms < work.timerId && work.countdown()) {
|
||||||
// clear the timer
|
// clear the timer
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
var path = require('path');
|
const path = require('path');
|
||||||
var nodeUtils = require('util');
|
const nodeUtils = require('util');
|
||||||
var lodash = require('lodash');
|
const lodash = require('lodash');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Custom utils library, basically a modified version of [lodash](http://lodash.com/docs) +
|
* Custom utils library, basically a modified version of [lodash](http://lodash.com/docs) +
|
||||||
@ -10,7 +10,7 @@ var lodash = require('lodash');
|
|||||||
* @class utils
|
* @class utils
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
var _ = lodash.assign({}, lodash, nodeUtils);
|
const _ = lodash.assign({}, lodash, nodeUtils);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Link to [path.join](http://nodejs.org/api/path.html#path_path_join_path1_path2)
|
* Link to [path.join](http://nodejs.org/api/path.html#path_path_join_path1_path2)
|
||||||
@ -67,7 +67,7 @@ _.each([
|
|||||||
'Function',
|
'Function',
|
||||||
'RegExp'
|
'RegExp'
|
||||||
], function (type) {
|
], function (type) {
|
||||||
var check = _['is' + type];
|
const check = _['is' + type];
|
||||||
|
|
||||||
_['isArrayOf' + type + 's'] = function (arr) {
|
_['isArrayOf' + type + 's'] = function (arr) {
|
||||||
// quick shallow check of arrays
|
// quick shallow check of arrays
|
||||||
@ -94,10 +94,10 @@ _.ucfirst = function (word) {
|
|||||||
*/
|
*/
|
||||||
function adjustWordCase(firstWordCap, otherWordsCap, sep) {
|
function adjustWordCase(firstWordCap, otherWordsCap, sep) {
|
||||||
return function (string) {
|
return function (string) {
|
||||||
var i = 0;
|
let i = 0;
|
||||||
var words = [];
|
const words = [];
|
||||||
var word = '';
|
let word = '';
|
||||||
var code, c, upper, lower;
|
let code, c, upper, lower;
|
||||||
|
|
||||||
for (; i < string.length; i++) {
|
for (; i < string.length; i++) {
|
||||||
code = string.charCodeAt(i);
|
code = string.charCodeAt(i);
|
||||||
@ -210,7 +210,7 @@ _.isNumeric = function (val) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// regexp to test for intervals
|
// regexp to test for intervals
|
||||||
var intervalRE = /^(\d+(?:\.\d+)?)(M|w|d|h|m|s|y|ms)$/;
|
const intervalRE = /^(\d+(?:\.\d+)?)(M|w|d|h|m|s|y|ms)$/;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test if a string represents an interval (eg. 1m, 2Y)
|
* Test if a string represents an interval (eg. 1m, 2Y)
|
||||||
@ -315,7 +315,7 @@ _.scheduled = _.handler;
|
|||||||
*/
|
*/
|
||||||
_.makeBoundMethods = function (obj) {
|
_.makeBoundMethods = function (obj) {
|
||||||
obj.bound = {};
|
obj.bound = {};
|
||||||
for (var prop in obj) {
|
for (const prop in obj) {
|
||||||
// dearest maintainer, we want to look through the prototype
|
// dearest maintainer, we want to look through the prototype
|
||||||
if (typeof obj[prop] === 'function' && obj[prop]._provideBound === true) {
|
if (typeof obj[prop] === 'function' && obj[prop]._provideBound === true) {
|
||||||
obj.bound[prop] = _.bind(obj[prop], obj);
|
obj.bound[prop] = _.bind(obj[prop], obj);
|
||||||
@ -332,7 +332,7 @@ _.noop = function () {};
|
|||||||
* @return {Function|undefined} - If a valid option was specified, then the constructor is returned
|
* @return {Function|undefined} - If a valid option was specified, then the constructor is returned
|
||||||
*/
|
*/
|
||||||
_.funcEnum = function (config, name, opts, def) {
|
_.funcEnum = function (config, name, opts, def) {
|
||||||
var val = config[name];
|
const val = config[name];
|
||||||
switch (typeof val) {
|
switch (typeof val) {
|
||||||
case 'undefined':
|
case 'undefined':
|
||||||
return opts[def];
|
return opts[def];
|
||||||
@ -371,9 +371,9 @@ _.funcEnum = function (config, name, opts, def) {
|
|||||||
*/
|
*/
|
||||||
_.createArray = function (input, transform) {
|
_.createArray = function (input, transform) {
|
||||||
transform = typeof transform === 'function' ? transform : _.identity;
|
transform = typeof transform === 'function' ? transform : _.identity;
|
||||||
var output = [];
|
const output = [];
|
||||||
var item;
|
let item;
|
||||||
var i;
|
let i;
|
||||||
|
|
||||||
if (!_.isArray(input)) {
|
if (!_.isArray(input)) {
|
||||||
input = [input];
|
input = [input];
|
||||||
@ -399,11 +399,11 @@ _.createArray = function (input, transform) {
|
|||||||
* @return {string} - the remaining test to be written to the stream
|
* @return {string} - the remaining test to be written to the stream
|
||||||
*/
|
*/
|
||||||
_.getUnwrittenFromStream = function (stream) {
|
_.getUnwrittenFromStream = function (stream) {
|
||||||
var writeBuffer = _.getStreamWriteBuffer(stream);
|
const writeBuffer = _.getStreamWriteBuffer(stream);
|
||||||
if (!writeBuffer) return;
|
if (!writeBuffer) return;
|
||||||
|
|
||||||
// flush the write buffer
|
// flush the write buffer
|
||||||
var out = '';
|
let out = '';
|
||||||
if (!writeBuffer.length) return out;
|
if (!writeBuffer.length) return out;
|
||||||
|
|
||||||
_.each(writeBuffer, function (writeReq) {
|
_.each(writeBuffer, function (writeReq) {
|
||||||
@ -423,7 +423,7 @@ _.getUnwrittenFromStream = function (stream) {
|
|||||||
_.getStreamWriteBuffer = function (stream) {
|
_.getStreamWriteBuffer = function (stream) {
|
||||||
if (!stream || !stream._writableState) return;
|
if (!stream || !stream._writableState) return;
|
||||||
|
|
||||||
var writeState = stream._writableState;
|
const writeState = stream._writableState;
|
||||||
|
|
||||||
if (writeState.getBuffer) {
|
if (writeState.getBuffer) {
|
||||||
return writeState.getBuffer();
|
return writeState.getBuffer();
|
||||||
@ -433,7 +433,7 @@ _.getStreamWriteBuffer = function (stream) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
_.clearWriteStreamBuffer = function (stream) {
|
_.clearWriteStreamBuffer = function (stream) {
|
||||||
var buffer = _.getStreamWriteBuffer(stream);
|
const buffer = _.getStreamWriteBuffer(stream);
|
||||||
return buffer && buffer.splice(0);
|
return buffer && buffer.splice(0);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
16
test/fixtures/keepalive.js
vendored
16
test/fixtures/keepalive.js
vendored
@ -1,10 +1,10 @@
|
|||||||
var clock = require('sinon').useFakeTimers();
|
const clock = require('sinon').useFakeTimers();
|
||||||
var Client = require('../../src/elasticsearch').Client;
|
const Client = require('../../src/elasticsearch').Client;
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var times = require('async').times;
|
const times = require('async').times;
|
||||||
|
|
||||||
process.once('message', function (port) {
|
process.once('message', function (port) {
|
||||||
var es = new Client({
|
const es = new Client({
|
||||||
host: 'http://127.0.0.1:' + port,
|
host: 'http://127.0.0.1:' + port,
|
||||||
log: false
|
log: false
|
||||||
});
|
});
|
||||||
@ -19,8 +19,8 @@ process.once('message', function (port) {
|
|||||||
}, done);
|
}, done);
|
||||||
clock.tick(10);
|
clock.tick(10);
|
||||||
}, function (err) {
|
}, function (err) {
|
||||||
var conns = es.transport.connectionPool._conns;
|
const conns = es.transport.connectionPool._conns;
|
||||||
var sockets = _([].concat(conns.dead, conns.alive))
|
const sockets = _([].concat(conns.dead, conns.alive))
|
||||||
.transform(function (sockets, conn) {
|
.transform(function (sockets, conn) {
|
||||||
sockets.push(_.values(conn.agent.sockets), _.values(conn.agent.freeSockets));
|
sockets.push(_.values(conn.agent.sockets), _.values(conn.agent.freeSockets));
|
||||||
}, [])
|
}, [])
|
||||||
@ -29,7 +29,7 @@ process.once('message', function (port) {
|
|||||||
|
|
||||||
es.close();
|
es.close();
|
||||||
|
|
||||||
var out = {
|
const out = {
|
||||||
socketCount: err || sockets.length,
|
socketCount: err || sockets.length,
|
||||||
remaining: _.filter(sockets, { destroyed: true }).length - sockets.length,
|
remaining: _.filter(sockets, { destroyed: true }).length - sockets.length,
|
||||||
timeouts: _.size(clock.timers) && _.map(clock.timers, 'func').map(String)
|
timeouts: _.size(clock.timers) && _.map(clock.timers, 'func').map(String)
|
||||||
|
|||||||
8
test/fixtures/keepalive_server.js
vendored
8
test/fixtures/keepalive_server.js
vendored
@ -4,13 +4,13 @@
|
|||||||
// which prevent sinon from being able to ensure
|
// which prevent sinon from being able to ensure
|
||||||
// timeouts aren't being left behind
|
// timeouts aren't being left behind
|
||||||
|
|
||||||
var express = require('express');
|
const express = require('express');
|
||||||
var app = express().post('/_search', function (req, res) {
|
const app = express().post('/_search', function (req, res) {
|
||||||
res.json(200, { hits: { hits: [] } });
|
res.json(200, { hits: { hits: [] } });
|
||||||
});
|
});
|
||||||
|
|
||||||
var server = require('http').createServer(app);
|
const server = require('http').createServer(app);
|
||||||
server.listen(function () {
|
server.listen(function () {
|
||||||
var port = server.address().port;
|
const port = server.address().port;
|
||||||
process.connected ? process.send(port) : console.log(port);
|
process.connected ? process.send(port) : console.log(port);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,22 +1,22 @@
|
|||||||
var BROWSER = process.env.browser;
|
const BROWSER = process.env.browser;
|
||||||
var VERBOSE = process.env.VERBOSE;
|
const VERBOSE = process.env.VERBOSE;
|
||||||
var JENKINS = !!process.env.JENKINS_HOME;
|
const JENKINS = !!process.env.JENKINS_HOME;
|
||||||
|
|
||||||
var es;
|
let es;
|
||||||
if (BROWSER) {
|
if (BROWSER) {
|
||||||
es = window.elasticsearch;
|
es = window.elasticsearch;
|
||||||
} else {
|
} else {
|
||||||
es = require('../../../src/elasticsearch');
|
es = require('../../../src/elasticsearch');
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ = require('../../../src/lib/utils');
|
const _ = require('../../../src/lib/utils');
|
||||||
var path = require('path');
|
const path = require('path');
|
||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
var fromRoot = _.bindKey(path, 'join', require('find-root')(__dirname));
|
const fromRoot = _.bindKey(path, 'join', require('find-root')(__dirname));
|
||||||
var Bluebird = require('bluebird');
|
const Bluebird = require('bluebird');
|
||||||
|
|
||||||
// current client
|
// current client
|
||||||
var client = null;
|
let client = null;
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
create: function create(apiVersion, port, host, cb) {
|
create: function create(apiVersion, port, host, cb) {
|
||||||
@ -24,8 +24,8 @@ module.exports = {
|
|||||||
doCreateClient({
|
doCreateClient({
|
||||||
logConfig: null
|
logConfig: null
|
||||||
}, function () {
|
}, function () {
|
||||||
var attemptsRemaining = 60;
|
let attemptsRemaining = 60;
|
||||||
var timeout = 500;
|
const timeout = 500;
|
||||||
|
|
||||||
(function ping() {
|
(function ping() {
|
||||||
client.info({
|
client.info({
|
||||||
@ -59,7 +59,7 @@ module.exports = {
|
|||||||
options = {};
|
options = {};
|
||||||
}
|
}
|
||||||
|
|
||||||
var logConfig = {};
|
let logConfig = {};
|
||||||
if (_.has(options, 'logConfig')) {
|
if (_.has(options, 'logConfig')) {
|
||||||
logConfig = options.logConfig;
|
logConfig = options.logConfig;
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@ -1,18 +1,18 @@
|
|||||||
module.exports = function (branch) {
|
module.exports = function (branch) {
|
||||||
var path = require('path');
|
const path = require('path');
|
||||||
var jsYaml = require('js-yaml');
|
const jsYaml = require('js-yaml');
|
||||||
var YamlFile = require('./yaml_file');
|
const YamlFile = require('./yaml_file');
|
||||||
var root = require('find-root')(__dirname);
|
const root = require('find-root')(__dirname);
|
||||||
var rootReq = function (loc) { return require(path.join(root, loc)); };
|
const rootReq = function (loc) { return require(path.join(root, loc)); };
|
||||||
var _ = rootReq('src/lib/utils');
|
const _ = rootReq('src/lib/utils');
|
||||||
var utils = rootReq('grunt/utils');
|
const utils = rootReq('grunt/utils');
|
||||||
var es = rootReq('src/elasticsearch');
|
const es = rootReq('src/elasticsearch');
|
||||||
var clientManager = require('./client_manager');
|
const clientManager = require('./client_manager');
|
||||||
|
|
||||||
var port = parseInt(process.env.ES_PORT || 9200, 10);
|
const port = parseInt(process.env.ES_PORT || 9200, 10);
|
||||||
var host = process.env.ES_HOST || 'localhost';
|
const host = process.env.ES_HOST || 'localhost';
|
||||||
var _release = branch.match(/^v(\d+\.\d+)\.\d+$/);
|
const _release = branch.match(/^v(\d+\.\d+)\.\d+$/);
|
||||||
var apiVersion = _release ? _release[1] : branch;
|
const apiVersion = _release ? _release[1] : branch;
|
||||||
|
|
||||||
console.log(' branch:', branch);
|
console.log(' branch:', branch);
|
||||||
console.log(' port:', port);
|
console.log(' port:', port);
|
||||||
@ -32,7 +32,7 @@ module.exports = function (branch) {
|
|||||||
return clientManager.get().clearEs();
|
return clientManager.get().clearEs();
|
||||||
});
|
});
|
||||||
|
|
||||||
var files = _.map(require('./yaml_tests_' + _.snakeCase(branch) + '.json'), function (docs, filename) {
|
const files = _.map(require('./yaml_tests_' + _.snakeCase(branch) + '.json'), function (docs, filename) {
|
||||||
return new YamlFile(filename, docs);
|
return new YamlFile(filename, docs);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -9,39 +9,39 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = YamlDoc;
|
module.exports = YamlDoc;
|
||||||
|
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var clientManager = require('./client_manager');
|
const clientManager = require('./client_manager');
|
||||||
var inspect = require('util').inspect;
|
const inspect = require('util').inspect;
|
||||||
|
|
||||||
var implementedFeatures = ['gtelte', 'regex', 'benchmark', 'stash_in_path', 'groovy_scripting'];
|
const implementedFeatures = ['gtelte', 'regex', 'benchmark', 'stash_in_path', 'groovy_scripting'];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The version that ES is running, in comparable string form XXX-XXX-XXX, fetched when needed
|
* The version that ES is running, in comparable string form XXX-XXX-XXX, fetched when needed
|
||||||
* @type {String}
|
* @type {String}
|
||||||
*/
|
*/
|
||||||
var ES_VERSION = null;
|
let ES_VERSION = null;
|
||||||
|
|
||||||
// core expression for finding a version
|
// core expression for finding a version
|
||||||
var versionExp = '((?:\\d+\\.){0,2}\\d+)(?:[\\.\\-]\\w+)?|';
|
const versionExp = '((?:\\d+\\.){0,2}\\d+)(?:[\\.\\-]\\w+)?|';
|
||||||
|
|
||||||
// match all whitespace within a "regexp" match arg
|
// match all whitespace within a "regexp" match arg
|
||||||
var reWhitespaceRE = /\s+/g;
|
const reWhitespaceRE = /\s+/g;
|
||||||
|
|
||||||
// match all comments within a "regexp" match arg
|
// match all comments within a "regexp" match arg
|
||||||
var reCommentsRE = /([\S\s]?)#[^\n]*\n/g;
|
const reCommentsRE = /([\S\s]?)#[^\n]*\n/g;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Regular Expression to extract a version number from a string
|
* Regular Expression to extract a version number from a string
|
||||||
* @type {RegExp}
|
* @type {RegExp}
|
||||||
*/
|
*/
|
||||||
var versionRE = new RegExp('^(?:' + versionExp + ')$');
|
const versionRE = new RegExp('^(?:' + versionExp + ')$');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Regular Expression to extract a version range from a string
|
* Regular Expression to extract a version range from a string
|
||||||
* @type {RegExp}
|
* @type {RegExp}
|
||||||
*/
|
*/
|
||||||
var versionRangeRE = new RegExp('^(?:' + versionExp + ')\\s*\\-\\s*(?:' + versionExp + ')$');
|
const versionRangeRE = new RegExp('^(?:' + versionExp + ')\\s*\\-\\s*(?:' + versionExp + ')$');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetches the client.info, and parses out the version number to a comparable string
|
* Fetches the client.info, and parses out the version number to a comparable string
|
||||||
@ -70,7 +70,7 @@ function versionToComparableString(version, def) {
|
|||||||
return def;
|
return def;
|
||||||
}
|
}
|
||||||
|
|
||||||
var parts = _.map(version.split('.'), function (part) {
|
const parts = _.map(version.split('.'), function (part) {
|
||||||
part = '' + _.parseInt(part);
|
part = '' + _.parseInt(part);
|
||||||
return (new Array(Math.max(4 - part.length, 0))).join('0') + part;
|
return (new Array(Math.max(4 - part.length, 0))).join('0') + part;
|
||||||
});
|
});
|
||||||
@ -106,7 +106,7 @@ function rangeMatchesCurrentVersion(rangeString, done) {
|
|||||||
|
|
||||||
|
|
||||||
function YamlDoc(doc, file) {
|
function YamlDoc(doc, file) {
|
||||||
var self = this;
|
const self = this;
|
||||||
|
|
||||||
self.file = file;
|
self.file = file;
|
||||||
self.description = _.keys(doc).shift();
|
self.description = _.keys(doc).shift();
|
||||||
@ -116,7 +116,7 @@ function YamlDoc(doc, file) {
|
|||||||
// setup the actions, creating a bound and testable method for each
|
// setup the actions, creating a bound and testable method for each
|
||||||
self._actions = _.map(self.flattenTestActions(doc[self.description]), function (action) {
|
self._actions = _.map(self.flattenTestActions(doc[self.description]), function (action) {
|
||||||
// get the method that will do the action
|
// get the method that will do the action
|
||||||
var method = self['do_' + action.name];
|
const method = self['do_' + action.name];
|
||||||
|
|
||||||
// check that it's a function
|
// check that it's a function
|
||||||
expect(method || 'YamlDoc#' + action.name).to.be.a('function');
|
expect(method || 'YamlDoc#' + action.name).to.be.a('function');
|
||||||
@ -175,14 +175,14 @@ function YamlDoc(doc, file) {
|
|||||||
|
|
||||||
YamlDoc.compareRangeToVersion = function (range, version) {
|
YamlDoc.compareRangeToVersion = function (range, version) {
|
||||||
expect(range).to.match(versionRangeRE);
|
expect(range).to.match(versionRangeRE);
|
||||||
var rangeMatch = versionRangeRE.exec(range);
|
const rangeMatch = versionRangeRE.exec(range);
|
||||||
|
|
||||||
expect(version).to.match(versionRE);
|
expect(version).to.match(versionRE);
|
||||||
var versionMatch = versionRE.exec(version);
|
const versionMatch = versionRE.exec(version);
|
||||||
|
|
||||||
var min = versionToComparableString(rangeMatch[1], -Infinity);
|
const min = versionToComparableString(rangeMatch[1], -Infinity);
|
||||||
var max = versionToComparableString(rangeMatch[2], Infinity);
|
const max = versionToComparableString(rangeMatch[2], Infinity);
|
||||||
var comp = versionToComparableString(versionMatch[1], Infinity);
|
const comp = versionToComparableString(versionMatch[1], Infinity);
|
||||||
|
|
||||||
return (min === -Infinity || min <= comp) && (max === Infinity || max >= comp);
|
return (min === -Infinity || min <= comp) && (max === Infinity || max >= comp);
|
||||||
};
|
};
|
||||||
@ -199,7 +199,7 @@ YamlDoc.prototype = {
|
|||||||
flattenTestActions: function (config) {
|
flattenTestActions: function (config) {
|
||||||
// creates [ [ {name:"", args:"" }, ... ], ... ]
|
// creates [ [ {name:"", args:"" }, ... ], ... ]
|
||||||
// from [ {name:args, name:args}, {name:args} ]
|
// from [ {name:args, name:args}, {name:args} ]
|
||||||
var actionSets = _.map(config, function (set) {
|
const actionSets = _.map(config, function (set) {
|
||||||
return _.map(_.toPairs(set), function (pair) {
|
return _.map(_.toPairs(set), function (pair) {
|
||||||
return { name: pair[0], args: pair[1] };
|
return { name: pair[0], args: pair[1] };
|
||||||
});
|
});
|
||||||
@ -219,7 +219,7 @@ YamlDoc.prototype = {
|
|||||||
* @return {undefined}
|
* @return {undefined}
|
||||||
*/
|
*/
|
||||||
each: function (ittr) {
|
each: function (ittr) {
|
||||||
for (var i = 0; i < this._actions.length; i++) {
|
for (let i = 0; i < this._actions.length; i++) {
|
||||||
if (ittr(this._actions[i].testable, this._actions[i].name) === false) {
|
if (ittr(this._actions[i].testable, this._actions[i].name) === false) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@ -249,9 +249,9 @@ YamlDoc.prototype = {
|
|||||||
* @return {*} - The value requested, or undefined if it was not found
|
* @return {*} - The value requested, or undefined if it was not found
|
||||||
*/
|
*/
|
||||||
get: function (path, from) {
|
get: function (path, from) {
|
||||||
var self = this;
|
const self = this;
|
||||||
var log = process.env.LOG_GETS && !from ? console.log.bind(console) : function () {};
|
const log = process.env.LOG_GETS && !from ? console.log.bind(console) : function () {};
|
||||||
var i;
|
let i;
|
||||||
|
|
||||||
if (path === '$body') {
|
if (path === '$body') {
|
||||||
// shortcut, the test just wants the whole body
|
// shortcut, the test just wants the whole body
|
||||||
@ -273,10 +273,10 @@ YamlDoc.prototype = {
|
|||||||
|
|
||||||
log('getting', path, 'from', from);
|
log('getting', path, 'from', from);
|
||||||
|
|
||||||
var steps = _.map(path ? path.replace(/\\\./g, '\uffff').split('.') : [], function (step) {
|
const steps = _.map(path ? path.replace(/\\\./g, '\uffff').split('.') : [], function (step) {
|
||||||
return step.replace(/\uffff/g, '.');
|
return step.replace(/\uffff/g, '.');
|
||||||
});
|
});
|
||||||
var remainingSteps;
|
let remainingSteps;
|
||||||
|
|
||||||
for (i = 0; from != null && i < steps.length; i++) {
|
for (i = 0; from != null && i < steps.length; i++) {
|
||||||
if (from[steps[i]] === void 0) {
|
if (from[steps[i]] === void 0) {
|
||||||
@ -319,8 +319,8 @@ YamlDoc.prototype = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (args.features) {
|
if (args.features) {
|
||||||
var features = Array.isArray(args.features) ? args.features : [args.features];
|
const features = Array.isArray(args.features) ? args.features : [args.features];
|
||||||
var notImplemented = _.difference(features, implementedFeatures);
|
const notImplemented = _.difference(features, implementedFeatures);
|
||||||
|
|
||||||
if (notImplemented.length) {
|
if (notImplemented.length) {
|
||||||
if (this.description === 'setup') {
|
if (this.description === 'setup') {
|
||||||
@ -343,10 +343,10 @@ YamlDoc.prototype = {
|
|||||||
* @return {[type]} [description]
|
* @return {[type]} [description]
|
||||||
*/
|
*/
|
||||||
do_do: function (args, done) {
|
do_do: function (args, done) {
|
||||||
var catcher;
|
let catcher;
|
||||||
|
|
||||||
if (process.env.LOG_DO) {
|
if (process.env.LOG_DO) {
|
||||||
var __done = done;
|
const __done = done;
|
||||||
done = function (err, resp) {
|
done = function (err, resp) {
|
||||||
console.log('doing', clientActionName, 'with', params);
|
console.log('doing', clientActionName, 'with', params);
|
||||||
console.log('got', resp);
|
console.log('got', resp);
|
||||||
@ -388,7 +388,7 @@ YamlDoc.prototype = {
|
|||||||
|
|
||||||
delete args.catch;
|
delete args.catch;
|
||||||
|
|
||||||
var inputParams = {};
|
const inputParams = {};
|
||||||
|
|
||||||
// resolve the headers for a request
|
// resolve the headers for a request
|
||||||
if (args.headers) {
|
if (args.headers) {
|
||||||
@ -396,25 +396,25 @@ YamlDoc.prototype = {
|
|||||||
delete args.headers;
|
delete args.headers;
|
||||||
}
|
}
|
||||||
|
|
||||||
var otherKeys = _.keys(args);
|
const otherKeys = _.keys(args);
|
||||||
var action = otherKeys.shift();
|
const action = otherKeys.shift();
|
||||||
if (otherKeys.length) {
|
if (otherKeys.length) {
|
||||||
return done(new TypeError('Unexpected top-level args to "do": ' + otherKeys.join(', ')));
|
return done(new TypeError('Unexpected top-level args to "do": ' + otherKeys.join(', ')));
|
||||||
}
|
}
|
||||||
|
|
||||||
var client = clientManager.get();
|
const client = clientManager.get();
|
||||||
var clientActionName = _.map(action.split('.'), _.camelCase).join('.');
|
var clientActionName = _.map(action.split('.'), _.camelCase).join('.');
|
||||||
var clientAction = this.get(clientActionName, client);
|
const clientAction = this.get(clientActionName, client);
|
||||||
_.assign(inputParams, args[action]);
|
_.assign(inputParams, args[action]);
|
||||||
|
|
||||||
var params = _.transform(inputParams, _.bind(function (params, val, name) {
|
var params = _.transform(inputParams, _.bind(function (params, val, name) {
|
||||||
var camelName = _.camelCase(name);
|
const camelName = _.camelCase(name);
|
||||||
|
|
||||||
// search through the params and url peices to find this param name
|
// search through the params and url peices to find this param name
|
||||||
var paramName = name;
|
let paramName = name;
|
||||||
var spec = clientAction && clientAction.spec;
|
const spec = clientAction && clientAction.spec;
|
||||||
var knownParam = spec && spec.params && spec.params[camelName];
|
const knownParam = spec && spec.params && spec.params[camelName];
|
||||||
var knownUrlParam = spec && !knownParam && !!_.find(spec.url ? [spec.url] : spec.urls, function (url) {
|
const knownUrlParam = spec && !knownParam && !!_.find(spec.url ? [spec.url] : spec.urls, function (url) {
|
||||||
if ((url.opt && url.opt[camelName]) || (url.req && url.req[camelName])) {
|
if ((url.opt && url.opt[camelName]) || (url.req && url.req[camelName])) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -447,8 +447,8 @@ YamlDoc.prototype = {
|
|||||||
catcher = null;
|
catcher = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var timeoutId;
|
let timeoutId;
|
||||||
var cb = _.bind(function (error, body) {
|
const cb = _.bind(function (error, body) {
|
||||||
this._last_requests_response = body;
|
this._last_requests_response = body;
|
||||||
clearTimeout(timeoutId);
|
clearTimeout(timeoutId);
|
||||||
|
|
||||||
@ -473,7 +473,7 @@ YamlDoc.prototype = {
|
|||||||
done(error);
|
done(error);
|
||||||
}, this);
|
}, this);
|
||||||
|
|
||||||
var req = clientAction.call(client, params, cb);
|
const req = clientAction.call(client, params, cb);
|
||||||
timeoutId = setTimeout(function () {
|
timeoutId = setTimeout(function () {
|
||||||
// request timed out, so we will skip the rest of the tests and continue
|
// request timed out, so we will skip the rest of the tests and continue
|
||||||
req.abort();
|
req.abort();
|
||||||
@ -507,7 +507,7 @@ YamlDoc.prototype = {
|
|||||||
* @return {undefined}
|
* @return {undefined}
|
||||||
*/
|
*/
|
||||||
do_is_true: function (path) {
|
do_is_true: function (path) {
|
||||||
var val = this.get(path);
|
const val = this.get(path);
|
||||||
try {
|
try {
|
||||||
expect(Boolean(val)).to.be(true, 'path: ' + path);
|
expect(Boolean(val)).to.be(true, 'path: ' + path);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@ -523,7 +523,7 @@ YamlDoc.prototype = {
|
|||||||
* @return {undefined}
|
* @return {undefined}
|
||||||
*/
|
*/
|
||||||
do_is_false: function (path) {
|
do_is_false: function (path) {
|
||||||
var val = this.get(path);
|
const val = this.get(path);
|
||||||
try {
|
try {
|
||||||
expect(Boolean(val)).to.be(false, 'path: ' + path);
|
expect(Boolean(val)).to.be(false, 'path: ' + path);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@ -563,7 +563,7 @@ YamlDoc.prototype = {
|
|||||||
* @return {undefined}
|
* @return {undefined}
|
||||||
*/
|
*/
|
||||||
do_match: function (args) {
|
do_match: function (args) {
|
||||||
var self = this;
|
const self = this;
|
||||||
|
|
||||||
// recursively replace all $var within args
|
// recursively replace all $var within args
|
||||||
_.forOwn(args, function recurse(val, key, lvl) {
|
_.forOwn(args, function recurse(val, key, lvl) {
|
||||||
@ -579,10 +579,10 @@ YamlDoc.prototype = {
|
|||||||
});
|
});
|
||||||
|
|
||||||
_.forOwn(args, _.bind(function (match, path) {
|
_.forOwn(args, _.bind(function (match, path) {
|
||||||
var origMatch = match;
|
const origMatch = match;
|
||||||
|
|
||||||
var maybeRE = false;
|
let maybeRE = false;
|
||||||
var usedRE = false;
|
let usedRE = false;
|
||||||
|
|
||||||
if (_.isString(match)) {
|
if (_.isString(match)) {
|
||||||
// convert the matcher into a compatible string for building a regexp
|
// convert the matcher into a compatible string for building a regexp
|
||||||
@ -599,8 +599,8 @@ YamlDoc.prototype = {
|
|||||||
// whitespace is represented with \s
|
// whitespace is represented with \s
|
||||||
.replace(reWhitespaceRE, '');
|
.replace(reWhitespaceRE, '');
|
||||||
|
|
||||||
var startsWithSlash = maybeRE[0] === '/';
|
const startsWithSlash = maybeRE[0] === '/';
|
||||||
var endsWithSlash = maybeRE[maybeRE.length - 1] === '/';
|
const endsWithSlash = maybeRE[maybeRE.length - 1] === '/';
|
||||||
|
|
||||||
if (startsWithSlash && endsWithSlash) {
|
if (startsWithSlash && endsWithSlash) {
|
||||||
usedRE = true;
|
usedRE = true;
|
||||||
@ -608,8 +608,8 @@ YamlDoc.prototype = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var val = this.get(path);
|
let val = this.get(path);
|
||||||
var test = 'eql';
|
let test = 'eql';
|
||||||
|
|
||||||
if (match instanceof RegExp) {
|
if (match instanceof RegExp) {
|
||||||
test = 'match';
|
test = 'match';
|
||||||
@ -622,7 +622,7 @@ YamlDoc.prototype = {
|
|||||||
try {
|
try {
|
||||||
expect(val).to[test](match);
|
expect(val).to[test](match);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
var msg = [
|
const msg = [
|
||||||
'\nUnable to match',
|
'\nUnable to match',
|
||||||
inspect(match),
|
inspect(match),
|
||||||
'with the path',
|
'with the path',
|
||||||
|
|||||||
@ -6,13 +6,13 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = YamlFile;
|
module.exports = YamlFile;
|
||||||
|
|
||||||
var YamlDoc = require('./yaml_doc');
|
const YamlDoc = require('./yaml_doc');
|
||||||
var clientManager = require('./client_manager');
|
const clientManager = require('./client_manager');
|
||||||
var _ = require('../../../src/lib/utils');
|
const _ = require('../../../src/lib/utils');
|
||||||
var async = require('async');
|
const async = require('async');
|
||||||
|
|
||||||
function YamlFile(filename, docs) {
|
function YamlFile(filename, docs) {
|
||||||
var file = this;
|
const file = this;
|
||||||
|
|
||||||
// file level skipping flag
|
// file level skipping flag
|
||||||
file.skipping = false;
|
file.skipping = false;
|
||||||
|
|||||||
@ -1,22 +1,22 @@
|
|||||||
var interceptors = [];
|
const interceptors = [];
|
||||||
var complete = [];
|
const complete = [];
|
||||||
var MockHttpRequest = require('./browser_http');
|
const MockHttpRequest = require('./browser_http');
|
||||||
var XhrServer = MockHttpRequest.MockHttpServer;
|
const XhrServer = MockHttpRequest.MockHttpServer;
|
||||||
var parseUrl = MockHttpRequest.prototype.parseUri;
|
const parseUrl = MockHttpRequest.prototype.parseUri;
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
|
|
||||||
var server = new XhrServer(function (request) {
|
const server = new XhrServer(function (request) {
|
||||||
var reqDetails = {
|
const reqDetails = {
|
||||||
method: request.method,
|
method: request.method,
|
||||||
host: request.urlParts.host,
|
host: request.urlParts.host,
|
||||||
path: request.urlParts.relative
|
path: request.urlParts.relative
|
||||||
};
|
};
|
||||||
var response = _.find(interceptors, reqDetails);
|
const response = _.find(interceptors, reqDetails);
|
||||||
|
|
||||||
if (response) {
|
if (response) {
|
||||||
// remove of tick down the times
|
// remove of tick down the times
|
||||||
if (response.times === 1) {
|
if (response.times === 1) {
|
||||||
var i = interceptors.indexOf(response);
|
const i = interceptors.indexOf(response);
|
||||||
complete.push(interceptors.splice(i, 1));
|
complete.push(interceptors.splice(i, 1));
|
||||||
} else {
|
} else {
|
||||||
response.times--;
|
response.times--;
|
||||||
@ -31,8 +31,8 @@ var server = new XhrServer(function (request) {
|
|||||||
server.start();
|
server.start();
|
||||||
|
|
||||||
var mockNock = module.exports = function (url) {
|
var mockNock = module.exports = function (url) {
|
||||||
var parsedUrl = parseUrl(url);
|
const parsedUrl = parseUrl(url);
|
||||||
var req = {
|
const req = {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
host: parsedUrl.host,
|
host: parsedUrl.host,
|
||||||
times: 1
|
times: 1
|
||||||
|
|||||||
@ -6,9 +6,9 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = MockIncommingMessage;
|
module.exports = MockIncommingMessage;
|
||||||
|
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var util = require('util');
|
const util = require('util');
|
||||||
var Readable = require('stream').Readable;
|
let Readable = require('stream').Readable;
|
||||||
|
|
||||||
if (!Readable) {
|
if (!Readable) {
|
||||||
Readable = require('events').EventEmitter;
|
Readable = require('events').EventEmitter;
|
||||||
|
|||||||
@ -5,9 +5,9 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = MockRequest;
|
module.exports = MockRequest;
|
||||||
|
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var util = require('util');
|
const util = require('util');
|
||||||
var http = require('http');
|
const http = require('http');
|
||||||
|
|
||||||
function MockRequest() {
|
function MockRequest() {
|
||||||
sinon.stub(this, 'end');
|
sinon.stub(this, 'end');
|
||||||
|
|||||||
@ -1,3 +1,3 @@
|
|||||||
var nock = require('nock');
|
const nock = require('nock');
|
||||||
nock.disableNetConnect();
|
nock.disableNetConnect();
|
||||||
module.exports = nock;
|
module.exports = nock;
|
||||||
|
|||||||
@ -3,9 +3,9 @@
|
|||||||
* @type {Constuctor}
|
* @type {Constuctor}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
var util = require('util');
|
const util = require('util');
|
||||||
var MockWritableStream; // defined simply for 0.10+, in detail for older versions
|
let MockWritableStream; // defined simply for 0.10+, in detail for older versions
|
||||||
var Writable = require('stream').Writable;
|
const Writable = require('stream').Writable;
|
||||||
|
|
||||||
|
|
||||||
if (Writable) {
|
if (Writable) {
|
||||||
@ -18,7 +18,7 @@ if (Writable) {
|
|||||||
util.inherits(MockWritableStream, Writable);
|
util.inherits(MockWritableStream, Writable);
|
||||||
} else {
|
} else {
|
||||||
// Node < 0.10 did not provide a usefull stream abstract
|
// Node < 0.10 did not provide a usefull stream abstract
|
||||||
var Stream = require('stream').Stream;
|
const Stream = require('stream').Stream;
|
||||||
module.exports = MockWritableStream = function (opts) {
|
module.exports = MockWritableStream = function (opts) {
|
||||||
Stream.call(this);
|
Stream.call(this);
|
||||||
this.writable = true;
|
this.writable = true;
|
||||||
@ -31,7 +31,7 @@ if (Writable) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
var cb;
|
let cb;
|
||||||
if (typeof (arguments[arguments.length - 1]) === 'function') {
|
if (typeof (arguments[arguments.length - 1]) === 'function') {
|
||||||
cb = arguments[arguments.length - 1];
|
cb = arguments[arguments.length - 1];
|
||||||
}
|
}
|
||||||
@ -54,7 +54,7 @@ if (Writable) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
MockWritableStream.prototype.destroy = function (cb) {
|
MockWritableStream.prototype.destroy = function (cb) {
|
||||||
var self = this;
|
const self = this;
|
||||||
|
|
||||||
if (!this.writable) {
|
if (!this.writable) {
|
||||||
if (cb) {
|
if (cb) {
|
||||||
|
|||||||
28
test/unit/browser_builds/angular.js
vendored
28
test/unit/browser_builds/angular.js
vendored
@ -1,23 +1,23 @@
|
|||||||
/* global angular */
|
/* global angular */
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var Promise = require('bluebird');
|
const Promise = require('bluebird');
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
|
|
||||||
describe('Angular esFactory', function () {
|
describe('Angular esFactory', function () {
|
||||||
before(function () {
|
before(function () {
|
||||||
require('../../../src/elasticsearch.angular.js');
|
require('../../../src/elasticsearch.angular.js');
|
||||||
});
|
});
|
||||||
|
|
||||||
var uuid = (function () { var i = 0; return function () { return ++i; }; }());
|
const uuid = (function () { let i = 0; return function () { return ++i; }; }());
|
||||||
var esFactory;
|
let esFactory;
|
||||||
var $http;
|
let $http;
|
||||||
var $rootScope;
|
let $rootScope;
|
||||||
var $httpBackend;
|
let $httpBackend;
|
||||||
|
|
||||||
function bootstrap(env) {
|
function bootstrap(env) {
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
var promiseProvider = _.noop;
|
let promiseProvider = _.noop;
|
||||||
if (env.bluebirdPromises) {
|
if (env.bluebirdPromises) {
|
||||||
promiseProvider = function ($provide) {
|
promiseProvider = function ($provide) {
|
||||||
$provide.service('$q', function () {
|
$provide.service('$q', function () {
|
||||||
@ -59,7 +59,7 @@ describe('Angular esFactory', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('returns a new client when it is called', function () {
|
it('returns a new client when it is called', function () {
|
||||||
var client = esFactory({
|
const client = esFactory({
|
||||||
hosts: null
|
hosts: null
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -69,10 +69,10 @@ describe('Angular esFactory', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('returns an error created by calling a method incorrectly', function () {
|
it('returns an error created by calling a method incorrectly', function () {
|
||||||
var client = esFactory({ hosts: null });
|
const client = esFactory({ hosts: null });
|
||||||
var err;
|
let err;
|
||||||
|
|
||||||
var prom = client.get().then(function () {
|
const prom = client.get().then(function () {
|
||||||
throw new Error('expected request to fail');
|
throw new Error('expected request to fail');
|
||||||
}, function (err) {
|
}, function (err) {
|
||||||
expect(err).to.have.property('message');
|
expect(err).to.have.property('message');
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var Transport = require('../../../src/lib/transport');
|
const Transport = require('../../../src/lib/transport');
|
||||||
|
|
||||||
describe('elasticsearch namespace', function () {
|
describe('elasticsearch namespace', function () {
|
||||||
var es = window.elasticsearch;
|
const es = window.elasticsearch;
|
||||||
it('is defined on the window', function () {
|
it('is defined on the window', function () {
|
||||||
expect(es).to.be.ok();
|
expect(es).to.be.ok();
|
||||||
});
|
});
|
||||||
@ -12,7 +12,7 @@ describe('elasticsearch namespace', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('can create a client', function () {
|
it('can create a client', function () {
|
||||||
var client = new es.Client({ hosts: null });
|
const client = new es.Client({ hosts: null });
|
||||||
expect(client).to.have.keys('transport');
|
expect(client).to.have.keys('transport');
|
||||||
expect(client.transport).to.be.a(es.Transport);
|
expect(client.transport).to.be.a(es.Transport);
|
||||||
client.close();
|
client.close();
|
||||||
|
|||||||
6
test/unit/browser_builds/jquery.js
vendored
6
test/unit/browser_builds/jquery.js
vendored
@ -1,6 +1,6 @@
|
|||||||
/* global $ */
|
/* global $ */
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var Transport = require('../../../src/lib/transport');
|
const Transport = require('../../../src/lib/transport');
|
||||||
|
|
||||||
describe('jQuery.es namespace', function () {
|
describe('jQuery.es namespace', function () {
|
||||||
it('is defined on the global jQuery', function () {
|
it('is defined on the global jQuery', function () {
|
||||||
@ -12,7 +12,7 @@ describe('jQuery.es namespace', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('can create a client', function () {
|
it('can create a client', function () {
|
||||||
var client = new $.es.Client({ hosts: null });
|
const client = new $.es.Client({ hosts: null });
|
||||||
expect(client).to.have.keys('transport');
|
expect(client).to.have.keys('transport');
|
||||||
expect(client.transport).to.be.a($.es.Transport);
|
expect(client.transport).to.be.a($.es.Transport);
|
||||||
client.close();
|
client.close();
|
||||||
|
|||||||
@ -1,16 +1,16 @@
|
|||||||
module.exports = function (makeLogger) {
|
module.exports = function (makeLogger) {
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var stub = require('../utils/auto_release_stub').make();
|
const stub = require('../utils/auto_release_stub').make();
|
||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
var once = require('events').EventEmitter.prototype.once;
|
const once = require('events').EventEmitter.prototype.once;
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
|
|
||||||
describe('buffer flush', function () {
|
describe('buffer flush', function () {
|
||||||
if (require('stream').Writable) {
|
if (require('stream').Writable) {
|
||||||
it('writes everything in the buffer to console.error', function () {
|
it('writes everything in the buffer to console.error', function () {
|
||||||
var line = 'This string is written 10 times to create buffered output\n';
|
const line = 'This string is written 10 times to create buffered output\n';
|
||||||
|
|
||||||
var exitHandler;
|
let exitHandler;
|
||||||
stub(process, 'once', function (event, handler) {
|
stub(process, 'once', function (event, handler) {
|
||||||
if (event === 'exit') {
|
if (event === 'exit') {
|
||||||
exitHandler = handler;
|
exitHandler = handler;
|
||||||
@ -18,7 +18,7 @@ module.exports = function (makeLogger) {
|
|||||||
once.call(process, event, handler);
|
once.call(process, event, handler);
|
||||||
});
|
});
|
||||||
|
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
|
|
||||||
// write the line 10 times
|
// write the line 10 times
|
||||||
_.times(10, function () {
|
_.times(10, function () {
|
||||||
@ -26,7 +26,7 @@ module.exports = function (makeLogger) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// collect everything that is written to fs.appendFileSync
|
// collect everything that is written to fs.appendFileSync
|
||||||
var flushedOutput = '';
|
let flushedOutput = '';
|
||||||
stub(fs, 'appendFileSync', function (path, str) {
|
stub(fs, 'appendFileSync', function (path, str) {
|
||||||
flushedOutput += str;
|
flushedOutput += str;
|
||||||
});
|
});
|
||||||
@ -40,7 +40,7 @@ module.exports = function (makeLogger) {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
it('does not fall apart with non streams2 streams', function () {
|
it('does not fall apart with non streams2 streams', function () {
|
||||||
var exitHandler;
|
let exitHandler;
|
||||||
stub(process, 'once', function (event, handler) {
|
stub(process, 'once', function (event, handler) {
|
||||||
if (event === 'exit') {
|
if (event === 'exit') {
|
||||||
exitHandler = handler;
|
exitHandler = handler;
|
||||||
@ -48,7 +48,7 @@ module.exports = function (makeLogger) {
|
|||||||
once.call(process, event, handler);
|
once.call(process, event, handler);
|
||||||
});
|
});
|
||||||
|
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
|
|
||||||
expect(function () {
|
expect(function () {
|
||||||
// call the event handler
|
// call the event handler
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
var blanket = require('blanket')({
|
const blanket = require('blanket')({
|
||||||
pattern: require('path').join(__dirname, '../../src')
|
pattern: require('path').join(__dirname, '../../src')
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -1,13 +1,13 @@
|
|||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var Log = require('../../src/lib/log');
|
const Log = require('../../src/lib/log');
|
||||||
var LoggerAbstract = require('../../src/lib/logger');
|
const LoggerAbstract = require('../../src/lib/logger');
|
||||||
var TracerLogger = require('../../src/lib/loggers/tracer');
|
const TracerLogger = require('../../src/lib/loggers/tracer');
|
||||||
var now = new Date('2013-03-01T00:00:00Z');
|
const now = new Date('2013-03-01T00:00:00Z');
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
|
|
||||||
module.exports = function (makeLogger) {
|
module.exports = function (makeLogger) {
|
||||||
var stub = require('../utils/auto_release_stub').make();
|
const stub = require('../utils/auto_release_stub').make();
|
||||||
var parent = new Log();
|
const parent = new Log();
|
||||||
|
|
||||||
afterEach(function () {
|
afterEach(function () {
|
||||||
parent.close();
|
parent.close();
|
||||||
@ -15,7 +15,7 @@ module.exports = function (makeLogger) {
|
|||||||
|
|
||||||
describe('Constuctor', function () {
|
describe('Constuctor', function () {
|
||||||
it('calls setupListeners, passes its new levels', function () {
|
it('calls setupListeners, passes its new levels', function () {
|
||||||
var logger = makeLogger(parent);
|
let logger = makeLogger(parent);
|
||||||
stub(logger.constructor.prototype, 'setupListeners');
|
stub(logger.constructor.prototype, 'setupListeners');
|
||||||
parent.close();
|
parent.close();
|
||||||
|
|
||||||
@ -24,21 +24,21 @@ module.exports = function (makeLogger) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('listens for the loggers\' "closing" event', function () {
|
it('listens for the loggers\' "closing" event', function () {
|
||||||
var logger = makeLogger(parent);
|
const logger = makeLogger(parent);
|
||||||
expect(parent.listenerCount('closing')).to.eql(1);
|
expect(parent.listenerCount('closing')).to.eql(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('listening levels', function () {
|
describe('listening levels', function () {
|
||||||
it('calls cleanUpListeners when the listeners are being setup', function () {
|
it('calls cleanUpListeners when the listeners are being setup', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
stub(logger, 'cleanUpListeners');
|
stub(logger, 'cleanUpListeners');
|
||||||
logger.setupListeners([]);
|
logger.setupListeners([]);
|
||||||
expect(logger.cleanUpListeners).to.have.property('callCount', 1);
|
expect(logger.cleanUpListeners).to.have.property('callCount', 1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('listens to just error when log is explicitly error', function () {
|
it('listens to just error when log is explicitly error', function () {
|
||||||
var logger = makeLogger(parent, 'error');
|
const logger = makeLogger(parent, 'error');
|
||||||
expect(parent.listenerCount('error')).to.eql(1);
|
expect(parent.listenerCount('error')).to.eql(1);
|
||||||
expect(parent.listenerCount('warning')).to.eql(0);
|
expect(parent.listenerCount('warning')).to.eql(0);
|
||||||
expect(parent.listenerCount('info')).to.eql(0);
|
expect(parent.listenerCount('info')).to.eql(0);
|
||||||
@ -47,7 +47,7 @@ module.exports = function (makeLogger) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('listens for all the events when level is "trace"', function () {
|
it('listens for all the events when level is "trace"', function () {
|
||||||
var logger = makeLogger(parent, 'trace');
|
const logger = makeLogger(parent, 'trace');
|
||||||
expect(parent.listenerCount('error')).to.eql(1);
|
expect(parent.listenerCount('error')).to.eql(1);
|
||||||
expect(parent.listenerCount('warning')).to.eql(1);
|
expect(parent.listenerCount('warning')).to.eql(1);
|
||||||
expect(parent.listenerCount('info')).to.eql(1);
|
expect(parent.listenerCount('info')).to.eql(1);
|
||||||
@ -56,7 +56,7 @@ module.exports = function (makeLogger) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('listens for specific events when level is an array', function () {
|
it('listens for specific events when level is an array', function () {
|
||||||
var logger = makeLogger(parent, ['error', 'trace']);
|
const logger = makeLogger(parent, ['error', 'trace']);
|
||||||
expect(parent.listenerCount('error')).to.eql(1);
|
expect(parent.listenerCount('error')).to.eql(1);
|
||||||
expect(parent.listenerCount('warning')).to.eql(0);
|
expect(parent.listenerCount('warning')).to.eql(0);
|
||||||
expect(parent.listenerCount('info')).to.eql(0);
|
expect(parent.listenerCount('info')).to.eql(0);
|
||||||
@ -65,8 +65,8 @@ module.exports = function (makeLogger) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('sets the logLevel property to the new levels', function () {
|
it('sets the logLevel property to the new levels', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
var levels = ['error'];
|
let levels = ['error'];
|
||||||
logger.setupListeners(levels);
|
logger.setupListeners(levels);
|
||||||
expect(logger.listeningLevels).to.eql(levels).and.not.be(levels);
|
expect(logger.listeningLevels).to.eql(levels).and.not.be(levels);
|
||||||
|
|
||||||
@ -80,14 +80,14 @@ module.exports = function (makeLogger) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('rejects listening levels it can not listen to', function () {
|
it('rejects listening levels it can not listen to', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
expect(function () {
|
expect(function () {
|
||||||
logger.setupListeners(['scream']);
|
logger.setupListeners(['scream']);
|
||||||
}).to.throwError(/unable to listen/i);
|
}).to.throwError(/unable to listen/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('emits events because something is listening', function () {
|
it('emits events because something is listening', function () {
|
||||||
var logger = makeLogger(parent, 'trace');
|
const logger = makeLogger(parent, 'trace');
|
||||||
stub(parent, 'emit');
|
stub(parent, 'emit');
|
||||||
|
|
||||||
parent.error(new Error('error message'));
|
parent.error(new Error('error message'));
|
||||||
@ -110,7 +110,7 @@ module.exports = function (makeLogger) {
|
|||||||
describe('#timestamp', function () {
|
describe('#timestamp', function () {
|
||||||
it('returns in the right format', function () {
|
it('returns in the right format', function () {
|
||||||
stub.autoRelease(sinon.useFakeTimers(now.getTime()));
|
stub.autoRelease(sinon.useFakeTimers(now.getTime()));
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
expect(logger.timestamp()).to.eql('2013-03-01T00:00:00Z');
|
expect(logger.timestamp()).to.eql('2013-03-01T00:00:00Z');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -118,7 +118,7 @@ module.exports = function (makeLogger) {
|
|||||||
describe('#format', function () {
|
describe('#format', function () {
|
||||||
it('returns a single string with the message indented', function () {
|
it('returns a single string with the message indented', function () {
|
||||||
stub.autoRelease(sinon.useFakeTimers(now.getTime()));
|
stub.autoRelease(sinon.useFakeTimers(now.getTime()));
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
expect(logger.format('LABEL', 'MSG')).to.eql(
|
expect(logger.format('LABEL', 'MSG')).to.eql(
|
||||||
'LABEL: 2013-03-01T00:00:00Z\n' +
|
'LABEL: 2013-03-01T00:00:00Z\n' +
|
||||||
' MSG\n' +
|
' MSG\n' +
|
||||||
@ -128,7 +128,7 @@ module.exports = function (makeLogger) {
|
|||||||
|
|
||||||
it('properly indents multi-line messages', function () {
|
it('properly indents multi-line messages', function () {
|
||||||
stub.autoRelease(sinon.useFakeTimers(now.getTime()));
|
stub.autoRelease(sinon.useFakeTimers(now.getTime()));
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
expect(logger.format('LABEL', 'MSG\nwith\nseveral lines')).to.eql(
|
expect(logger.format('LABEL', 'MSG\nwith\nseveral lines')).to.eql(
|
||||||
'LABEL: 2013-03-01T00:00:00Z\n' +
|
'LABEL: 2013-03-01T00:00:00Z\n' +
|
||||||
' MSG\n' +
|
' MSG\n' +
|
||||||
@ -141,7 +141,7 @@ module.exports = function (makeLogger) {
|
|||||||
|
|
||||||
describe('#onError', function () {
|
describe('#onError', function () {
|
||||||
it('uses the Error name when it is not just "Error"', function () {
|
it('uses the Error name when it is not just "Error"', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
stub(logger, 'write', function (label, msg) {
|
stub(logger, 'write', function (label, msg) {
|
||||||
expect(label).to.eql('TypeError');
|
expect(label).to.eql('TypeError');
|
||||||
});
|
});
|
||||||
@ -151,7 +151,7 @@ module.exports = function (makeLogger) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('uses "ERROR" when the error name is "Error"', function () {
|
it('uses "ERROR" when the error name is "Error"', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
stub(logger, 'write', function (label, msg) {
|
stub(logger, 'write', function (label, msg) {
|
||||||
expect(label).to.eql('ERROR');
|
expect(label).to.eql('ERROR');
|
||||||
});
|
});
|
||||||
@ -163,7 +163,7 @@ module.exports = function (makeLogger) {
|
|||||||
|
|
||||||
describe('#onWarning', function () {
|
describe('#onWarning', function () {
|
||||||
it('uses the "WARNING" label', function () {
|
it('uses the "WARNING" label', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
stub(logger, 'write', function (label, msg) {
|
stub(logger, 'write', function (label, msg) {
|
||||||
expect(label).to.eql('WARNING');
|
expect(label).to.eql('WARNING');
|
||||||
});
|
});
|
||||||
@ -172,7 +172,7 @@ module.exports = function (makeLogger) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('echos the message', function () {
|
it('echos the message', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
stub(logger, 'write', function (label, msg) {
|
stub(logger, 'write', function (label, msg) {
|
||||||
expect(msg).to.eql('message');
|
expect(msg).to.eql('message');
|
||||||
});
|
});
|
||||||
@ -184,7 +184,7 @@ module.exports = function (makeLogger) {
|
|||||||
|
|
||||||
describe('#onInfo', function () {
|
describe('#onInfo', function () {
|
||||||
it('uses the "INFO" label', function () {
|
it('uses the "INFO" label', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
stub(logger, 'write', function (label, msg) {
|
stub(logger, 'write', function (label, msg) {
|
||||||
expect(label).to.eql('INFO');
|
expect(label).to.eql('INFO');
|
||||||
});
|
});
|
||||||
@ -193,7 +193,7 @@ module.exports = function (makeLogger) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('echos the message', function () {
|
it('echos the message', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
stub(logger, 'write', function (label, msg) {
|
stub(logger, 'write', function (label, msg) {
|
||||||
expect(msg).to.eql('message');
|
expect(msg).to.eql('message');
|
||||||
});
|
});
|
||||||
@ -205,7 +205,7 @@ module.exports = function (makeLogger) {
|
|||||||
|
|
||||||
describe('#onDebug', function () {
|
describe('#onDebug', function () {
|
||||||
it('uses the "DEBUG" label', function () {
|
it('uses the "DEBUG" label', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
stub(logger, 'write', function (label, msg) {
|
stub(logger, 'write', function (label, msg) {
|
||||||
expect(label).to.eql('DEBUG');
|
expect(label).to.eql('DEBUG');
|
||||||
});
|
});
|
||||||
@ -214,7 +214,7 @@ module.exports = function (makeLogger) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('echos the message', function () {
|
it('echos the message', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
stub(logger, 'write', function (label, msg) {
|
stub(logger, 'write', function (label, msg) {
|
||||||
expect(msg).to.eql('message');
|
expect(msg).to.eql('message');
|
||||||
});
|
});
|
||||||
@ -226,7 +226,7 @@ module.exports = function (makeLogger) {
|
|||||||
|
|
||||||
describe('#onTrace', function () {
|
describe('#onTrace', function () {
|
||||||
it('uses the "TRACE" label', function () {
|
it('uses the "TRACE" label', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
stub(logger, 'write', function (label, msg) {
|
stub(logger, 'write', function (label, msg) {
|
||||||
expect(label).to.eql('TRACE');
|
expect(label).to.eql('TRACE');
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
require('bluebird').longStackTraces();
|
require('bluebird').longStackTraces();
|
||||||
|
|
||||||
var specDir = __dirname + '/specs';
|
const specDir = __dirname + '/specs';
|
||||||
require('fs').readdirSync(specDir).forEach(function (file) {
|
require('fs').readdirSync(specDir).forEach(function (file) {
|
||||||
require(specDir + '/' + file);
|
require(specDir + '/' + file);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
describe('Logger Abstract', function () {
|
describe('Logger Abstract', function () {
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var Log = require('../../../src/lib/log');
|
const Log = require('../../../src/lib/log');
|
||||||
var LoggerAbstract = require('../../../src/lib/logger');
|
const LoggerAbstract = require('../../../src/lib/logger');
|
||||||
|
|
||||||
var parentLog;
|
let parentLog;
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
function makeLogger(parent, levels) {
|
function makeLogger(parent, levels) {
|
||||||
return new LoggerAbstract(parent || parentLog, {
|
return new LoggerAbstract(parent || parentLog, {
|
||||||
@ -24,7 +24,7 @@ describe('Logger Abstract', function () {
|
|||||||
describe('#write', function () {
|
describe('#write', function () {
|
||||||
it('requires that it is overwritten', function () {
|
it('requires that it is overwritten', function () {
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
logger.write();
|
logger.write();
|
||||||
}).to.throwError(/overwritten/);
|
}).to.throwError(/overwritten/);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
describe('Client instances creation', function () {
|
describe('Client instances creation', function () {
|
||||||
var stream = require('stream');
|
const stream = require('stream');
|
||||||
var util = require('util');
|
const util = require('util');
|
||||||
|
|
||||||
var es = require('../../../src/elasticsearch');
|
const es = require('../../../src/elasticsearch');
|
||||||
var apis = require('../../../src/lib/apis');
|
const apis = require('../../../src/lib/apis');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
var client;
|
let client;
|
||||||
|
|
||||||
describe('', function () {
|
describe('', function () {
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
@ -18,16 +18,16 @@ describe('Client instances creation', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('throws an error linking to the es module when you try to instanciate the exports', function () {
|
it('throws an error linking to the es module when you try to instanciate the exports', function () {
|
||||||
var Es = es;
|
const Es = es;
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var c = new Es();
|
const c = new Es();
|
||||||
return c
|
return c;
|
||||||
}).to.throwError(/previous "elasticsearch" module/);
|
}).to.throwError(/previous "elasticsearch" module/);
|
||||||
});
|
});
|
||||||
|
|
||||||
var pkg = require('../../../package.json');
|
const pkg = require('../../../package.json');
|
||||||
var def = pkg.config.default_api_branch;
|
const def = pkg.config.default_api_branch;
|
||||||
var prev = pkg.config.supported_es_branches[pkg.config.supported_es_branches.indexOf(def) + 1];
|
const prev = pkg.config.supported_es_branches[pkg.config.supported_es_branches.indexOf(def) + 1];
|
||||||
|
|
||||||
it('inherits the ' + def + ' API by default', function () {
|
it('inherits the ' + def + ' API by default', function () {
|
||||||
expect(client.bulk).to.be(apis[def].bulk);
|
expect(client.bulk).to.be(apis[def].bulk);
|
||||||
@ -44,7 +44,7 @@ describe('Client instances creation', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('closing the client causes it\'s transport to be closed', function () {
|
it('closing the client causes it\'s transport to be closed', function () {
|
||||||
var called = false;
|
let called = false;
|
||||||
client.transport.close = function () {
|
client.transport.close = function () {
|
||||||
called = true;
|
called = true;
|
||||||
};
|
};
|
||||||
@ -72,7 +72,7 @@ describe('Client instances creation', function () {
|
|||||||
done();
|
done();
|
||||||
};
|
};
|
||||||
|
|
||||||
var client = new es.Client({
|
const client = new es.Client({
|
||||||
log: [
|
log: [
|
||||||
{ type: 'stream', stream: new NullStream() }
|
{ type: 'stream', stream: new NullStream() }
|
||||||
]
|
]
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
var ca = require('../../../src/lib/client_action').factory;
|
const ca = require('../../../src/lib/client_action').factory;
|
||||||
var proxy = require('../../../src/lib/client_action').proxyFactory;
|
const proxy = require('../../../src/lib/client_action').proxyFactory;
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var Promise = require('bluebird');
|
const Promise = require('bluebird');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a simple mock of the client, whose "transport" has a request
|
* Creates a simple mock of the client, whose "transport" has a request
|
||||||
@ -60,13 +60,13 @@ function makeClientActionProxy(fn, spec) {
|
|||||||
|
|
||||||
|
|
||||||
describe('Client Action runner', function () {
|
describe('Client Action runner', function () {
|
||||||
var action;
|
let action;
|
||||||
|
|
||||||
// used to check that params are not clobbered
|
// used to check that params are not clobbered
|
||||||
var params = (function () {
|
const params = (function () {
|
||||||
var _stash = {};
|
let _stash = {};
|
||||||
afterEach(function () { _stash = {}; });
|
afterEach(function () { _stash = {}; });
|
||||||
var make = function (params) {
|
const make = function (params) {
|
||||||
_stash.orig = params;
|
_stash.orig = params;
|
||||||
_stash.copy = _.clone(params);
|
_stash.copy = _.clone(params);
|
||||||
return params;
|
return params;
|
||||||
@ -92,7 +92,7 @@ describe('Client Action runner', function () {
|
|||||||
|
|
||||||
describe('clientAction::proxy', function () {
|
describe('clientAction::proxy', function () {
|
||||||
it('proxies to the passed function', function () {
|
it('proxies to the passed function', function () {
|
||||||
var action = makeClientActionProxy(function (params, cb) {
|
const action = makeClientActionProxy(function (params, cb) {
|
||||||
throw new Error('proxy function called');
|
throw new Error('proxy function called');
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -102,8 +102,8 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('provides the proper context', function (done) {
|
it('provides the proper context', function (done) {
|
||||||
var client;
|
let client;
|
||||||
var action = makeClientActionProxy(function (params, cb) {
|
const action = makeClientActionProxy(function (params, cb) {
|
||||||
client = this;
|
client = this;
|
||||||
process.nextTick(function () {
|
process.nextTick(function () {
|
||||||
cb(void 0, params);
|
cb(void 0, params);
|
||||||
@ -117,7 +117,7 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('handles passing just the callback', function () {
|
it('handles passing just the callback', function () {
|
||||||
var action = makeClientActionProxy(function (params, cb) {
|
const action = makeClientActionProxy(function (params, cb) {
|
||||||
expect(_.isObject(params)).to.be.ok();
|
expect(_.isObject(params)).to.be.ok();
|
||||||
expect(cb).to.be.a('function');
|
expect(cb).to.be.a('function');
|
||||||
});
|
});
|
||||||
@ -126,7 +126,7 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('supports a param transformation function', function () {
|
it('supports a param transformation function', function () {
|
||||||
var action = makeClientActionProxy(function (params, cb) {
|
const action = makeClientActionProxy(function (params, cb) {
|
||||||
expect(params).to.have.property('transformed');
|
expect(params).to.have.property('transformed');
|
||||||
}, {
|
}, {
|
||||||
transform: function (params) {
|
transform: function (params) {
|
||||||
@ -138,8 +138,8 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('returns the proxied function\'s return value', function () {
|
it('returns the proxied function\'s return value', function () {
|
||||||
var football = {};
|
const football = {};
|
||||||
var action = makeClientActionProxy(function (params, cb) {
|
const action = makeClientActionProxy(function (params, cb) {
|
||||||
return football;
|
return football;
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -537,7 +537,7 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('accepts numbers, strings, and dates', function (done) {
|
it('accepts numbers, strings, and dates', function (done) {
|
||||||
var now = new Date();
|
const now = new Date();
|
||||||
|
|
||||||
action({
|
action({
|
||||||
one: '42',
|
one: '42',
|
||||||
@ -587,7 +587,7 @@ describe('Client Action runner', function () {
|
|||||||
|
|
||||||
describe('passing of control params from spec', function () {
|
describe('passing of control params from spec', function () {
|
||||||
it('passes bulkBody', function (done) {
|
it('passes bulkBody', function (done) {
|
||||||
var action = makeClientAction({
|
const action = makeClientAction({
|
||||||
bulkBody: true
|
bulkBody: true
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -598,7 +598,7 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('sets castExists when the method in the spec is HEAD', function (done) {
|
it('sets castExists when the method in the spec is HEAD', function (done) {
|
||||||
var action = makeClientAction({
|
const action = makeClientAction({
|
||||||
method: 'HEAD'
|
method: 'HEAD'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -610,12 +610,12 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('body handling', function () {
|
describe('body handling', function () {
|
||||||
var action = makeClientAction({
|
const action = makeClientAction({
|
||||||
needsBody: true
|
needsBody: true
|
||||||
});
|
});
|
||||||
|
|
||||||
it('passed the body when it is set', function (done) {
|
it('passed the body when it is set', function (done) {
|
||||||
var body = '{"JSON":"PLEASE"}';
|
const body = '{"JSON":"PLEASE"}';
|
||||||
|
|
||||||
action({ body: body }, function (err, params) {
|
action({ body: body }, function (err, params) {
|
||||||
expect(params.body).to.be(body);
|
expect(params.body).to.be(body);
|
||||||
@ -635,7 +635,7 @@ describe('Client Action runner', function () {
|
|||||||
|
|
||||||
describe('passing of http method', function () {
|
describe('passing of http method', function () {
|
||||||
it('uppercases and passed the default method', function (done) {
|
it('uppercases and passed the default method', function (done) {
|
||||||
var action = makeClientAction({
|
const action = makeClientAction({
|
||||||
method: 'POST'
|
method: 'POST'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -646,7 +646,7 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('uppercases and passed the default method', function (done) {
|
it('uppercases and passed the default method', function (done) {
|
||||||
var action = makeClientAction({
|
const action = makeClientAction({
|
||||||
method: 'POST'
|
method: 'POST'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -659,7 +659,7 @@ describe('Client Action runner', function () {
|
|||||||
|
|
||||||
describe('passing of ignore param', function () {
|
describe('passing of ignore param', function () {
|
||||||
it('passes ignore as an array', function (done) {
|
it('passes ignore as an array', function (done) {
|
||||||
var action = makeClientAction({});
|
const action = makeClientAction({});
|
||||||
action({ ignore: 404 }, function (err, params) {
|
action({ ignore: 404 }, function (err, params) {
|
||||||
expect(params.ignore).to.eql([404]);
|
expect(params.ignore).to.eql([404]);
|
||||||
done();
|
done();
|
||||||
@ -669,7 +669,7 @@ describe('Client Action runner', function () {
|
|||||||
|
|
||||||
describe('passing requestTimeout', function () {
|
describe('passing requestTimeout', function () {
|
||||||
it('passes passes the spec value by default', function (done) {
|
it('passes passes the spec value by default', function (done) {
|
||||||
var action = makeClientAction({
|
const action = makeClientAction({
|
||||||
requestTimeout: 100
|
requestTimeout: 100
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -680,7 +680,7 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('passes the provided value', function (done) {
|
it('passes the provided value', function (done) {
|
||||||
var action = makeClientAction({
|
const action = makeClientAction({
|
||||||
requestTimeout: 100
|
requestTimeout: 100
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -691,7 +691,7 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('passes nothing be default', function (done) {
|
it('passes nothing be default', function (done) {
|
||||||
var action = makeClientAction({});
|
const action = makeClientAction({});
|
||||||
|
|
||||||
action({}, function (err, params) {
|
action({}, function (err, params) {
|
||||||
expect(params.requestTimeout).be(void 0);
|
expect(params.requestTimeout).be(void 0);
|
||||||
@ -702,7 +702,7 @@ describe('Client Action runner', function () {
|
|||||||
|
|
||||||
describe('url resolver', function () {
|
describe('url resolver', function () {
|
||||||
|
|
||||||
var action = makeClientAction({
|
const action = makeClientAction({
|
||||||
urls: [
|
urls: [
|
||||||
{
|
{
|
||||||
fmt: '/<%=index%>/<%=type%>/<%=id%>/<%=thing%>',
|
fmt: '/<%=index%>/<%=type%>/<%=id%>/<%=thing%>',
|
||||||
@ -767,7 +767,7 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('param collection', function () {
|
describe('param collection', function () {
|
||||||
var action = makeClientAction({
|
const action = makeClientAction({
|
||||||
params: {
|
params: {
|
||||||
a: { type: 'list', required: true },
|
a: { type: 'list', required: true },
|
||||||
b: { type: 'duration', 'default': '15m' },
|
b: { type: 'duration', 'default': '15m' },
|
||||||
@ -853,7 +853,7 @@ describe('Client Action runner', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('does not modify the incoming params object', function () {
|
it('does not modify the incoming params object', function () {
|
||||||
var action = makeClientAction({
|
const action = makeClientAction({
|
||||||
url: {
|
url: {
|
||||||
req: {
|
req: {
|
||||||
index: { type: 'string' }
|
index: { type: 'string' }
|
||||||
|
|||||||
@ -1,42 +1,42 @@
|
|||||||
var ConnectionAbstract = require('../../../src/lib/connection');
|
const ConnectionAbstract = require('../../../src/lib/connection');
|
||||||
var Host = require('../../../src/lib/host');
|
const Host = require('../../../src/lib/host');
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var errors = require('../../../src/lib/errors');
|
const errors = require('../../../src/lib/errors');
|
||||||
|
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
describe('Connection Abstract', function () {
|
describe('Connection Abstract', function () {
|
||||||
var host = new Host('localhost:9200');
|
const host = new Host('localhost:9200');
|
||||||
|
|
||||||
it('constructs with defaults for host, and bound', function () {
|
it('constructs with defaults for host, and bound', function () {
|
||||||
var conn = new ConnectionAbstract(host);
|
const conn = new ConnectionAbstract(host);
|
||||||
expect(conn.host).to.be(host);
|
expect(conn.host).to.be(host);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('requires a valid host', function () {
|
it('requires a valid host', function () {
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var conn = new ConnectionAbstract();
|
const conn = new ConnectionAbstract();
|
||||||
}).to.throwError(TypeError);
|
}).to.throwError(TypeError);
|
||||||
|
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var conn = new ConnectionAbstract({});
|
const conn = new ConnectionAbstract({});
|
||||||
}).to.throwError(TypeError);
|
}).to.throwError(TypeError);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('required that the request method is overridden', function () {
|
it('required that the request method is overridden', function () {
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var conn = new ConnectionAbstract(host);
|
const conn = new ConnectionAbstract(host);
|
||||||
conn.request();
|
conn.request();
|
||||||
}).to.throwError(/overwrit/);
|
}).to.throwError(/overwrit/);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('#ping', function () {
|
describe('#ping', function () {
|
||||||
it('accpets just a callback', function () {
|
it('accpets just a callback', function () {
|
||||||
var conn = new ConnectionAbstract(host);
|
const conn = new ConnectionAbstract(host);
|
||||||
stub(conn, 'request');
|
stub(conn, 'request');
|
||||||
var cb = function () {};
|
const cb = function () {};
|
||||||
conn.ping(cb);
|
conn.ping(cb);
|
||||||
expect(conn.request.callCount).to.eql(1);
|
expect(conn.request.callCount).to.eql(1);
|
||||||
expect(conn.request.lastCall.args[0]).to.be.a('object');
|
expect(conn.request.lastCall.args[0]).to.be.a('object');
|
||||||
@ -44,7 +44,7 @@ describe('Connection Abstract', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('accpets just params', function () {
|
it('accpets just params', function () {
|
||||||
var conn = new ConnectionAbstract(host);
|
const conn = new ConnectionAbstract(host);
|
||||||
stub(conn, 'request');
|
stub(conn, 'request');
|
||||||
conn.ping({});
|
conn.ping({});
|
||||||
expect(conn.request.callCount).to.eql(1);
|
expect(conn.request.callCount).to.eql(1);
|
||||||
@ -53,9 +53,9 @@ describe('Connection Abstract', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('allows overriding the requestTimeout, method, and path', function () {
|
it('allows overriding the requestTimeout, method, and path', function () {
|
||||||
var conn = new ConnectionAbstract(host);
|
const conn = new ConnectionAbstract(host);
|
||||||
stub(conn, 'request');
|
stub(conn, 'request');
|
||||||
var params = {
|
const params = {
|
||||||
method: 'HEAD',
|
method: 'HEAD',
|
||||||
path: '/',
|
path: '/',
|
||||||
requestTimeout: 10000
|
requestTimeout: 10000
|
||||||
@ -67,8 +67,8 @@ describe('Connection Abstract', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('defaults to the pingTimeout in the config', function () {
|
it('defaults to the pingTimeout in the config', function () {
|
||||||
var conn = new ConnectionAbstract(host, { pingTimeout: 5000 });
|
const conn = new ConnectionAbstract(host, { pingTimeout: 5000 });
|
||||||
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
||||||
stub.autoRelease(clock);
|
stub.autoRelease(clock);
|
||||||
|
|
||||||
stub(conn, 'request');
|
stub(conn, 'request');
|
||||||
@ -80,17 +80,17 @@ describe('Connection Abstract', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('calls it\'s own request method', function () {
|
it('calls it\'s own request method', function () {
|
||||||
var conn = new ConnectionAbstract(host);
|
const conn = new ConnectionAbstract(host);
|
||||||
stub(conn, 'request');
|
stub(conn, 'request');
|
||||||
conn.ping();
|
conn.ping();
|
||||||
expect(conn.request.callCount).to.eql(1);
|
expect(conn.request.callCount).to.eql(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sets a timer for the request', function (done) {
|
it('sets a timer for the request', function (done) {
|
||||||
var conn = new ConnectionAbstract(host);
|
const conn = new ConnectionAbstract(host);
|
||||||
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
||||||
stub.autoRelease(clock);
|
stub.autoRelease(clock);
|
||||||
var order = 0;
|
let order = 0;
|
||||||
|
|
||||||
stub(conn, 'request', function (params, cb) {
|
stub(conn, 'request', function (params, cb) {
|
||||||
setTimeout(function () {
|
setTimeout(function () {
|
||||||
@ -113,10 +113,10 @@ describe('Connection Abstract', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
it('calls the requestAborter if req takes too long', function (done) {
|
it('calls the requestAborter if req takes too long', function (done) {
|
||||||
var conn = new ConnectionAbstract(host);
|
const conn = new ConnectionAbstract(host);
|
||||||
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
||||||
stub.autoRelease(clock);
|
stub.autoRelease(clock);
|
||||||
var order = 0;
|
let order = 0;
|
||||||
|
|
||||||
stub(conn, 'request', function (params, cb) {
|
stub(conn, 'request', function (params, cb) {
|
||||||
setTimeout(function () {
|
setTimeout(function () {
|
||||||
@ -148,8 +148,8 @@ describe('Connection Abstract', function () {
|
|||||||
|
|
||||||
describe('#setStatus', function () {
|
describe('#setStatus', function () {
|
||||||
it('emits the "status set" event with `new`, `old` & `conn` args', function () {
|
it('emits the "status set" event with `new`, `old` & `conn` args', function () {
|
||||||
var conn = new ConnectionAbstract(host);
|
const conn = new ConnectionAbstract(host);
|
||||||
var emitted = false;
|
let emitted = false;
|
||||||
|
|
||||||
conn.emit = function (eventName) {
|
conn.emit = function (eventName) {
|
||||||
emitted = {
|
emitted = {
|
||||||
@ -164,7 +164,7 @@ describe('Connection Abstract', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('stores the status in this.status', function () {
|
it('stores the status in this.status', function () {
|
||||||
var conn = new ConnectionAbstract(host);
|
const conn = new ConnectionAbstract(host);
|
||||||
|
|
||||||
conn.setStatus('closed');
|
conn.setStatus('closed');
|
||||||
expect(conn.status).to.eql('closed');
|
expect(conn.status).to.eql('closed');
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
var ConnectionPool = require('../../../src/lib/connection_pool');
|
const ConnectionPool = require('../../../src/lib/connection_pool');
|
||||||
var Host = require('../../../src/lib/host');
|
const Host = require('../../../src/lib/host');
|
||||||
var ConnectionAbstract = require('../../../src/lib/connection');
|
const ConnectionAbstract = require('../../../src/lib/connection');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var EventEmitter = require('events').EventEmitter;
|
const EventEmitter = require('events').EventEmitter;
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
function listenerCount(emitter, event) {
|
function listenerCount(emitter, event) {
|
||||||
if (EventEmitter.listenerCount) {
|
if (EventEmitter.listenerCount) {
|
||||||
@ -19,7 +19,7 @@ function listenerCount(emitter, event) {
|
|||||||
|
|
||||||
describe('Connection Pool', function () {
|
describe('Connection Pool', function () {
|
||||||
describe('Adding/Removing/Syncing Connections', function () {
|
describe('Adding/Removing/Syncing Connections', function () {
|
||||||
var pool, host, connection, host2, connection2;
|
let pool, host, connection, host2, connection2;
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
pool = new ConnectionPool({});
|
pool = new ConnectionPool({});
|
||||||
@ -93,7 +93,7 @@ describe('Connection Pool', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('Connection selection', function () {
|
describe('Connection selection', function () {
|
||||||
var pool, host, host2;
|
let pool, host, host2;
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
pool = new ConnectionPool({});
|
pool = new ConnectionPool({});
|
||||||
@ -135,7 +135,7 @@ describe('Connection Pool', function () {
|
|||||||
return list[0];
|
return list[0];
|
||||||
};
|
};
|
||||||
|
|
||||||
var selected = null;
|
let selected = null;
|
||||||
|
|
||||||
pool.select(function (err, selection) {
|
pool.select(function (err, selection) {
|
||||||
if (err) { throw err; }
|
if (err) { throw err; }
|
||||||
@ -163,20 +163,20 @@ describe('Connection Pool', function () {
|
|||||||
describe('Connection selection with no living nodes', function () {
|
describe('Connection selection with no living nodes', function () {
|
||||||
it('should ping all of the dead nodes, in order of oldest timeout, and return the first that\'s okay',
|
it('should ping all of the dead nodes, in order of oldest timeout, and return the first that\'s okay',
|
||||||
function (done) {
|
function (done) {
|
||||||
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
||||||
stub.autoRelease(clock);
|
stub.autoRelease(clock);
|
||||||
var pool = new ConnectionPool({
|
const pool = new ConnectionPool({
|
||||||
deadTimeout: 10000
|
deadTimeout: 10000
|
||||||
});
|
});
|
||||||
|
|
||||||
var connections = [
|
const connections = [
|
||||||
new ConnectionAbstract(new Host('http://localhost:9200')),
|
new ConnectionAbstract(new Host('http://localhost:9200')),
|
||||||
new ConnectionAbstract(new Host('http://localhost:9201')),
|
new ConnectionAbstract(new Host('http://localhost:9201')),
|
||||||
new ConnectionAbstract(new Host('http://localhost:9202')),
|
new ConnectionAbstract(new Host('http://localhost:9202')),
|
||||||
new ConnectionAbstract(new Host('http://localhost:9203'))
|
new ConnectionAbstract(new Host('http://localhost:9203'))
|
||||||
];
|
];
|
||||||
var pingQueue = _.shuffle(connections);
|
const pingQueue = _.shuffle(connections);
|
||||||
var expectedSelection = pingQueue[pingQueue.length - 1];
|
const expectedSelection = pingQueue[pingQueue.length - 1];
|
||||||
|
|
||||||
_.each(pingQueue, function (conn) {
|
_.each(pingQueue, function (conn) {
|
||||||
pool.addConnection(conn);
|
pool.addConnection(conn);
|
||||||
@ -184,7 +184,7 @@ describe('Connection Pool', function () {
|
|||||||
if (typeof params === 'function') {
|
if (typeof params === 'function') {
|
||||||
cb = params;
|
cb = params;
|
||||||
}
|
}
|
||||||
var expectedConn = pingQueue.shift();
|
const expectedConn = pingQueue.shift();
|
||||||
expect(conn).to.be(expectedConn);
|
expect(conn).to.be(expectedConn);
|
||||||
if (pingQueue.length) {
|
if (pingQueue.length) {
|
||||||
process.nextTick(function () {
|
process.nextTick(function () {
|
||||||
@ -211,7 +211,7 @@ describe('Connection Pool', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('Connection state management', function () {
|
describe('Connection state management', function () {
|
||||||
var pool, host, host2, connection, connection2;
|
let pool, host, host2, connection, connection2;
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
pool = new ConnectionPool({});
|
pool = new ConnectionPool({});
|
||||||
@ -243,12 +243,12 @@ describe('Connection Pool', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('clears and resets the timeout when a connection redies', function () {
|
it('clears and resets the timeout when a connection redies', function () {
|
||||||
var clock = sinon.useFakeTimers();
|
const clock = sinon.useFakeTimers();
|
||||||
stub.autoRelease(clock);
|
stub.autoRelease(clock);
|
||||||
|
|
||||||
connection.setStatus('dead');
|
connection.setStatus('dead');
|
||||||
expect(_.size(clock.timers)).to.eql(1);
|
expect(_.size(clock.timers)).to.eql(1);
|
||||||
var id = _(clock.timers).keys().first();
|
const id = _(clock.timers).keys().first();
|
||||||
|
|
||||||
// it re-dies
|
// it re-dies
|
||||||
connection.setStatus('dead');
|
connection.setStatus('dead');
|
||||||
@ -257,8 +257,8 @@ describe('Connection Pool', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('does nothing when a connection is re-alive', function () {
|
it('does nothing when a connection is re-alive', function () {
|
||||||
var last = pool._conns.alive[pool._conns.alive.length - 1];
|
const last = pool._conns.alive[pool._conns.alive.length - 1];
|
||||||
var first = pool._conns.alive[0];
|
const first = pool._conns.alive[0];
|
||||||
|
|
||||||
expect(last).to.not.be(first);
|
expect(last).to.not.be(first);
|
||||||
|
|
||||||
@ -286,17 +286,17 @@ describe('Connection Pool', function () {
|
|||||||
|
|
||||||
describe('#getConnections', function () {
|
describe('#getConnections', function () {
|
||||||
it('will return all values from the alive list by default', function () {
|
it('will return all values from the alive list by default', function () {
|
||||||
var pool = new ConnectionPool({});
|
const pool = new ConnectionPool({});
|
||||||
pool._conns.alive = new Array(1000);
|
pool._conns.alive = new Array(1000);
|
||||||
var length = pool._conns.alive.length;
|
let length = pool._conns.alive.length;
|
||||||
while (length--) {
|
while (length--) {
|
||||||
pool._conns.alive[length] = length;
|
pool._conns.alive[length] = length;
|
||||||
}
|
}
|
||||||
|
|
||||||
var result = pool.getConnections();
|
const result = pool.getConnections();
|
||||||
expect(result.length).to.be(1000);
|
expect(result.length).to.be(1000);
|
||||||
expect(_.reduce(result, function (sum, num) {
|
expect(_.reduce(result, function (sum, num) {
|
||||||
sum += num
|
sum += num;
|
||||||
return sum;
|
return sum;
|
||||||
}, 0)).to.eql(499500);
|
}, 0)).to.eql(499500);
|
||||||
});
|
});
|
||||||
@ -304,14 +304,14 @@ describe('Connection Pool', function () {
|
|||||||
|
|
||||||
describe('#calcDeadTimeout', function () {
|
describe('#calcDeadTimeout', function () {
|
||||||
it('should be configurable via config.calcDeadTimeout', function () {
|
it('should be configurable via config.calcDeadTimeout', function () {
|
||||||
var pool = new ConnectionPool({
|
const pool = new ConnectionPool({
|
||||||
calcDeadTimeout: 'flat'
|
calcDeadTimeout: 'flat'
|
||||||
});
|
});
|
||||||
expect(pool.calcDeadTimeout).to.be(ConnectionPool.calcDeadTimeoutOptions.flat);
|
expect(pool.calcDeadTimeout).to.be(ConnectionPool.calcDeadTimeoutOptions.flat);
|
||||||
pool.close();
|
pool.close();
|
||||||
});
|
});
|
||||||
it('"flat" always returns the base timeout', function () {
|
it('"flat" always returns the base timeout', function () {
|
||||||
var pool = new ConnectionPool({
|
const pool = new ConnectionPool({
|
||||||
calcDeadTimeout: 'flat'
|
calcDeadTimeout: 'flat'
|
||||||
});
|
});
|
||||||
expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
|
expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
|
||||||
@ -319,7 +319,7 @@ describe('Connection Pool', function () {
|
|||||||
expect(pool.calcDeadTimeout(25, 10000)).to.eql(10000);
|
expect(pool.calcDeadTimeout(25, 10000)).to.eql(10000);
|
||||||
});
|
});
|
||||||
it('"exponential" always increases the timeout based on the attempts', function () {
|
it('"exponential" always increases the timeout based on the attempts', function () {
|
||||||
var pool = new ConnectionPool({
|
const pool = new ConnectionPool({
|
||||||
calcDeadTimeout: 'exponential'
|
calcDeadTimeout: 'exponential'
|
||||||
});
|
});
|
||||||
expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
|
expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
|
||||||
@ -327,7 +327,7 @@ describe('Connection Pool', function () {
|
|||||||
expect(pool.calcDeadTimeout(25, 10000)).to.be.greaterThan(10000);
|
expect(pool.calcDeadTimeout(25, 10000)).to.be.greaterThan(10000);
|
||||||
});
|
});
|
||||||
it('"exponential" produces predicatable results', function () {
|
it('"exponential" produces predicatable results', function () {
|
||||||
var pool = new ConnectionPool({
|
const pool = new ConnectionPool({
|
||||||
calcDeadTimeout: 'exponential'
|
calcDeadTimeout: 'exponential'
|
||||||
});
|
});
|
||||||
expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
|
expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
|
||||||
@ -336,7 +336,7 @@ describe('Connection Pool', function () {
|
|||||||
expect(pool.calcDeadTimeout(25, 30000)).to.eql(18e5);
|
expect(pool.calcDeadTimeout(25, 30000)).to.eql(18e5);
|
||||||
});
|
});
|
||||||
it('"exponential" repects config.maxDeadtimeout', function () {
|
it('"exponential" repects config.maxDeadtimeout', function () {
|
||||||
var pool = new ConnectionPool({
|
const pool = new ConnectionPool({
|
||||||
calcDeadTimeout: 'exponential',
|
calcDeadTimeout: 'exponential',
|
||||||
maxDeadTimeout: 10000
|
maxDeadTimeout: 10000
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
var Log = require('../../../src/lib/log');
|
const Log = require('../../../src/lib/log');
|
||||||
var ConsoleLogger = require('../../../src/lib/loggers/console');
|
const ConsoleLogger = require('../../../src/lib/loggers/console');
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var parentLog;
|
let parentLog;
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
parentLog = new Log();
|
parentLog = new Log();
|
||||||
@ -14,24 +14,24 @@ afterEach(function () {
|
|||||||
|
|
||||||
function makeLogger(parent, levels) {
|
function makeLogger(parent, levels) {
|
||||||
parent = parent || parentLog;
|
parent = parent || parentLog;
|
||||||
var config = {
|
const config = {
|
||||||
levels: Log.parseLevels(levels || 'trace')
|
levels: Log.parseLevels(levels || 'trace')
|
||||||
};
|
};
|
||||||
return new ConsoleLogger(parent, config);
|
return new ConsoleLogger(parent, config);
|
||||||
}
|
}
|
||||||
|
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
describe('Console Logger', function () {
|
describe('Console Logger', function () {
|
||||||
|
|
||||||
require('../generic_logger_tests')(makeLogger);
|
require('../generic_logger_tests')(makeLogger);
|
||||||
|
|
||||||
it('checks before using unique logging functions, falls back to #log()', function () {
|
it('checks before using unique logging functions, falls back to #log()', function () {
|
||||||
var _warning = console.warn;
|
const _warning = console.warn;
|
||||||
console.warn = null;
|
console.warn = null;
|
||||||
sinon.stub(console, 'log');
|
sinon.stub(console, 'log');
|
||||||
|
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
|
|
||||||
logger.onWarning('message');
|
logger.onWarning('message');
|
||||||
expect(console.log.callCount).to.be(1);
|
expect(console.log.callCount).to.be(1);
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
var errors = require('../../../src/lib/errors');
|
const errors = require('../../../src/lib/errors');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
|
|
||||||
_.each(errors, function (CustomError, name) {
|
_.each(errors, function (CustomError, name) {
|
||||||
if (name.charAt(0) !== '_') {
|
if (name.charAt(0) !== '_') {
|
||||||
describe(name, function () {
|
describe(name, function () {
|
||||||
it('extend the ErrorAbstract and Error classes', function () {
|
it('extend the ErrorAbstract and Error classes', function () {
|
||||||
var err = new CustomError();
|
const err = new CustomError();
|
||||||
expect(err).to.be.an(Error);
|
expect(err).to.be.an(Error);
|
||||||
expect(err).to.be.an(errors._Abstract);
|
expect(err).to.be.an(errors._Abstract);
|
||||||
});
|
});
|
||||||
@ -16,9 +16,9 @@ _.each(errors, function (CustomError, name) {
|
|||||||
|
|
||||||
describe('Error Abstract', function () {
|
describe('Error Abstract', function () {
|
||||||
it('provides a stack property in the browser', function () {
|
it('provides a stack property in the browser', function () {
|
||||||
var isBrowser = process.browser;
|
const isBrowser = process.browser;
|
||||||
process.browser = true;
|
process.browser = true;
|
||||||
var err = new errors._Abstract();
|
const err = new errors._Abstract();
|
||||||
process.browser = isBrowser;
|
process.browser = isBrowser;
|
||||||
|
|
||||||
expect(err.stack).to.be.a('string');
|
expect(err.stack).to.be.a('string');
|
||||||
@ -27,7 +27,7 @@ describe('Error Abstract', function () {
|
|||||||
|
|
||||||
describe('StatusCodeError', function () {
|
describe('StatusCodeError', function () {
|
||||||
it('exposes status code as a number', function () {
|
it('exposes status code as a number', function () {
|
||||||
var err = new errors['404']();
|
const err = new errors['404']();
|
||||||
expect(err.status).to.be(404);
|
expect(err.status).to.be(404);
|
||||||
expect(err.status).to.not.be('404');
|
expect(err.status).to.not.be('404');
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,13 +1,13 @@
|
|||||||
describe('File Logger', function () {
|
describe('File Logger', function () {
|
||||||
var Log = require('../../../src/lib/log');
|
const Log = require('../../../src/lib/log');
|
||||||
var FileLogger = require('../../../src/lib/loggers/file');
|
const FileLogger = require('../../../src/lib/loggers/file');
|
||||||
var once = require('events').EventEmitter.prototype.once;
|
const once = require('events').EventEmitter.prototype.once;
|
||||||
var _ = require('../../../src/lib/utils');
|
const _ = require('../../../src/lib/utils');
|
||||||
var parentLog;
|
let parentLog;
|
||||||
var logger;
|
let logger;
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
parentLog = new Log();
|
parentLog = new Log();
|
||||||
@ -36,9 +36,9 @@ describe('File Logger', function () {
|
|||||||
describe('buffer flush', function () {
|
describe('buffer flush', function () {
|
||||||
if (require('stream').Writable) {
|
if (require('stream').Writable) {
|
||||||
it('writes everything in the buffer to console.error', function () {
|
it('writes everything in the buffer to console.error', function () {
|
||||||
var line = 'This string is written 10 times to create buffered output\n';
|
const line = 'This string is written 10 times to create buffered output\n';
|
||||||
|
|
||||||
var exitHandler;
|
let exitHandler;
|
||||||
stub(process, 'once', function (event, handler) {
|
stub(process, 'once', function (event, handler) {
|
||||||
if (event === 'exit') {
|
if (event === 'exit') {
|
||||||
exitHandler = handler;
|
exitHandler = handler;
|
||||||
@ -46,7 +46,7 @@ describe('File Logger', function () {
|
|||||||
once.call(process, event, handler);
|
once.call(process, event, handler);
|
||||||
});
|
});
|
||||||
|
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
|
|
||||||
// write the line 10 times
|
// write the line 10 times
|
||||||
_.times(10, function () {
|
_.times(10, function () {
|
||||||
@ -54,7 +54,7 @@ describe('File Logger', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// collect everything that is written to fs.appendFileSync
|
// collect everything that is written to fs.appendFileSync
|
||||||
var flushedOutput = '';
|
let flushedOutput = '';
|
||||||
stub(fs, 'appendFileSync', function (path, str) {
|
stub(fs, 'appendFileSync', function (path, str) {
|
||||||
flushedOutput += str;
|
flushedOutput += str;
|
||||||
});
|
});
|
||||||
@ -68,7 +68,7 @@ describe('File Logger', function () {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
it('does not fall apart with non streams2 streams', function () {
|
it('does not fall apart with non streams2 streams', function () {
|
||||||
var exitHandler;
|
let exitHandler;
|
||||||
stub(process, 'once', function (event, handler) {
|
stub(process, 'once', function (event, handler) {
|
||||||
if (event === 'exit') {
|
if (event === 'exit') {
|
||||||
exitHandler = handler;
|
exitHandler = handler;
|
||||||
@ -76,7 +76,7 @@ describe('File Logger', function () {
|
|||||||
once.call(process, event, handler);
|
once.call(process, event, handler);
|
||||||
});
|
});
|
||||||
|
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
|
|
||||||
expect(function () {
|
expect(function () {
|
||||||
// call the event handler
|
// call the event handler
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
var Host = require('../../../src/lib/host');
|
const Host = require('../../../src/lib/host');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var url = require('url');
|
const url = require('url');
|
||||||
var expectSubObject = require('../../utils/expect_sub_object');
|
const expectSubObject = require('../../utils/expect_sub_object');
|
||||||
|
|
||||||
var hostDefaults = {
|
const hostDefaults = {
|
||||||
protocol: 'http',
|
protocol: 'http',
|
||||||
host: 'localhost',
|
host: 'localhost',
|
||||||
port: 9200,
|
port: 9200,
|
||||||
@ -24,20 +24,20 @@ var hostDefaults = {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var base64 = function (str) {
|
const base64 = function (str) {
|
||||||
var buffer = Buffer.from ? Buffer.from(str, 'utf8') : new Buffer(str, 'utf8')
|
const buffer = Buffer.from ? Buffer.from(str, 'utf8') : new Buffer(str, 'utf8');
|
||||||
return buffer.toString('base64')
|
return buffer.toString('base64');
|
||||||
}
|
};
|
||||||
|
|
||||||
describe('Host class', function () {
|
describe('Host class', function () {
|
||||||
describe('construction', function () {
|
describe('construction', function () {
|
||||||
it('properly sets the defaults', function () {
|
it('properly sets the defaults', function () {
|
||||||
var host = new Host();
|
const host = new Host();
|
||||||
expect(host).to.eql(hostDefaults);
|
expect(host).to.eql(hostDefaults);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('accepts a string for query', function () {
|
it('accepts a string for query', function () {
|
||||||
var host = new Host({ query: 'beep=boop' });
|
const host = new Host({ query: 'beep=boop' });
|
||||||
|
|
||||||
expect(host.query).to.eql({
|
expect(host.query).to.eql({
|
||||||
beep: 'boop'
|
beep: 'boop'
|
||||||
@ -45,15 +45,15 @@ describe('Host class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('accepts other generic params', function () {
|
it('accepts other generic params', function () {
|
||||||
var headers = { 'X-Special-Routing-Header': 'pie' };
|
const headers = { 'X-Special-Routing-Header': 'pie' };
|
||||||
var host = new Host({ headers: headers });
|
const host = new Host({ headers: headers });
|
||||||
|
|
||||||
expect(host.headers).to.eql(headers);
|
expect(host.headers).to.eql(headers);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('from a string', function () {
|
describe('from a string', function () {
|
||||||
it('accepts a string for the entire url', function () {
|
it('accepts a string for the entire url', function () {
|
||||||
var host = new Host('john:dude@pizza.com:420/pizza/cheese?shrooms=true');
|
const host = new Host('john:dude@pizza.com:420/pizza/cheese?shrooms=true');
|
||||||
|
|
||||||
expectSubObject(host, {
|
expectSubObject(host, {
|
||||||
protocol: 'http',
|
protocol: 'http',
|
||||||
@ -67,7 +67,7 @@ describe('Host class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('uses the default port based on the protocol', function () {
|
it('uses the default port based on the protocol', function () {
|
||||||
var host;
|
let host;
|
||||||
|
|
||||||
host = new Host('https://google.com');
|
host = new Host('https://google.com');
|
||||||
expect(host.port).to.be(443);
|
expect(host.port).to.be(443);
|
||||||
@ -82,7 +82,7 @@ describe('Host class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('parses simple urls properly', function () {
|
it('parses simple urls properly', function () {
|
||||||
var host;
|
let host;
|
||||||
|
|
||||||
host = new Host('localhost');
|
host = new Host('localhost');
|
||||||
expect(host.host).to.be('localhost');
|
expect(host.host).to.be('localhost');
|
||||||
@ -108,19 +108,19 @@ describe('Host class', function () {
|
|||||||
|
|
||||||
describe('based on the output from url.parse', function () {
|
describe('based on the output from url.parse', function () {
|
||||||
it('might cause weird things to happen', function () {
|
it('might cause weird things to happen', function () {
|
||||||
var parsedUrl = url.parse('pizza.com:888');
|
const parsedUrl = url.parse('pizza.com:888');
|
||||||
|
|
||||||
// I imagine most people don't expect
|
// I imagine most people don't expect
|
||||||
expect(parsedUrl.protocol).to.eql('pizza.com:');
|
expect(parsedUrl.protocol).to.eql('pizza.com:');
|
||||||
expect(parsedUrl.host).to.eql('888');
|
expect(parsedUrl.host).to.eql('888');
|
||||||
|
|
||||||
var host = new Host(parsedUrl);
|
const host = new Host(parsedUrl);
|
||||||
expect(host.protocol).to.eql('pizza.com');
|
expect(host.protocol).to.eql('pizza.com');
|
||||||
expect(host.host).to.eql('888');
|
expect(host.host).to.eql('888');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('will cause extra properties', function () {
|
it('will cause extra properties', function () {
|
||||||
var host = new Host(url.parse('https://joe:diner@pizza.com:888/path?query=yes#section'));
|
const host = new Host(url.parse('https://joe:diner@pizza.com:888/path?query=yes#section'));
|
||||||
expect(host.protocol).to.eql('https');
|
expect(host.protocol).to.eql('https');
|
||||||
expect(host.host).to.eql('pizza.com');
|
expect(host.host).to.eql('pizza.com');
|
||||||
expect(host.port).to.eql(888);
|
expect(host.port).to.eql(888);
|
||||||
@ -135,13 +135,13 @@ describe('Host class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('ignores anything that\'s not a string or object-y', function () {
|
it('ignores anything that\'s not a string or object-y', function () {
|
||||||
var host = new Host(1234);
|
const host = new Host(1234);
|
||||||
|
|
||||||
expect(host).to.eql(hostDefaults);
|
expect(host).to.eql(hostDefaults);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('defaults auth values from the `httpAuth` setting', function () {
|
it('defaults auth values from the `httpAuth` setting', function () {
|
||||||
var host = new Host('http://localhost:9200', {
|
const host = new Host('http://localhost:9200', {
|
||||||
httpAuth: 'username:password'
|
httpAuth: 'username:password'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -151,7 +151,7 @@ describe('Host class', function () {
|
|||||||
|
|
||||||
describe('#makeUrl', function () {
|
describe('#makeUrl', function () {
|
||||||
it('merges parameters', function () {
|
it('merges parameters', function () {
|
||||||
var host = new Host({
|
const host = new Host({
|
||||||
path: '/prefix',
|
path: '/prefix',
|
||||||
query: {
|
query: {
|
||||||
user_id: 123
|
user_id: 123
|
||||||
@ -167,7 +167,7 @@ describe('Host class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('ensures that path starts with a forward-slash', function () {
|
it('ensures that path starts with a forward-slash', function () {
|
||||||
var host = new Host();
|
const host = new Host();
|
||||||
host.path = 'prefix';
|
host.path = 'prefix';
|
||||||
|
|
||||||
expect(host.makeUrl({ path: '/this and that' }))
|
expect(host.makeUrl({ path: '/this and that' }))
|
||||||
@ -175,14 +175,14 @@ describe('Host class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('does not try to prevent double forward-slashes', function () {
|
it('does not try to prevent double forward-slashes', function () {
|
||||||
var host = new Host({ path: 'prefix/' });
|
const host = new Host({ path: 'prefix/' });
|
||||||
|
|
||||||
expect(host.makeUrl({ path: '/this and that' }))
|
expect(host.makeUrl({ path: '/this and that' }))
|
||||||
.to.be('http://localhost:9200/prefix//this and that');
|
.to.be('http://localhost:9200/prefix//this and that');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('creates proper url without any params', function () {
|
it('creates proper url without any params', function () {
|
||||||
var host = new Host({});
|
let host = new Host({});
|
||||||
expect(host.makeUrl()).to.be('http://localhost:9200/');
|
expect(host.makeUrl()).to.be('http://localhost:9200/');
|
||||||
|
|
||||||
host = new Host({ host: 'john', port: 80 });
|
host = new Host({ host: 'john', port: 80 });
|
||||||
@ -193,7 +193,7 @@ describe('Host class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('outputs valid relative urls when the host is empty', function () {
|
it('outputs valid relative urls when the host is empty', function () {
|
||||||
var host = new Host({
|
const host = new Host({
|
||||||
host: false,
|
host: false,
|
||||||
path: '/path',
|
path: '/path',
|
||||||
query: { this: 'that' }
|
query: { this: 'that' }
|
||||||
@ -205,7 +205,7 @@ describe('Host class', function () {
|
|||||||
|
|
||||||
describe('#toString', function () {
|
describe('#toString', function () {
|
||||||
it('produces the same output as makeUrl when it is called without params', function () {
|
it('produces the same output as makeUrl when it is called without params', function () {
|
||||||
var host = new Host({
|
const host = new Host({
|
||||||
path: '/pasta',
|
path: '/pasta',
|
||||||
host: 'google.com'
|
host: 'google.com'
|
||||||
});
|
});
|
||||||
@ -216,7 +216,7 @@ describe('Host class', function () {
|
|||||||
|
|
||||||
describe('#getHeaders', function () {
|
describe('#getHeaders', function () {
|
||||||
it('merges the passed in headers with the default headers', function () {
|
it('merges the passed in headers with the default headers', function () {
|
||||||
var host = new Host({ headers: { 'Joe-Smith': 'present' } });
|
const host = new Host({ headers: { 'Joe-Smith': 'present' } });
|
||||||
|
|
||||||
expect(host.getHeaders({
|
expect(host.getHeaders({
|
||||||
'John-Smith': 'present'
|
'John-Smith': 'present'
|
||||||
@ -227,7 +227,7 @@ describe('Host class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('overrides the default headers with the passed in headers', function () {
|
it('overrides the default headers with the passed in headers', function () {
|
||||||
var host = new Host({ headers: { 'Joe-Smith': 'present' } });
|
const host = new Host({ headers: { 'Joe-Smith': 'present' } });
|
||||||
|
|
||||||
expect(host.getHeaders({
|
expect(host.getHeaders({
|
||||||
'John-Smith': 'present',
|
'John-Smith': 'present',
|
||||||
@ -239,7 +239,7 @@ describe('Host class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('adds Accept-Encoding header when the suggestCompression setting is true', function () {
|
it('adds Accept-Encoding header when the suggestCompression setting is true', function () {
|
||||||
var host = new Host({ suggestCompression: true });
|
const host = new Host({ suggestCompression: true });
|
||||||
expect(host.getHeaders()).to.eql({
|
expect(host.getHeaders()).to.eql({
|
||||||
'Accept-Encoding': 'gzip,deflate'
|
'Accept-Encoding': 'gzip,deflate'
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,32 +1,32 @@
|
|||||||
describe('Http Connector', function () {
|
describe('Http Connector', function () {
|
||||||
|
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var nock = require('nock');
|
const nock = require('nock');
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var util = require('util');
|
const util = require('util');
|
||||||
var parseUrl = require('url').parse;
|
const parseUrl = require('url').parse;
|
||||||
var http = require('http');
|
const http = require('http');
|
||||||
var https = require('https');
|
const https = require('https');
|
||||||
var AgentKeepAlive = require('agentkeepalive');
|
const AgentKeepAlive = require('agentkeepalive');
|
||||||
|
|
||||||
var Host = require('../../../src/lib/host');
|
const Host = require('../../../src/lib/host');
|
||||||
var errors = require('../../../src/lib/errors');
|
const errors = require('../../../src/lib/errors');
|
||||||
var HttpConnection = require('../../../src/lib/connectors/http');
|
const HttpConnection = require('../../../src/lib/connectors/http');
|
||||||
var ConnectionAbstract = require('../../../src/lib/connection');
|
const ConnectionAbstract = require('../../../src/lib/connection');
|
||||||
|
|
||||||
var expectSubObject = require('../../utils/expect_sub_object');
|
const expectSubObject = require('../../utils/expect_sub_object');
|
||||||
var MockRequest = require('../../mocks/request');
|
const MockRequest = require('../../mocks/request');
|
||||||
var MockIncommingMessage = require('../../mocks/incomming_message');
|
const MockIncommingMessage = require('../../mocks/incomming_message');
|
||||||
var zlib = require('zlib');
|
const zlib = require('zlib');
|
||||||
|
|
||||||
nock.disableNetConnect();
|
nock.disableNetConnect();
|
||||||
|
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
function makeStubReqMethod(prep) {
|
function makeStubReqMethod(prep) {
|
||||||
return function (params, cb) {
|
return function (params, cb) {
|
||||||
var req = new MockRequest();
|
const req = new MockRequest();
|
||||||
if (prep) {
|
if (prep) {
|
||||||
prep(req, params, cb);
|
prep(req, params, cb);
|
||||||
}
|
}
|
||||||
@ -45,12 +45,12 @@ describe('Http Connector', function () {
|
|||||||
|
|
||||||
describe('Constructor', function () {
|
describe('Constructor', function () {
|
||||||
it('creates an object that extends ConnectionAbstract', function () {
|
it('creates an object that extends ConnectionAbstract', function () {
|
||||||
var con = new HttpConnection(new Host());
|
const con = new HttpConnection(new Host());
|
||||||
expect(con).to.be.a(ConnectionAbstract);
|
expect(con).to.be.a(ConnectionAbstract);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sets certain defaults', function () {
|
it('sets certain defaults', function () {
|
||||||
var con = new HttpConnection(new Host());
|
const con = new HttpConnection(new Host());
|
||||||
|
|
||||||
expect(con.hand).to.be(require('http'));
|
expect(con.hand).to.be(require('http'));
|
||||||
// con.requestTimeout
|
// con.requestTimeout
|
||||||
@ -62,27 +62,27 @@ describe('Http Connector', function () {
|
|||||||
|
|
||||||
it('expects the host to have a protocol of http or https', function () {
|
it('expects the host to have a protocol of http or https', function () {
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var con = new HttpConnection(new Host('thrifty://es.com/stuff'));
|
const con = new HttpConnection(new Host('thrifty://es.com/stuff'));
|
||||||
}).to.throwError(/invalid protocol/i);
|
}).to.throwError(/invalid protocol/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('allows defining a custom agent', function () {
|
it('allows defining a custom agent', function () {
|
||||||
var football = {};
|
const football = {};
|
||||||
var con = new HttpConnection(new Host(), { createNodeAgent: _.constant(football) });
|
const con = new HttpConnection(new Host(), { createNodeAgent: _.constant(football) });
|
||||||
expect(con.agent).to.be(football);
|
expect(con.agent).to.be(football);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('allows setting agent to false', function () {
|
it('allows setting agent to false', function () {
|
||||||
var con = new HttpConnection(new Host(), { createNodeAgent: _.constant(false) });
|
const con = new HttpConnection(new Host(), { createNodeAgent: _.constant(false) });
|
||||||
expect(con.agent).to.be(false);
|
expect(con.agent).to.be(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('#makeReqParams', function () {
|
describe('#makeReqParams', function () {
|
||||||
it('properly reads the host object', function () {
|
it('properly reads the host object', function () {
|
||||||
var host = new Host('john:dude@pizza.com:9200/pizza/cheese?shrooms=true');
|
const host = new Host('john:dude@pizza.com:9200/pizza/cheese?shrooms=true');
|
||||||
var con = new HttpConnection(host, {});
|
const con = new HttpConnection(host, {});
|
||||||
var reqParams = con.makeReqParams();
|
const reqParams = con.makeReqParams();
|
||||||
|
|
||||||
expect(reqParams).to.not.have.property('auth');
|
expect(reqParams).to.not.have.property('auth');
|
||||||
expect(reqParams).to.eql({
|
expect(reqParams).to.eql({
|
||||||
@ -97,13 +97,13 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('merges a query object with the hosts\'', function () {
|
it('merges a query object with the hosts\'', function () {
|
||||||
var con = new HttpConnection(new Host({
|
const con = new HttpConnection(new Host({
|
||||||
query: {
|
query: {
|
||||||
user_id: 123
|
user_id: 123
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
|
||||||
var reqParams = con.makeReqParams({
|
const reqParams = con.makeReqParams({
|
||||||
query: {
|
query: {
|
||||||
jvm: 'yes'
|
jvm: 'yes'
|
||||||
}
|
}
|
||||||
@ -113,8 +113,8 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('merges the path prefix', function () {
|
it('merges the path prefix', function () {
|
||||||
var con = new HttpConnection(new Host('https://google.com/path/prefix/for/user/1'));
|
const con = new HttpConnection(new Host('https://google.com/path/prefix/for/user/1'));
|
||||||
var reqParams = con.makeReqParams({
|
const reqParams = con.makeReqParams({
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
path: '/items',
|
path: '/items',
|
||||||
query: {
|
query: {
|
||||||
@ -128,9 +128,9 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('merges the query', function () {
|
it('merges the query', function () {
|
||||||
var con = new HttpConnection(new Host('http://google.com/pref-x?userId=12345&token=42069'));
|
const con = new HttpConnection(new Host('http://google.com/pref-x?userId=12345&token=42069'));
|
||||||
|
|
||||||
var reqParams = con.makeReqParams({
|
const reqParams = con.makeReqParams({
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
path: '/stuff',
|
path: '/stuff',
|
||||||
query: {
|
query: {
|
||||||
@ -144,9 +144,9 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Works well with minimum params', function () {
|
it('Works well with minimum params', function () {
|
||||||
var con = new HttpConnection(new Host('http://google.com'));
|
const con = new HttpConnection(new Host('http://google.com'));
|
||||||
|
|
||||||
var reqParams = con.makeReqParams({
|
const reqParams = con.makeReqParams({
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
path: '/stuff'
|
path: '/stuff'
|
||||||
});
|
});
|
||||||
@ -170,7 +170,7 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('calls http based on the host', function (done) {
|
it('calls http based on the host', function (done) {
|
||||||
var con = new HttpConnection(new Host('http://google.com'));
|
const con = new HttpConnection(new Host('http://google.com'));
|
||||||
con.request({}, function () {
|
con.request({}, function () {
|
||||||
expect(http.request.callCount).to.be(1);
|
expect(http.request.callCount).to.be(1);
|
||||||
expect(https.request.callCount).to.be(0);
|
expect(https.request.callCount).to.be(0);
|
||||||
@ -180,7 +180,7 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('calls https based on the host', function (done) {
|
it('calls https based on the host', function (done) {
|
||||||
var con = new HttpConnection(new Host('https://google.com'));
|
const con = new HttpConnection(new Host('https://google.com'));
|
||||||
con.request({}, function () {
|
con.request({}, function () {
|
||||||
expect(http.request.callCount).to.be(0);
|
expect(http.request.callCount).to.be(0);
|
||||||
expect(https.request.callCount).to.be(1);
|
expect(https.request.callCount).to.be(1);
|
||||||
@ -190,7 +190,7 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('does not log error events', function (done) {
|
it('does not log error events', function (done) {
|
||||||
var con = new HttpConnection(new Host('http://google.com'));
|
const con = new HttpConnection(new Host('http://google.com'));
|
||||||
|
|
||||||
stub(con.log, 'error');
|
stub(con.log, 'error');
|
||||||
stub(con.log, 'trace');
|
stub(con.log, 'trace');
|
||||||
@ -217,7 +217,7 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('logs error events', function (done) {
|
it('logs error events', function (done) {
|
||||||
var con = new HttpConnection(new Host('http://google.com'));
|
const con = new HttpConnection(new Host('http://google.com'));
|
||||||
|
|
||||||
stub(con.log, 'error');
|
stub(con.log, 'error');
|
||||||
|
|
||||||
@ -238,7 +238,7 @@ describe('Http Connector', function () {
|
|||||||
function makeStubReqWithMsgWhichErrorsMidBody(err) {
|
function makeStubReqWithMsgWhichErrorsMidBody(err) {
|
||||||
return makeStubReqMethod(function (req, params, cb) {
|
return makeStubReqMethod(function (req, params, cb) {
|
||||||
process.nextTick(function () {
|
process.nextTick(function () {
|
||||||
var incom = new MockIncommingMessage();
|
const incom = new MockIncommingMessage();
|
||||||
incom.statusCode = 200;
|
incom.statusCode = 200;
|
||||||
setTimeout(function () {
|
setTimeout(function () {
|
||||||
incom.emit('data', '{ "not json"');
|
incom.emit('data', '{ "not json"');
|
||||||
@ -250,7 +250,7 @@ describe('Http Connector', function () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
it('does not log errors', function (done) {
|
it('does not log errors', function (done) {
|
||||||
var con = new HttpConnection(new Host('https://google.com'));
|
const con = new HttpConnection(new Host('https://google.com'));
|
||||||
stub(con.log, 'error');
|
stub(con.log, 'error');
|
||||||
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
|
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
|
||||||
|
|
||||||
@ -261,7 +261,7 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('passes the original error on', function (done) {
|
it('passes the original error on', function (done) {
|
||||||
var con = new HttpConnection(new Host('https://google.com'));
|
const con = new HttpConnection(new Host('https://google.com'));
|
||||||
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody(new Error('no more message :(')));
|
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody(new Error('no more message :(')));
|
||||||
|
|
||||||
con.request({}, function (err, resp, status) {
|
con.request({}, function (err, resp, status) {
|
||||||
@ -272,7 +272,7 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('does not pass the partial body along', function (done) {
|
it('does not pass the partial body along', function (done) {
|
||||||
var con = new HttpConnection(new Host('https://google.com'));
|
const con = new HttpConnection(new Host('https://google.com'));
|
||||||
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
|
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
|
||||||
|
|
||||||
con.request({}, function (err, resp, status) {
|
con.request({}, function (err, resp, status) {
|
||||||
@ -282,7 +282,7 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('does not pass the status code along', function (done) {
|
it('does not pass the status code along', function (done) {
|
||||||
var con = new HttpConnection(new Host('https://google.com'));
|
const con = new HttpConnection(new Host('https://google.com'));
|
||||||
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
|
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
|
||||||
|
|
||||||
con.request({}, function (err, resp, status) {
|
con.request({}, function (err, resp, status) {
|
||||||
@ -294,9 +294,9 @@ describe('Http Connector', function () {
|
|||||||
|
|
||||||
describe('#request\'s responder', function () {
|
describe('#request\'s responder', function () {
|
||||||
it('collects the whole request body', function (done) {
|
it('collects the whole request body', function (done) {
|
||||||
var server = nock('http://esjs.com:9200');
|
const server = nock('http://esjs.com:9200');
|
||||||
var con = new HttpConnection(new Host('http://esjs.com:9200'));
|
const con = new HttpConnection(new Host('http://esjs.com:9200'));
|
||||||
var body = '{ "USER": "doc" }';
|
const body = '{ "USER": "doc" }';
|
||||||
|
|
||||||
server
|
server
|
||||||
.get('/users/1')
|
.get('/users/1')
|
||||||
@ -315,13 +315,13 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('collects the whole request body (gzip compressed)', function (done) {
|
it('collects the whole request body (gzip compressed)', function (done) {
|
||||||
var server = nock('http://esjs.com:9200');
|
const server = nock('http://esjs.com:9200');
|
||||||
var con = new HttpConnection(new Host('http://esjs.com:9200'));
|
const con = new HttpConnection(new Host('http://esjs.com:9200'));
|
||||||
var elements = [];
|
const elements = [];
|
||||||
for (var i = 0; i < 500; i++) {
|
for (let i = 0; i < 500; i++) {
|
||||||
elements.push({ USER: 'doc' });
|
elements.push({ USER: 'doc' });
|
||||||
}
|
}
|
||||||
var body = JSON.stringify(elements);
|
const body = JSON.stringify(elements);
|
||||||
zlib.gzip(body, function (err, compressedBody) {
|
zlib.gzip(body, function (err, compressedBody) {
|
||||||
server
|
server
|
||||||
.get('/users/1')
|
.get('/users/1')
|
||||||
@ -341,13 +341,13 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('collects the whole request body (deflate compressed)', function (done) {
|
it('collects the whole request body (deflate compressed)', function (done) {
|
||||||
var server = nock('http://esjs.com:9200');
|
const server = nock('http://esjs.com:9200');
|
||||||
var con = new HttpConnection(new Host('http://esjs.com:9200'));
|
const con = new HttpConnection(new Host('http://esjs.com:9200'));
|
||||||
var elements = [];
|
const elements = [];
|
||||||
for (var i = 0; i < 500; i++) {
|
for (let i = 0; i < 500; i++) {
|
||||||
elements.push({ USER: 'doc' });
|
elements.push({ USER: 'doc' });
|
||||||
}
|
}
|
||||||
var body = JSON.stringify(elements);
|
const body = JSON.stringify(elements);
|
||||||
zlib.deflate(body, function (err, compressedBody) {
|
zlib.deflate(body, function (err, compressedBody) {
|
||||||
server
|
server
|
||||||
.get('/users/1')
|
.get('/users/1')
|
||||||
@ -367,9 +367,9 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Can handle decompression errors', function (done) {
|
it('Can handle decompression errors', function (done) {
|
||||||
var server = nock('http://esjs.com:9200');
|
const server = nock('http://esjs.com:9200');
|
||||||
var con = new HttpConnection(new Host('http://esjs.com:9200'));
|
const con = new HttpConnection(new Host('http://esjs.com:9200'));
|
||||||
var body = 'blah';
|
const body = 'blah';
|
||||||
server
|
server
|
||||||
.get('/users/1')
|
.get('/users/1')
|
||||||
.reply(200, body, { 'Content-Encoding': 'gzip' });
|
.reply(200, body, { 'Content-Encoding': 'gzip' });
|
||||||
@ -387,9 +387,9 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Ignores serialization errors', function (done) {
|
it('Ignores serialization errors', function (done) {
|
||||||
var server = nock('http://esjs.com:9200');
|
const server = nock('http://esjs.com:9200');
|
||||||
var con = new HttpConnection(new Host('http://esjs.com:9200'));
|
const con = new HttpConnection(new Host('http://esjs.com:9200'));
|
||||||
var body = '{ "USER":';
|
const body = '{ "USER":';
|
||||||
|
|
||||||
// partial body
|
// partial body
|
||||||
server
|
server
|
||||||
@ -410,9 +410,9 @@ describe('Http Connector', function () {
|
|||||||
|
|
||||||
describe('HTTP specifics', function () {
|
describe('HTTP specifics', function () {
|
||||||
it('uses TCP no delay', function (done) {
|
it('uses TCP no delay', function (done) {
|
||||||
var con = new HttpConnection(new Host('localhost'));
|
const con = new HttpConnection(new Host('localhost'));
|
||||||
stub(http.ClientRequest.prototype, 'setNoDelay');
|
stub(http.ClientRequest.prototype, 'setNoDelay');
|
||||||
var server = nock('http://localhost').get('/').reply(200);
|
const server = nock('http://localhost').get('/').reply(200);
|
||||||
|
|
||||||
con.request({}, function (err, resp, status) {
|
con.request({}, function (err, resp, status) {
|
||||||
expect(http.ClientRequest.prototype.setNoDelay.callCount).to.eql(1);
|
expect(http.ClientRequest.prototype.setNoDelay.callCount).to.eql(1);
|
||||||
@ -423,11 +423,11 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('sets the Content-Length header properly', function (done) {
|
it('sets the Content-Length header properly', function (done) {
|
||||||
var con = new HttpConnection(new Host('localhost'));
|
const con = new HttpConnection(new Host('localhost'));
|
||||||
stub(http.ClientRequest.prototype, 'setHeader');
|
stub(http.ClientRequest.prototype, 'setHeader');
|
||||||
var server = nock('http://localhost').get('/').reply(200);
|
const server = nock('http://localhost').get('/').reply(200);
|
||||||
|
|
||||||
var body = 'pasta and 𝄞';
|
const body = 'pasta and 𝄞';
|
||||||
expect(body.length).to.eql(12); // nope
|
expect(body.length).to.eql(12); // nope
|
||||||
expect(Buffer.byteLength(body, 'utf8')).to.eql(14); // yep
|
expect(Buffer.byteLength(body, 'utf8')).to.eql(14); // yep
|
||||||
|
|
||||||
@ -441,9 +441,9 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('does not set the Accept-Encoding header by default', function (done) {
|
it('does not set the Accept-Encoding header by default', function (done) {
|
||||||
var con = new HttpConnection(new Host());
|
const con = new HttpConnection(new Host());
|
||||||
var respBody = 'i should not be encoded';
|
const respBody = 'i should not be encoded';
|
||||||
var server = nock('http://localhost:9200')
|
const server = nock('http://localhost:9200')
|
||||||
.matchHeader('accept-encoding', undefined)
|
.matchHeader('accept-encoding', undefined)
|
||||||
.get('/')
|
.get('/')
|
||||||
.once()
|
.once()
|
||||||
@ -457,9 +457,9 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('sets the Accept-Encoding header when specified', function (done) {
|
it('sets the Accept-Encoding header when specified', function (done) {
|
||||||
var con = new HttpConnection(new Host({ suggestCompression: true }));
|
const con = new HttpConnection(new Host({ suggestCompression: true }));
|
||||||
var respBody = 'i should be encoded';
|
const respBody = 'i should be encoded';
|
||||||
var server = nock('http://localhost:9200')
|
const server = nock('http://localhost:9200')
|
||||||
.matchHeader('accept-encoding', 'gzip,deflate')
|
.matchHeader('accept-encoding', 'gzip,deflate')
|
||||||
.get('/')
|
.get('/')
|
||||||
.once()
|
.once()
|
||||||
@ -476,12 +476,12 @@ describe('Http Connector', function () {
|
|||||||
describe('Connection cleanup', function () {
|
describe('Connection cleanup', function () {
|
||||||
it('destroys any connections created', function (done) {
|
it('destroys any connections created', function (done) {
|
||||||
this.timeout(5 * 60 * 1000);
|
this.timeout(5 * 60 * 1000);
|
||||||
var cp = require('child_process');
|
const cp = require('child_process');
|
||||||
var path = require('path');
|
const path = require('path');
|
||||||
var fixture = _.partial(path.join, __dirname, '../../fixtures');
|
const fixture = _.partial(path.join, __dirname, '../../fixtures');
|
||||||
var timeout; // start the timeout once we hear back from the client
|
let timeout; // start the timeout once we hear back from the client
|
||||||
|
|
||||||
var server = cp.fork(fixture('keepalive_server.js'))
|
const server = cp.fork(fixture('keepalive_server.js'))
|
||||||
.on('message', function (port) {
|
.on('message', function (port) {
|
||||||
client.send(port);
|
client.send(port);
|
||||||
});
|
});
|
||||||
@ -507,8 +507,8 @@ describe('Http Connector', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('properly removes all elements from the socket', function () {
|
it('properly removes all elements from the socket', function () {
|
||||||
var con = new HttpConnection(new Host('localhost'));
|
const con = new HttpConnection(new Host('localhost'));
|
||||||
var sockets = [
|
const sockets = [
|
||||||
{ destroy: function () {} },
|
{ destroy: function () {} },
|
||||||
{ destroy: function () {} },
|
{ destroy: function () {} },
|
||||||
{ destroy: function () {} },
|
{ destroy: function () {} },
|
||||||
@ -520,7 +520,7 @@ describe('Http Connector', function () {
|
|||||||
{ destroy: function () {} },
|
{ destroy: function () {} },
|
||||||
{ destroy: function () {} }
|
{ destroy: function () {} }
|
||||||
];
|
];
|
||||||
var name = con.agent.getName(parseUrl('http://localhost/'));
|
const name = con.agent.getName(parseUrl('http://localhost/'));
|
||||||
con.agent.sockets[name] = sockets;
|
con.agent.sockets[name] = sockets;
|
||||||
con.setStatus('closed');
|
con.setStatus('closed');
|
||||||
expect(sockets).to.eql([]);
|
expect(sockets).to.eql([]);
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
describe('JSON serializer', function () {
|
describe('JSON serializer', function () {
|
||||||
var JsonSerializer = require('../../../src/lib/serializers/json');
|
const JsonSerializer = require('../../../src/lib/serializers/json');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
function makeSerializer() {
|
function makeSerializer() {
|
||||||
return new JsonSerializer();
|
return new JsonSerializer();
|
||||||
@ -10,29 +10,29 @@ describe('JSON serializer', function () {
|
|||||||
|
|
||||||
describe('#serialize', function () {
|
describe('#serialize', function () {
|
||||||
it('defers to JSON.stringify', function () {
|
it('defers to JSON.stringify', function () {
|
||||||
var stub = sinon.stub(JSON, 'stringify');
|
const stub = sinon.stub(JSON, 'stringify');
|
||||||
var ser = makeSerializer();
|
const ser = makeSerializer();
|
||||||
ser.serialize({ some: 'object' });
|
ser.serialize({ some: 'object' });
|
||||||
expect(stub.callCount).to.eql(1);
|
expect(stub.callCount).to.eql(1);
|
||||||
stub.restore();
|
stub.restore();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('does not modify strings', function () {
|
it('does not modify strings', function () {
|
||||||
var ser = makeSerializer();
|
const ser = makeSerializer();
|
||||||
var thing = 'pretend that I am serialized';
|
const thing = 'pretend that I am serialized';
|
||||||
expect(ser.serialize(thing)).to.be(thing);
|
expect(ser.serialize(thing)).to.be(thing);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('returns nothing for invalid values', function () {
|
it('returns nothing for invalid values', function () {
|
||||||
var ser = makeSerializer();
|
const ser = makeSerializer();
|
||||||
|
|
||||||
expect(ser.serialize(null)).to.be(undefined);
|
expect(ser.serialize(null)).to.be(undefined);
|
||||||
expect(ser.serialize(false)).to.be(undefined);
|
expect(ser.serialize(false)).to.be(undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('throws serialization errors', function () {
|
it('throws serialization errors', function () {
|
||||||
var ser = makeSerializer();
|
const ser = makeSerializer();
|
||||||
var thing = { name: 'thing' };
|
const thing = { name: 'thing' };
|
||||||
thing.self = thing;
|
thing.self = thing;
|
||||||
|
|
||||||
expect(function () {
|
expect(function () {
|
||||||
@ -44,46 +44,46 @@ describe('JSON serializer', function () {
|
|||||||
describe('#deserialize', function () {
|
describe('#deserialize', function () {
|
||||||
it('defers to JSON.parse', function () {
|
it('defers to JSON.parse', function () {
|
||||||
stub(JSON, 'parse');
|
stub(JSON, 'parse');
|
||||||
var ser = makeSerializer();
|
const ser = makeSerializer();
|
||||||
ser.deserialize('{ "some": "JSON" }');
|
ser.deserialize('{ "some": "JSON" }');
|
||||||
expect(JSON.parse.callCount).to.eql(1);
|
expect(JSON.parse.callCount).to.eql(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('ignores non string values', function () {
|
it('ignores non string values', function () {
|
||||||
var ser = makeSerializer();
|
const ser = makeSerializer();
|
||||||
var thing = ['pretend that I am not here'];
|
const thing = ['pretend that I am not here'];
|
||||||
expect(ser.deserialize(thing)).to.be(undefined);
|
expect(ser.deserialize(thing)).to.be(undefined);
|
||||||
expect(ser.deserialize(null)).to.be(undefined);
|
expect(ser.deserialize(null)).to.be(undefined);
|
||||||
expect(ser.deserialize(false)).to.be(undefined);
|
expect(ser.deserialize(false)).to.be(undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('catches serialization errors, returns nothing', function () {
|
it('catches serialization errors, returns nothing', function () {
|
||||||
var ser = makeSerializer();
|
const ser = makeSerializer();
|
||||||
var thing = '{ name: \'thing\' }';
|
const thing = '{ name: \'thing\' }';
|
||||||
|
|
||||||
expect(ser.deserialize(thing)).to.be(undefined);
|
expect(ser.deserialize(thing)).to.be(undefined);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('#bulkBody', function () {
|
describe('#bulkBody', function () {
|
||||||
var body = [
|
const body = [
|
||||||
{ index: 'thing' },
|
{ index: 'thing' },
|
||||||
{ document: 'hi' }
|
{ document: 'hi' }
|
||||||
];
|
];
|
||||||
var bulk = '{"index":"thing"}\n{"document":"hi"}\n';
|
const bulk = '{"index":"thing"}\n{"document":"hi"}\n';
|
||||||
|
|
||||||
it('creates a string out of an array of obejcts', function () {
|
it('creates a string out of an array of obejcts', function () {
|
||||||
var ser = makeSerializer();
|
const ser = makeSerializer();
|
||||||
expect(ser.bulkBody(body)).to.eql(bulk);
|
expect(ser.bulkBody(body)).to.eql(bulk);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('adds a newline to the end of strings', function () {
|
it('adds a newline to the end of strings', function () {
|
||||||
var ser = makeSerializer();
|
const ser = makeSerializer();
|
||||||
expect(ser.bulkBody(bulk.substr(0, bulk.length - 1))).to.eql(bulk);
|
expect(ser.bulkBody(bulk.substr(0, bulk.length - 1))).to.eql(bulk);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('throws an error for anything else', function () {
|
it('throws an error for anything else', function () {
|
||||||
var ser = makeSerializer();
|
const ser = makeSerializer();
|
||||||
expect(function () {
|
expect(function () {
|
||||||
ser.bulkBody({});
|
ser.bulkBody({});
|
||||||
}).to.throwError();
|
}).to.throwError();
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
var Log = require('../../../src/lib/log');
|
const Log = require('../../../src/lib/log');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
|
|
||||||
describe('Log class', function () {
|
describe('Log class', function () {
|
||||||
describe('::parseLevels', function () {
|
describe('::parseLevels', function () {
|
||||||
@ -32,7 +32,7 @@ describe('Log class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('#addOutput', function () {
|
describe('#addOutput', function () {
|
||||||
var log;
|
let log;
|
||||||
|
|
||||||
Log.loggers.stub = function (log, config) {
|
Log.loggers.stub = function (log, config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
@ -47,7 +47,7 @@ describe('Log class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Accepts a config object with `level: "{{level}}"`', function () {
|
it('Accepts a config object with `level: "{{level}}"`', function () {
|
||||||
var logger = log.addOutput({
|
const logger = log.addOutput({
|
||||||
type: 'stub',
|
type: 'stub',
|
||||||
level: 'warning'
|
level: 'warning'
|
||||||
});
|
});
|
||||||
@ -58,7 +58,7 @@ describe('Log class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Accepts a config object with `level: ["{{level}}"]`', function () {
|
it('Accepts a config object with `level: ["{{level}}"]`', function () {
|
||||||
var logger = log.addOutput({
|
const logger = log.addOutput({
|
||||||
type: 'stub',
|
type: 'stub',
|
||||||
level: ['warning']
|
level: ['warning']
|
||||||
});
|
});
|
||||||
@ -70,7 +70,7 @@ describe('Log class', function () {
|
|||||||
|
|
||||||
|
|
||||||
it('Accepts a config object with `levels: "{{level}}"`', function () {
|
it('Accepts a config object with `levels: "{{level}}"`', function () {
|
||||||
var logger = log.addOutput({
|
const logger = log.addOutput({
|
||||||
type: 'stub',
|
type: 'stub',
|
||||||
levels: 'warning'
|
levels: 'warning'
|
||||||
});
|
});
|
||||||
@ -81,7 +81,7 @@ describe('Log class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Accepts a config object with `levels: ["{{level}}"]`', function () {
|
it('Accepts a config object with `levels: ["{{level}}"]`', function () {
|
||||||
var logger = log.addOutput({
|
const logger = log.addOutput({
|
||||||
type: 'stub',
|
type: 'stub',
|
||||||
level: ['warning']
|
level: ['warning']
|
||||||
});
|
});
|
||||||
@ -101,14 +101,14 @@ describe('Log class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('fully stringifies deeply nested objects', function () {
|
it('fully stringifies deeply nested objects', function () {
|
||||||
var object = { foo: { bar: { baz: 'value' } } };
|
const object = { foo: { bar: { baz: 'value' } } };
|
||||||
var expected = '{\n "bar": {\n "baz": "value"\n }\n}\n';
|
const expected = '{\n "bar": {\n "baz": "value"\n }\n}\n';
|
||||||
expect(Log.join(object)).to.eql(expected);
|
expect(Log.join(object)).to.eql(expected);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('instance without any outputs', function () {
|
describe('instance without any outputs', function () {
|
||||||
var log;
|
let log;
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
log = new Log();
|
log = new Log();
|
||||||
});
|
});
|
||||||
@ -128,7 +128,7 @@ describe('Log class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('instance without one output listening to all events', function () {
|
describe('instance without one output listening to all events', function () {
|
||||||
var log, call;
|
let log, call;
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
call = void 0;
|
call = void 0;
|
||||||
log = new Log({
|
log = new Log({
|
||||||
@ -154,7 +154,7 @@ describe('Log class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should emit an "error" event with an Error object arg', function () {
|
it('should emit an "error" event with an Error object arg', function () {
|
||||||
var err = new Error('error');
|
const err = new Error('error');
|
||||||
log.error(err);
|
log.error(err);
|
||||||
expect(call.event).to.eql('error');
|
expect(call.event).to.eql('error');
|
||||||
expect(call.args[0]).to.be(err);
|
expect(call.args[0]).to.be(err);
|
||||||
@ -200,7 +200,7 @@ describe('Log class', function () {
|
|||||||
|
|
||||||
describe('constructor', function () {
|
describe('constructor', function () {
|
||||||
it('looks for output config options at config.log', function () {
|
it('looks for output config options at config.log', function () {
|
||||||
var log = new Log({ log: { type: process.browser ? 'console' : 'stdio', level: 'error' } });
|
const log = new Log({ log: { type: process.browser ? 'console' : 'stdio', level: 'error' } });
|
||||||
expect(log.listenerCount('error')).to.eql(1);
|
expect(log.listenerCount('error')).to.eql(1);
|
||||||
expect(log.listenerCount('warning')).to.eql(0);
|
expect(log.listenerCount('warning')).to.eql(0);
|
||||||
expect(log.listenerCount('info')).to.eql(0);
|
expect(log.listenerCount('info')).to.eql(0);
|
||||||
@ -209,7 +209,7 @@ describe('Log class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('accepts a string and treat it as a log level', function () {
|
it('accepts a string and treat it as a log level', function () {
|
||||||
var log = new Log({ log: 'error' });
|
const log = new Log({ log: 'error' });
|
||||||
expect(log.listenerCount('error')).to.eql(1);
|
expect(log.listenerCount('error')).to.eql(1);
|
||||||
expect(log.listenerCount('warning')).to.eql(0);
|
expect(log.listenerCount('warning')).to.eql(0);
|
||||||
expect(log.listenerCount('info')).to.eql(0);
|
expect(log.listenerCount('info')).to.eql(0);
|
||||||
@ -218,7 +218,7 @@ describe('Log class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('accepts an array of strings and treat it as a log level config', function () {
|
it('accepts an array of strings and treat it as a log level config', function () {
|
||||||
var log = new Log({ log: ['error', 'trace'] });
|
const log = new Log({ log: ['error', 'trace'] });
|
||||||
expect(log.listenerCount('error')).to.eql(1);
|
expect(log.listenerCount('error')).to.eql(1);
|
||||||
expect(log.listenerCount('warning')).to.eql(0);
|
expect(log.listenerCount('warning')).to.eql(0);
|
||||||
expect(log.listenerCount('info')).to.eql(0);
|
expect(log.listenerCount('info')).to.eql(0);
|
||||||
@ -227,7 +227,7 @@ describe('Log class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('accepts an array of output config objects', function () {
|
it('accepts an array of output config objects', function () {
|
||||||
var log = new Log({ log: [{ level: 'error' }, { level: 'trace' }] });
|
const log = new Log({ log: [{ level: 'error' }, { level: 'trace' }] });
|
||||||
expect(log.listenerCount('error')).to.eql(2);
|
expect(log.listenerCount('error')).to.eql(2);
|
||||||
expect(log.listenerCount('warning')).to.eql(1);
|
expect(log.listenerCount('warning')).to.eql(1);
|
||||||
expect(log.listenerCount('info')).to.eql(1);
|
expect(log.listenerCount('info')).to.eql(1);
|
||||||
@ -237,22 +237,22 @@ describe('Log class', function () {
|
|||||||
|
|
||||||
it('rejects numbers and other truthy data-types', function () {
|
it('rejects numbers and other truthy data-types', function () {
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var log = new Log({ log: 1515 });
|
const log = new Log({ log: 1515 });
|
||||||
}).to.throwError(/invalid logging output config/i);
|
}).to.throwError(/invalid logging output config/i);
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var log = new Log({ log: /regexp/ });
|
const log = new Log({ log: /regexp/ });
|
||||||
}).to.throwError(/invalid logging output config/i);
|
}).to.throwError(/invalid logging output config/i);
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var log = new Log({ log: new Date() });
|
const log = new Log({ log: new Date() });
|
||||||
}).to.throwError(/invalid logging output config/i);
|
}).to.throwError(/invalid logging output config/i);
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var log = new Log({ log: [1515] });
|
const log = new Log({ log: [1515] });
|
||||||
}).to.throwError(/invalid logging output config/i);
|
}).to.throwError(/invalid logging output config/i);
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var log = new Log({ log: [/regexp/] });
|
const log = new Log({ log: [/regexp/] });
|
||||||
}).to.throwError(/invalid logging output config/i);
|
}).to.throwError(/invalid logging output config/i);
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var log = new Log({ log: [new Date()] });
|
const log = new Log({ log: [new Date()] });
|
||||||
}).to.throwError(/invalid logging output config/i);
|
}).to.throwError(/invalid logging output config/i);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
describe('Nodes to host callback', function () {
|
describe('Nodes to host callback', function () {
|
||||||
var callback = require('../../../src/lib/nodes_to_host');
|
const callback = require('../../../src/lib/nodes_to_host');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
|
|
||||||
var nodes90 = require('../../fixtures/short_node_list.0.90.json');
|
const nodes90 = require('../../fixtures/short_node_list.0.90.json');
|
||||||
var nodes10 = require('../../fixtures/short_node_list.1.0.json');
|
const nodes10 = require('../../fixtures/short_node_list.1.0.json');
|
||||||
var nodes20 = require('../../fixtures/short_node_list.2.0.json');
|
const nodes20 = require('../../fixtures/short_node_list.2.0.json');
|
||||||
var nodes50 = require('../../fixtures/short_node_list.5.0.json');
|
const nodes50 = require('../../fixtures/short_node_list.5.0.json');
|
||||||
|
|
||||||
context('0.x style', function () {
|
context('0.x style', function () {
|
||||||
it('properly creates host objects', function () {
|
it('properly creates host objects', function () {
|
||||||
@ -109,7 +109,7 @@ describe('Nodes to host callback', function () {
|
|||||||
|
|
||||||
|
|
||||||
it('ignores hosts that don\'t have an http_host property', function () {
|
it('ignores hosts that don\'t have an http_host property', function () {
|
||||||
var hosts = callback({
|
const hosts = callback({
|
||||||
node_id: {
|
node_id: {
|
||||||
not: 'much of a node'
|
not: 'much of a node'
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,14 +1,14 @@
|
|||||||
describe('Random Selector', function () {
|
describe('Random Selector', function () {
|
||||||
var randomSelector = require('../../../src/lib/selectors/random');
|
const randomSelector = require('../../../src/lib/selectors/random');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
|
|
||||||
it('chooses a selection by random', function () {
|
it('chooses a selection by random', function () {
|
||||||
var log = { a: 0, b: 0, c: 0 };
|
const log = { a: 0, b: 0, c: 0 };
|
||||||
var choices = _.keys(log);
|
const choices = _.keys(log);
|
||||||
|
|
||||||
_.times(1000, function () {
|
_.times(1000, function () {
|
||||||
var choice = randomSelector(choices);
|
const choice = randomSelector(choices);
|
||||||
log[choice]++;
|
log[choice]++;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
describe('Round Robin Selector', function () {
|
describe('Round Robin Selector', function () {
|
||||||
var selector = require('../../../src/lib/selectors/round_robin');
|
const selector = require('../../../src/lib/selectors/round_robin');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
|
|
||||||
it('chooses options in order', function () {
|
it('chooses options in order', function () {
|
||||||
var options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
|
const options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
|
||||||
var expected = _.clone(options);
|
const expected = _.clone(options);
|
||||||
var selections = [];
|
const selections = [];
|
||||||
|
|
||||||
_.times(options.length, function () {
|
_.times(options.length, function () {
|
||||||
selections.push(selector(options));
|
selections.push(selector(options));
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
describe('Stdio Logger', function () {
|
describe('Stdio Logger', function () {
|
||||||
|
|
||||||
var Log = require('../../../src/lib/log');
|
const Log = require('../../../src/lib/log');
|
||||||
var StdioLogger = require('../../../src/lib/loggers/stdio');
|
const StdioLogger = require('../../../src/lib/loggers/stdio');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var parentLog;
|
let parentLog;
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
parentLog = new Log();
|
parentLog = new Log();
|
||||||
@ -16,37 +16,37 @@ describe('Stdio Logger', function () {
|
|||||||
|
|
||||||
function makeLogger(parent, levels) {
|
function makeLogger(parent, levels) {
|
||||||
parent = parent || parentLog;
|
parent = parent || parentLog;
|
||||||
var config = {
|
const config = {
|
||||||
levels: Log.parseLevels(levels || 'trace')
|
levels: Log.parseLevels(levels || 'trace')
|
||||||
};
|
};
|
||||||
return new StdioLogger(parent, config);
|
return new StdioLogger(parent, config);
|
||||||
}
|
}
|
||||||
|
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
require('../generic_logger_tests')(makeLogger);
|
require('../generic_logger_tests')(makeLogger);
|
||||||
|
|
||||||
describe('colorizing', function () {
|
describe('colorizing', function () {
|
||||||
var chalk = require('chalk');
|
const chalk = require('chalk');
|
||||||
var now = '2013-01-01T00:00:00Z';
|
const now = '2013-01-01T00:00:00Z';
|
||||||
var nowDate = new Date(now);
|
const nowDate = new Date(now);
|
||||||
var nowTime = nowDate.getTime();
|
const nowTime = nowDate.getTime();
|
||||||
var clock;
|
let clock;
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
stub.autoRelease(sinon.useFakeTimers(nowTime));
|
stub.autoRelease(sinon.useFakeTimers(nowTime));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uses colors when it\'s supported', function () {
|
it('uses colors when it\'s supported', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
var hasColor = require('chalk').supportsColor;
|
const hasColor = require('chalk').supportsColor;
|
||||||
expect(logger.color).to.be(hasColor);
|
expect(logger.color).to.be(hasColor);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('obeys the logger.color === false', function () {
|
it('obeys the logger.color === false', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
stub(process.stdout, 'write');
|
stub(process.stdout, 'write');
|
||||||
var withoutColor = 'Elasticsearch INFO: ' + now + '\n something\n\n';
|
const withoutColor = 'Elasticsearch INFO: ' + now + '\n something\n\n';
|
||||||
|
|
||||||
logger.color = false;
|
logger.color = false;
|
||||||
logger.onInfo('something');
|
logger.onInfo('something');
|
||||||
@ -54,10 +54,10 @@ describe('Stdio Logger', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('obeys the logger.color === true', function () {
|
it('obeys the logger.color === true', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
|
|
||||||
stub(process.stdout, 'write');
|
stub(process.stdout, 'write');
|
||||||
var withoutColor = 'Elasticsearch DEBUG: ' + now + '\n be weary\n\n';
|
const withoutColor = 'Elasticsearch DEBUG: ' + now + '\n be weary\n\n';
|
||||||
|
|
||||||
logger.color = true;
|
logger.color = true;
|
||||||
logger.onDebug('be weary');
|
logger.onDebug('be weary');
|
||||||
|
|||||||
@ -1,14 +1,14 @@
|
|||||||
describe('Stream Logger', function () {
|
describe('Stream Logger', function () {
|
||||||
var Log = require('../../../src/lib/log');
|
const Log = require('../../../src/lib/log');
|
||||||
var StreamLogger = require('../../../src/lib/loggers/stream');
|
const StreamLogger = require('../../../src/lib/loggers/stream');
|
||||||
var MockWritableStream = require('../../mocks/writable_stream');
|
const MockWritableStream = require('../../mocks/writable_stream');
|
||||||
var once = require('events').EventEmitter.prototype.once;
|
const once = require('events').EventEmitter.prototype.once;
|
||||||
var stream = new MockWritableStream();
|
const stream = new MockWritableStream();
|
||||||
var _ = require('../../../src/lib/utils');
|
const _ = require('../../../src/lib/utils');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var parentLog;
|
let parentLog;
|
||||||
|
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
stub(stream, 'write');
|
stub(stream, 'write');
|
||||||
@ -24,7 +24,7 @@ describe('Stream Logger', function () {
|
|||||||
|
|
||||||
function makeLogger(parent, levels) {
|
function makeLogger(parent, levels) {
|
||||||
parent = parent || parentLog;
|
parent = parent || parentLog;
|
||||||
var config = {
|
const config = {
|
||||||
levels: Log.parseLevels(levels || 'trace'),
|
levels: Log.parseLevels(levels || 'trace'),
|
||||||
stream: stream
|
stream: stream
|
||||||
};
|
};
|
||||||
@ -36,12 +36,12 @@ describe('Stream Logger', function () {
|
|||||||
describe('buffer flush', function () {
|
describe('buffer flush', function () {
|
||||||
if (require('stream').Writable) {
|
if (require('stream').Writable) {
|
||||||
it('writes everything in the buffer to console.error', function () {
|
it('writes everything in the buffer to console.error', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
var line = 'This string is written 10 times to create buffered output\n';
|
const line = 'This string is written 10 times to create buffered output\n';
|
||||||
|
|
||||||
// get the last handler for process's "exit" event
|
// get the last handler for process's "exit" event
|
||||||
var exitHandlers = process._events.exit;
|
const exitHandlers = process._events.exit;
|
||||||
var exitHandler = _.isArray(exitHandlers) ? _.last(exitHandlers) : exitHandlers;
|
const exitHandler = _.isArray(exitHandlers) ? _.last(exitHandlers) : exitHandlers;
|
||||||
|
|
||||||
// allow the logger to acctually write to the stream
|
// allow the logger to acctually write to the stream
|
||||||
stream.write.restore();
|
stream.write.restore();
|
||||||
@ -52,7 +52,7 @@ describe('Stream Logger', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// collect everything that is written to console.error
|
// collect everything that is written to console.error
|
||||||
var flushedOutput = '';
|
let flushedOutput = '';
|
||||||
stub(console, 'error', function (str) {
|
stub(console, 'error', function (str) {
|
||||||
flushedOutput += str;
|
flushedOutput += str;
|
||||||
});
|
});
|
||||||
@ -69,7 +69,7 @@ describe('Stream Logger', function () {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
it('does not fall apart with non streams2 streams', function () {
|
it('does not fall apart with non streams2 streams', function () {
|
||||||
var exitHandler;
|
let exitHandler;
|
||||||
stub(process, 'once', function (event, handler) {
|
stub(process, 'once', function (event, handler) {
|
||||||
if (event === 'exit') {
|
if (event === 'exit') {
|
||||||
exitHandler = handler;
|
exitHandler = handler;
|
||||||
@ -77,7 +77,7 @@ describe('Stream Logger', function () {
|
|||||||
once.call(process, event, handler);
|
once.call(process, event, handler);
|
||||||
});
|
});
|
||||||
|
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
|
|
||||||
expect(function () {
|
expect(function () {
|
||||||
// call the event handler
|
// call the event handler
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
describe('Tracer Logger', function () {
|
describe('Tracer Logger', function () {
|
||||||
|
|
||||||
var Log = require('../../../src/lib/log');
|
const Log = require('../../../src/lib/log');
|
||||||
var TracerLogger = require('../../../src/lib/loggers/tracer');
|
const TracerLogger = require('../../../src/lib/loggers/tracer');
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var parentLog;
|
let parentLog;
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
parentLog = new Log();
|
parentLog = new Log();
|
||||||
@ -16,21 +16,21 @@ describe('Tracer Logger', function () {
|
|||||||
|
|
||||||
function makeLogger(parent, levels) {
|
function makeLogger(parent, levels) {
|
||||||
parent = parent || parentLog;
|
parent = parent || parentLog;
|
||||||
var config = {
|
const config = {
|
||||||
levels: Log.parseLevels(levels || 'trace')
|
levels: Log.parseLevels(levels || 'trace')
|
||||||
};
|
};
|
||||||
return new TracerLogger(parent, config);
|
return new TracerLogger(parent, config);
|
||||||
}
|
}
|
||||||
|
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
// require('../generic_logger_tests')(makeLogger);
|
// require('../generic_logger_tests')(makeLogger);
|
||||||
|
|
||||||
describe('#formatTraceMessage', function () {
|
describe('#formatTraceMessage', function () {
|
||||||
it('includes the original host', function () {
|
it('includes the original host', function () {
|
||||||
var logger = makeLogger();
|
const logger = makeLogger();
|
||||||
|
|
||||||
var formatted = logger._formatTraceMessage({
|
const formatted = logger._formatTraceMessage({
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
url: 'https://originalHost.com:9522/path/to/thing?qs=100',
|
url: 'https://originalHost.com:9522/path/to/thing?qs=100',
|
||||||
body: '{ "yes": true }',
|
body: '{ "yes": true }',
|
||||||
@ -45,7 +45,7 @@ describe('Tracer Logger', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('#write', function () {
|
describe('#write', function () {
|
||||||
var logger;
|
let logger;
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
logger = makeLogger();
|
logger = makeLogger();
|
||||||
stub(logger.stream, 'write');
|
stub(logger.stream, 'write');
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
var Transport = require('../../../src/lib/transport');
|
const Transport = require('../../../src/lib/transport');
|
||||||
var Host = require('../../../src/lib/host');
|
const Host = require('../../../src/lib/host');
|
||||||
var errors = require('../../../src/lib/errors');
|
const errors = require('../../../src/lib/errors');
|
||||||
|
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var nodeList = require('../../fixtures/short_node_list.5.0.json');
|
const nodeList = require('../../fixtures/short_node_list.5.0.json');
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Allows the tests call #request() without it doing anything past trying to select
|
* Allows the tests call #request() without it doing anything past trying to select
|
||||||
@ -31,7 +31,7 @@ describe('Transport Class', function () {
|
|||||||
describe('Constructor', function () {
|
describe('Constructor', function () {
|
||||||
it('Accepts a log class and intanciates it at this.log', function () {
|
it('Accepts a log class and intanciates it at this.log', function () {
|
||||||
function CustomLogClass() {}
|
function CustomLogClass() {}
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
log: CustomLogClass
|
log: CustomLogClass
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -39,7 +39,7 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Accepts a connection pool class and intanciates it at this.connectionPool', function () {
|
it('Accepts a connection pool class and intanciates it at this.connectionPool', function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
connectionPool: CustomConnectionPool
|
connectionPool: CustomConnectionPool
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -49,7 +49,7 @@ describe('Transport Class', function () {
|
|||||||
it('Accepts the name of a connectionPool class that is defined on Transport.connectionPools', function () {
|
it('Accepts the name of a connectionPool class that is defined on Transport.connectionPools', function () {
|
||||||
Transport.connectionPools.custom = CustomConnectionPool;
|
Transport.connectionPools.custom = CustomConnectionPool;
|
||||||
|
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
connectionPool: 'custom'
|
connectionPool: 'custom'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -59,7 +59,7 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
it('Throws an error when connectionPool config is set wrong', function () {
|
it('Throws an error when connectionPool config is set wrong', function () {
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
connectionPool: 'pasta'
|
connectionPool: 'pasta'
|
||||||
});
|
});
|
||||||
}).to.throwError(/invalid connectionpool/i);
|
}).to.throwError(/invalid connectionpool/i);
|
||||||
@ -67,7 +67,7 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
it('calls sniff immediately if sniffOnStart is true', function () {
|
it('calls sniff immediately if sniffOnStart is true', function () {
|
||||||
stub(Transport.prototype, 'sniff');
|
stub(Transport.prototype, 'sniff');
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
sniffOnStart: true
|
sniffOnStart: true
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -75,16 +75,16 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('schedules a sniff when sniffInterval is set', function () {
|
it('schedules a sniff when sniffInterval is set', function () {
|
||||||
var clock = sinon.useFakeTimers('setTimeout');
|
const clock = sinon.useFakeTimers('setTimeout');
|
||||||
stub.autoRelease(clock);
|
stub.autoRelease(clock);
|
||||||
stub(Transport.prototype, 'sniff');
|
stub(Transport.prototype, 'sniff');
|
||||||
|
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
sniffInterval: 25000
|
sniffInterval: 25000
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(_.size(clock.timers)).to.eql(1);
|
expect(_.size(clock.timers)).to.eql(1);
|
||||||
var id = _.keys(clock.timers).pop();
|
const id = _.keys(clock.timers).pop();
|
||||||
clock.tick(25000);
|
clock.tick(25000);
|
||||||
expect(trans.sniff.callCount).to.eql(1);
|
expect(trans.sniff.callCount).to.eql(1);
|
||||||
expect(_.size(clock.timers)).to.eql(1);
|
expect(_.size(clock.timers)).to.eql(1);
|
||||||
@ -94,15 +94,15 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
describe('config.sniffedNodesProtocol', function () {
|
describe('config.sniffedNodesProtocol', function () {
|
||||||
it('Assigns to itself', function () {
|
it('Assigns to itself', function () {
|
||||||
var football = {};
|
const football = {};
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
sniffedNodesProtocol: football
|
sniffedNodesProtocol: football
|
||||||
});
|
});
|
||||||
expect(trans).to.have.property('sniffedNodesProtocol', football);
|
expect(trans).to.have.property('sniffedNodesProtocol', football);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Defaults to null when no hosts given', function () {
|
it('Defaults to null when no hosts given', function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: []
|
hosts: []
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -110,7 +110,7 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Defaults to "http" when a single http host given', function () {
|
it('Defaults to "http" when a single http host given', function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: [
|
hosts: [
|
||||||
new Host({
|
new Host({
|
||||||
protocol: 'http'
|
protocol: 'http'
|
||||||
@ -122,7 +122,7 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Defaults to "http" when multiple http host given', function () {
|
it('Defaults to "http" when multiple http host given', function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: [
|
hosts: [
|
||||||
new Host(),
|
new Host(),
|
||||||
'http://google.com',
|
'http://google.com',
|
||||||
@ -137,7 +137,7 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Defaults to "https" when a single https host given', function () {
|
it('Defaults to "https" when a single https host given', function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
host: {
|
host: {
|
||||||
protocol: 'https'
|
protocol: 'https'
|
||||||
}
|
}
|
||||||
@ -147,7 +147,7 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('Defaults to "https" when every seed host uses https', function () {
|
it('Defaults to "https" when every seed host uses https', function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: [
|
hosts: [
|
||||||
'https://localhost:9200',
|
'https://localhost:9200',
|
||||||
new Host({
|
new Host({
|
||||||
@ -166,7 +166,7 @@ describe('Transport Class', function () {
|
|||||||
describe('host config', function () {
|
describe('host config', function () {
|
||||||
it('rejects non-strings/objects', function () {
|
it('rejects non-strings/objects', function () {
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
host: [
|
host: [
|
||||||
'localhost',
|
'localhost',
|
||||||
9393
|
9393
|
||||||
@ -175,7 +175,7 @@ describe('Transport Class', function () {
|
|||||||
}).to.throwError(TypeError);
|
}).to.throwError(TypeError);
|
||||||
|
|
||||||
expect(function () {
|
expect(function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
host: [
|
host: [
|
||||||
[9292]
|
[9292]
|
||||||
]
|
]
|
||||||
@ -185,7 +185,7 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
it('accepts the config value on the host: key', function () {
|
it('accepts the config value on the host: key', function () {
|
||||||
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
host: 'localhost'
|
host: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -197,7 +197,7 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
it('accepts the config value on the hosts: key', function () {
|
it('accepts the config value on the hosts: key', function () {
|
||||||
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -209,8 +209,8 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
it('accepts A host object as the config', function () {
|
it('accepts A host object as the config', function () {
|
||||||
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
||||||
var h = new Host('localhost');
|
const h = new Host('localhost');
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
host: h
|
host: h
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -220,7 +220,7 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
it('accepts strings as the config', function () {
|
it('accepts strings as the config', function () {
|
||||||
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: [
|
hosts: [
|
||||||
'localhost:8888',
|
'localhost:8888',
|
||||||
]
|
]
|
||||||
@ -237,7 +237,7 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
it('accepts objects as the config', function () {
|
it('accepts objects as the config', function () {
|
||||||
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: [
|
hosts: [
|
||||||
{
|
{
|
||||||
protocol: 'https',
|
protocol: 'https',
|
||||||
@ -262,13 +262,13 @@ describe('Transport Class', function () {
|
|||||||
// check that it's getting the suggestCompression setting
|
// check that it's getting the suggestCompression setting
|
||||||
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
||||||
|
|
||||||
var trans = new Transport({
|
let trans = new Transport({
|
||||||
suggestCompression: true,
|
suggestCompression: true,
|
||||||
hosts: ['localhost:9200']
|
hosts: ['localhost:9200']
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(trans.connectionPool.setHosts).to.have.property('callCount', 1);
|
expect(trans.connectionPool.setHosts).to.have.property('callCount', 1);
|
||||||
var hosts = trans.connectionPool.setHosts.firstCall.args[0];
|
let hosts = trans.connectionPool.setHosts.firstCall.args[0];
|
||||||
expect(hosts).to.have.length(1);
|
expect(hosts).to.have.length(1);
|
||||||
expect(hosts[0]).to.have.property('suggestCompression', true);
|
expect(hosts[0]).to.have.property('suggestCompression', true);
|
||||||
|
|
||||||
@ -285,20 +285,20 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
describe('randomizeHosts options', function () {
|
describe('randomizeHosts options', function () {
|
||||||
it('calls _.shuffle be default', function () {
|
it('calls _.shuffle be default', function () {
|
||||||
var _ = require('../../../src/lib/utils');
|
const _ = require('../../../src/lib/utils');
|
||||||
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
||||||
stub(_, 'shuffle');
|
stub(_, 'shuffle');
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(_.shuffle.callCount).to.eql(1);
|
expect(_.shuffle.callCount).to.eql(1);
|
||||||
});
|
});
|
||||||
it('skips the call to _.shuffle when false', function () {
|
it('skips the call to _.shuffle when false', function () {
|
||||||
var _ = require('../../../src/lib/utils');
|
const _ = require('../../../src/lib/utils');
|
||||||
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
stub(Transport.connectionPools.main.prototype, 'setHosts');
|
||||||
stub(_, 'shuffle');
|
stub(_, 'shuffle');
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost',
|
hosts: 'localhost',
|
||||||
randomizeHosts: false
|
randomizeHosts: false
|
||||||
});
|
});
|
||||||
@ -310,7 +310,7 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
describe('#defer', function () {
|
describe('#defer', function () {
|
||||||
it('returns a custom defer object', function () {
|
it('returns a custom defer object', function () {
|
||||||
var defer = Transport.prototype.defer();
|
const defer = Transport.prototype.defer();
|
||||||
expect(defer).to.have.property('promise');
|
expect(defer).to.have.property('promise');
|
||||||
expect(defer).to.have.property('resolve');
|
expect(defer).to.have.property('resolve');
|
||||||
expect(defer).to.have.property('reject');
|
expect(defer).to.have.property('reject');
|
||||||
@ -319,7 +319,7 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
|
|
||||||
describe('#sniff', function () {
|
describe('#sniff', function () {
|
||||||
var trans;
|
let trans;
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
trans = new Transport({ suggestCompression: true });
|
trans = new Transport({ suggestCompression: true });
|
||||||
@ -366,7 +366,7 @@ describe('Transport Class', function () {
|
|||||||
function (done) {
|
function (done) {
|
||||||
trans.sniff(function () {
|
trans.sniff(function () {
|
||||||
expect(trans.connectionPool.setHosts.callCount).to.eql(1);
|
expect(trans.connectionPool.setHosts.callCount).to.eql(1);
|
||||||
var hosts = trans.connectionPool.setHosts.lastCall.args[0];
|
const hosts = trans.connectionPool.setHosts.lastCall.args[0];
|
||||||
|
|
||||||
expect(hosts).to.have.length(2);
|
expect(hosts).to.have.length(2);
|
||||||
|
|
||||||
@ -386,7 +386,7 @@ describe('Transport Class', function () {
|
|||||||
// check that it's getting the suggestCompression setting
|
// check that it's getting the suggestCompression setting
|
||||||
trans.sniff(function () {
|
trans.sniff(function () {
|
||||||
expect(trans.connectionPool.setHosts).to.have.property('callCount', 1);
|
expect(trans.connectionPool.setHosts).to.have.property('callCount', 1);
|
||||||
var hosts = trans.connectionPool.setHosts.lastCall.args[0];
|
const hosts = trans.connectionPool.setHosts.lastCall.args[0];
|
||||||
expect(hosts).to.have.length(2);
|
expect(hosts).to.have.length(2);
|
||||||
expect(hosts[0]).to.have.property('suggestCompression', true);
|
expect(hosts[0]).to.have.property('suggestCompression', true);
|
||||||
expect(hosts[1]).to.have.property('suggestCompression', true);
|
expect(hosts[1]).to.have.property('suggestCompression', true);
|
||||||
@ -423,7 +423,7 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
describe('#request', function () {
|
describe('#request', function () {
|
||||||
it('logs when it begins', function (done) {
|
it('logs when it begins', function (done) {
|
||||||
var trans = new Transport();
|
const trans = new Transport();
|
||||||
stub(trans.log, 'debug');
|
stub(trans.log, 'debug');
|
||||||
stub(trans.connectionPool, 'select', function (cb) {
|
stub(trans.connectionPool, 'select', function (cb) {
|
||||||
// simulate "no connections"
|
// simulate "no connections"
|
||||||
@ -437,7 +437,7 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('rejects GET requests with a body (callback)', function (done) {
|
it('rejects GET requests with a body (callback)', function (done) {
|
||||||
var trans = new Transport();
|
const trans = new Transport();
|
||||||
stub(trans.log, 'debug');
|
stub(trans.log, 'debug');
|
||||||
stub(trans.connectionPool, 'select', function (cb) {
|
stub(trans.connectionPool, 'select', function (cb) {
|
||||||
// simulate "no connections"
|
// simulate "no connections"
|
||||||
@ -454,7 +454,7 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('rejects GET requests with a body (promise)', function (done) {
|
it('rejects GET requests with a body (promise)', function (done) {
|
||||||
var trans = new Transport();
|
const trans = new Transport();
|
||||||
stub(trans.log, 'debug');
|
stub(trans.log, 'debug');
|
||||||
stub(trans.connectionPool, 'select', function (cb) {
|
stub(trans.connectionPool, 'select', function (cb) {
|
||||||
// simulate "no connections"
|
// simulate "no connections"
|
||||||
@ -475,11 +475,11 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
describe('gets a body', function () {
|
describe('gets a body', function () {
|
||||||
it('serializes it', function (done) {
|
it('serializes it', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
var conn = getConnection(trans);
|
const conn = getConnection(trans);
|
||||||
var body = {
|
const body = {
|
||||||
_id: 'simple body',
|
_id: 'simple body',
|
||||||
name: 'ഢധയമബ'
|
name: 'ഢധയമബ'
|
||||||
};
|
};
|
||||||
@ -495,11 +495,11 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
it('serializes bulk bodies', function (done) {
|
it('serializes bulk bodies', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
var conn = getConnection(trans);
|
const conn = getConnection(trans);
|
||||||
var body = [
|
const body = [
|
||||||
{ _id: 'simple body' },
|
{ _id: 'simple body' },
|
||||||
{ name: 'ഢധയമബ' }
|
{ name: 'ഢധയമബ' }
|
||||||
];
|
];
|
||||||
@ -522,11 +522,11 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
describe('gets a body it cant serialize', function () {
|
describe('gets a body it cant serialize', function () {
|
||||||
it('throws an error', function () {
|
it('throws an error', function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
getConnection(trans);
|
getConnection(trans);
|
||||||
var body = {
|
const body = {
|
||||||
_id: 'circular body'
|
_id: 'circular body'
|
||||||
};
|
};
|
||||||
body.body = body;
|
body.body = body;
|
||||||
@ -541,7 +541,7 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
describe('when selecting a connection', function () {
|
describe('when selecting a connection', function () {
|
||||||
it('logs a warning, and responds with NoConnection when it receives nothing', function (done) {
|
it('logs a warning, and responds with NoConnection when it receives nothing', function (done) {
|
||||||
var trans = new Transport();
|
const trans = new Transport();
|
||||||
stub(trans.log, 'warning');
|
stub(trans.log, 'warning');
|
||||||
trans.request({}, function (err, body, status) {
|
trans.request({}, function (err, body, status) {
|
||||||
expect(trans.log.warning.callCount).to.eql(1);
|
expect(trans.log.warning.callCount).to.eql(1);
|
||||||
@ -552,7 +552,7 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
it('quits if a sync selector throws an error', function () {
|
it('quits if a sync selector throws an error', function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost',
|
hosts: 'localhost',
|
||||||
selector: function () {
|
selector: function () {
|
||||||
throw new Error('I am broken');
|
throw new Error('I am broken');
|
||||||
@ -564,7 +564,7 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
it('quits if gets an error from an async selector', function () {
|
it('quits if gets an error from an async selector', function () {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost',
|
hosts: 'localhost',
|
||||||
selector: function (connections, cb) {
|
selector: function (connections, cb) {
|
||||||
process.nextTick(function () {
|
process.nextTick(function () {
|
||||||
@ -578,10 +578,10 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
it('calls connection#request once it gets one', function (done) {
|
it('calls connection#request once it gets one', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
var conn = getConnection(trans);
|
const conn = getConnection(trans);
|
||||||
|
|
||||||
stub(conn, 'request', function () {
|
stub(conn, 'request', function () {
|
||||||
done();
|
done();
|
||||||
@ -595,9 +595,9 @@ describe('Transport Class', function () {
|
|||||||
// create a test that checks N retries
|
// create a test that checks N retries
|
||||||
function testRetries(retries) {
|
function testRetries(retries) {
|
||||||
return function (done) {
|
return function (done) {
|
||||||
var randomSelector = require('../../../src/lib/selectors/random');
|
const randomSelector = require('../../../src/lib/selectors/random');
|
||||||
var connections;
|
let connections;
|
||||||
var attempts = 0;
|
let attempts = 0;
|
||||||
function failRequest(params, cb) {
|
function failRequest(params, cb) {
|
||||||
attempts++;
|
attempts++;
|
||||||
process.nextTick(function () {
|
process.nextTick(function () {
|
||||||
@ -605,7 +605,7 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: _.map(new Array(retries + 1), function (val, i) {
|
hosts: _.map(new Array(retries + 1), function (val, i) {
|
||||||
return 'localhost/' + i;
|
return 'localhost/' + i;
|
||||||
}),
|
}),
|
||||||
@ -639,24 +639,24 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
describe('return value', function () {
|
describe('return value', function () {
|
||||||
it('returns an object with an abort() method when a callback is sent', function () {
|
it('returns an object with an abort() method when a callback is sent', function () {
|
||||||
var tran = new Transport();
|
const tran = new Transport();
|
||||||
shortCircuitRequest(tran);
|
shortCircuitRequest(tran);
|
||||||
var ret = tran.request({}, _.noop);
|
const ret = tran.request({}, _.noop);
|
||||||
expect(ret).to.be.a('object');
|
expect(ret).to.be.a('object');
|
||||||
expect(ret.abort).to.be.a('function');
|
expect(ret.abort).to.be.a('function');
|
||||||
});
|
});
|
||||||
it('the object is a promise when a callback is not suplied', function () {
|
it('the object is a promise when a callback is not suplied', function () {
|
||||||
var tran = new Transport();
|
const tran = new Transport();
|
||||||
shortCircuitRequest(tran);
|
shortCircuitRequest(tran);
|
||||||
var ret = tran.request({});
|
const ret = tran.request({});
|
||||||
expect(ret.then).to.be.a('function');
|
expect(ret.then).to.be.a('function');
|
||||||
expect(ret.abort).to.be.a('function');
|
expect(ret.abort).to.be.a('function');
|
||||||
ret.then(_.noop, _.noop); // prevent complaining from bluebird
|
ret.then(_.noop, _.noop); // prevent complaining from bluebird
|
||||||
});
|
});
|
||||||
it('promise is always pulled from the defer created by this.defer()', function () {
|
it('promise is always pulled from the defer created by this.defer()', function () {
|
||||||
var fakePromise = {};
|
const fakePromise = {};
|
||||||
var origDefer = Transport.prototype.defer;
|
const origDefer = Transport.prototype.defer;
|
||||||
var tran = new Transport({
|
const tran = new Transport({
|
||||||
defer: function () {
|
defer: function () {
|
||||||
return {
|
return {
|
||||||
resolve: _.noop,
|
resolve: _.noop,
|
||||||
@ -666,7 +666,7 @@ describe('Transport Class', function () {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
shortCircuitRequest(tran);
|
shortCircuitRequest(tran);
|
||||||
var ret = tran.request({});
|
const ret = tran.request({});
|
||||||
Transport.prototype.defer = origDefer;
|
Transport.prototype.defer = origDefer;
|
||||||
expect(ret).to.be(fakePromise);
|
expect(ret).to.be(fakePromise);
|
||||||
expect(ret.abort).to.be.a('function');
|
expect(ret.abort).to.be.a('function');
|
||||||
@ -677,7 +677,7 @@ describe('Transport Class', function () {
|
|||||||
if (process && process.hasOwnProperty('domain')) {
|
if (process && process.hasOwnProperty('domain')) {
|
||||||
it('works without a domain', function () {
|
it('works without a domain', function () {
|
||||||
expect(process.domain).to.be(null);
|
expect(process.domain).to.be(null);
|
||||||
var tran = new Transport();
|
const tran = new Transport();
|
||||||
shortCircuitRequest(tran);
|
shortCircuitRequest(tran);
|
||||||
tran.request({}, function () {
|
tran.request({}, function () {
|
||||||
expect(process.domain).to.be(null);
|
expect(process.domain).to.be(null);
|
||||||
@ -686,12 +686,12 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
it('binds the callback to the correct domain', function () {
|
it('binds the callback to the correct domain', function () {
|
||||||
expect(process.domain).to.be(null);
|
expect(process.domain).to.be(null);
|
||||||
var domain = require('domain').create();
|
const domain = require('domain').create();
|
||||||
domain.run(function () {
|
domain.run(function () {
|
||||||
var tran = new Transport();
|
const tran = new Transport();
|
||||||
shortCircuitRequest(tran);
|
shortCircuitRequest(tran);
|
||||||
expect(process.domain).not.to.be(null);
|
expect(process.domain).not.to.be(null);
|
||||||
var startingDomain = process.domain
|
const startingDomain = process.domain;
|
||||||
tran.request({}, function () {
|
tran.request({}, function () {
|
||||||
expect(process.domain).not.to.be(null);
|
expect(process.domain).not.to.be(null);
|
||||||
expect(process.domain).to.be(startingDomain);
|
expect(process.domain).to.be(startingDomain);
|
||||||
@ -704,24 +704,24 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
describe('aborting', function () {
|
describe('aborting', function () {
|
||||||
it('prevents the request from starting if called in the same tick', function () {
|
it('prevents the request from starting if called in the same tick', function () {
|
||||||
var tran = new Transport({
|
const tran = new Transport({
|
||||||
host: 'localhost'
|
host: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
var con = getConnection(tran);
|
const con = getConnection(tran);
|
||||||
stub(con, 'request', function () {
|
stub(con, 'request', function () {
|
||||||
throw new Error('Request should not have been called.');
|
throw new Error('Request should not have been called.');
|
||||||
});
|
});
|
||||||
|
|
||||||
var ret = tran.request({});
|
const ret = tran.request({});
|
||||||
ret.abort();
|
ret.abort();
|
||||||
});
|
});
|
||||||
it('calls the function returned by the connector if it has been called', function (done) {
|
it('calls the function returned by the connector if it has been called', function (done) {
|
||||||
var tran = new Transport({
|
const tran = new Transport({
|
||||||
host: 'localhost'
|
host: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
var con = getConnection(tran);
|
const con = getConnection(tran);
|
||||||
stub(con, 'request', function () {
|
stub(con, 'request', function () {
|
||||||
process.nextTick(function () {
|
process.nextTick(function () {
|
||||||
ret.abort();
|
ret.abort();
|
||||||
@ -734,16 +734,16 @@ describe('Transport Class', function () {
|
|||||||
var ret = tran.request({});
|
var ret = tran.request({});
|
||||||
});
|
});
|
||||||
it('ignores the response from the connection when the connector does not support aborting', function (done) {
|
it('ignores the response from the connection when the connector does not support aborting', function (done) {
|
||||||
var tran = new Transport({
|
const tran = new Transport({
|
||||||
host: 'localhost'
|
host: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
var con = getConnection(tran);
|
const con = getConnection(tran);
|
||||||
stub(con, 'request', function (params, cb) {
|
stub(con, 'request', function (params, cb) {
|
||||||
cb();
|
cb();
|
||||||
});
|
});
|
||||||
|
|
||||||
var ret = tran.request({}, function () {
|
const ret = tran.request({}, function () {
|
||||||
throw new Error('Callback should not have been called.');
|
throw new Error('Callback should not have been called.');
|
||||||
});
|
});
|
||||||
ret.abort();
|
ret.abort();
|
||||||
@ -753,11 +753,11 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
describe('timeout', function () {
|
describe('timeout', function () {
|
||||||
it('uses 30 seconds for the default', function () {
|
it('uses 30 seconds for the default', function () {
|
||||||
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
||||||
stub.autoRelease(clock);
|
stub.autoRelease(clock);
|
||||||
var tran = new Transport({});
|
const tran = new Transport({});
|
||||||
|
|
||||||
var prom = tran.request({});
|
const prom = tran.request({});
|
||||||
// disregard promise, prevent bluebird's warnings
|
// disregard promise, prevent bluebird's warnings
|
||||||
prom.then(_.noop, _.noop);
|
prom.then(_.noop, _.noop);
|
||||||
|
|
||||||
@ -768,13 +768,13 @@ describe('Transport Class', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
it('inherits the requestTimeout from the transport', function () {
|
it('inherits the requestTimeout from the transport', function () {
|
||||||
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
||||||
stub.autoRelease(clock);
|
stub.autoRelease(clock);
|
||||||
var tran = new Transport({
|
const tran = new Transport({
|
||||||
requestTimeout: 5000
|
requestTimeout: 5000
|
||||||
});
|
});
|
||||||
|
|
||||||
var prom = tran.request({});
|
const prom = tran.request({});
|
||||||
// disregard promise, prevent bluebird's warnings
|
// disregard promise, prevent bluebird's warnings
|
||||||
prom.then(_.noop, _.noop);
|
prom.then(_.noop, _.noop);
|
||||||
|
|
||||||
@ -788,9 +788,9 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
_.each([false, 0, null], function (falsy) {
|
_.each([false, 0, null], function (falsy) {
|
||||||
it('skips the timeout when it is ' + falsy, function () {
|
it('skips the timeout when it is ' + falsy, function () {
|
||||||
var clock = sinon.useFakeTimers();
|
const clock = sinon.useFakeTimers();
|
||||||
stub.autoRelease(clock);
|
stub.autoRelease(clock);
|
||||||
var tran = new Transport({});
|
const tran = new Transport({});
|
||||||
stub(tran.connectionPool, 'select', function () {});
|
stub(tran.connectionPool, 'select', function () {});
|
||||||
|
|
||||||
tran.request({
|
tran.request({
|
||||||
@ -806,7 +806,7 @@ describe('Transport Class', function () {
|
|||||||
describe('#setHosts', function () {
|
describe('#setHosts', function () {
|
||||||
it('accepts strings, host objects, and host configs', function () {
|
it('accepts strings, host objects, and host configs', function () {
|
||||||
|
|
||||||
var trans = new Transport({ suggestCompression: true });
|
const trans = new Transport({ suggestCompression: true });
|
||||||
stub(trans.connectionPool, 'setHosts');
|
stub(trans.connectionPool, 'setHosts');
|
||||||
|
|
||||||
trans.setHosts([
|
trans.setHosts([
|
||||||
@ -816,7 +816,7 @@ describe('Transport Class', function () {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
sinon.assert.calledOnce(trans.connectionPool.setHosts);
|
sinon.assert.calledOnce(trans.connectionPool.setHosts);
|
||||||
var host, hosts = trans.connectionPool.setHosts.firstCall.args[0];
|
let host, hosts = trans.connectionPool.setHosts.firstCall.args[0];
|
||||||
|
|
||||||
expect(hosts).to.have.length(3);
|
expect(hosts).to.have.length(3);
|
||||||
|
|
||||||
@ -842,7 +842,7 @@ describe('Transport Class', function () {
|
|||||||
|
|
||||||
describe('#close', function () {
|
describe('#close', function () {
|
||||||
it('proxies the call to it\'s log and connection pool', function () {
|
it('proxies the call to it\'s log and connection pool', function () {
|
||||||
var tran = new Transport();
|
const tran = new Transport();
|
||||||
stub(tran.connectionPool, 'close');
|
stub(tran.connectionPool, 'close');
|
||||||
stub(tran.log, 'close');
|
stub(tran.log, 'close');
|
||||||
|
|
||||||
|
|||||||
@ -1,14 +1,14 @@
|
|||||||
var Transport = require('../../../src/lib/transport');
|
const Transport = require('../../../src/lib/transport');
|
||||||
var ConnectionPool = require('../../../src/lib/connection_pool');
|
const ConnectionPool = require('../../../src/lib/connection_pool');
|
||||||
var Host = require('../../../src/lib/host');
|
const Host = require('../../../src/lib/host');
|
||||||
var errors = require('../../../src/lib/errors');
|
const errors = require('../../../src/lib/errors');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
|
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
var nock = require('../../mocks/server.js');
|
const nock = require('../../mocks/server.js');
|
||||||
var through2 = require('through2');
|
const through2 = require('through2');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Allows the tests call #request() without it doing anything past trying to select
|
* Allows the tests call #request() without it doing anything past trying to select
|
||||||
@ -28,7 +28,7 @@ function getConnection(transport, status) {
|
|||||||
describe('Transport + Mock server', function () {
|
describe('Transport + Mock server', function () {
|
||||||
describe('#request', function () {
|
describe('#request', function () {
|
||||||
describe('server responds', function () {
|
describe('server responds', function () {
|
||||||
var serverMock;
|
let serverMock;
|
||||||
|
|
||||||
before(function () {
|
before(function () {
|
||||||
serverMock = nock('http://localhost')
|
serverMock = nock('http://localhost')
|
||||||
@ -79,7 +79,7 @@ describe('Transport + Mock server', function () {
|
|||||||
|
|
||||||
describe('with a 400 status code', function () {
|
describe('with a 400 status code', function () {
|
||||||
it('passes back a 400/BadRequest error', function (done) {
|
it('passes back a 400/BadRequest error', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -98,7 +98,7 @@ describe('Transport + Mock server', function () {
|
|||||||
describe('with a 404 status code', function () {
|
describe('with a 404 status code', function () {
|
||||||
describe('and castExists is set', function () {
|
describe('and castExists is set', function () {
|
||||||
it('sends back false', function (done) {
|
it('sends back false', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -115,7 +115,7 @@ describe('Transport + Mock server', function () {
|
|||||||
});
|
});
|
||||||
describe('and the castExists param is not set', function () {
|
describe('and the castExists param is not set', function () {
|
||||||
it('sends back a 404/NotFound error', function (done) {
|
it('sends back a 404/NotFound error', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -134,7 +134,7 @@ describe('Transport + Mock server', function () {
|
|||||||
|
|
||||||
describe('with a 500 status code', function () {
|
describe('with a 500 status code', function () {
|
||||||
it('passes back a 500/InternalServerError error', function (done) {
|
it('passes back a 500/InternalServerError error', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -152,7 +152,7 @@ describe('Transport + Mock server', function () {
|
|||||||
|
|
||||||
describe('with a 530 status code', function () {
|
describe('with a 530 status code', function () {
|
||||||
it('passes back a Generic error', function (done) {
|
it('passes back a Generic error', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -170,7 +170,7 @@ describe('Transport + Mock server', function () {
|
|||||||
describe('with a 200 status code', function () {
|
describe('with a 200 status code', function () {
|
||||||
describe('and the castExists param is set', function () {
|
describe('and the castExists param is set', function () {
|
||||||
it('sends back true', function (done) {
|
it('sends back true', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -187,7 +187,7 @@ describe('Transport + Mock server', function () {
|
|||||||
});
|
});
|
||||||
describe('with a partial response body', function () {
|
describe('with a partial response body', function () {
|
||||||
it('sends back a serialization error', function (done) {
|
it('sends back a serialization error', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -203,7 +203,7 @@ describe('Transport + Mock server', function () {
|
|||||||
});
|
});
|
||||||
describe('with a valid response body', function () {
|
describe('with a valid response body', function () {
|
||||||
it('sends back the body and status code with no error', function (done) {
|
it('sends back the body and status code with no error', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -222,7 +222,7 @@ describe('Transport + Mock server', function () {
|
|||||||
|
|
||||||
describe('with plain text', function () {
|
describe('with plain text', function () {
|
||||||
it('notices the content-type header and returns the text', function (done) {
|
it('notices the content-type header and returns the text', function (done) {
|
||||||
var trans = new Transport({
|
const trans = new Transport({
|
||||||
hosts: 'localhost'
|
hosts: 'localhost'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -239,13 +239,13 @@ describe('Transport + Mock server', function () {
|
|||||||
|
|
||||||
describe('return value', function () {
|
describe('return value', function () {
|
||||||
it('resolves the promise it with the response body', function (done) {
|
it('resolves the promise it with the response body', function (done) {
|
||||||
var serverMock = nock('http://esbox.1.com')
|
const serverMock = nock('http://esbox.1.com')
|
||||||
.get('/')
|
.get('/')
|
||||||
.reply(200, {
|
.reply(200, {
|
||||||
good: 'day'
|
good: 'day'
|
||||||
});
|
});
|
||||||
|
|
||||||
var tran = new Transport({
|
const tran = new Transport({
|
||||||
hosts: 'http://esbox.1.com'
|
hosts: 'http://esbox.1.com'
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -260,13 +260,13 @@ describe('Transport + Mock server', function () {
|
|||||||
|
|
||||||
describe('timeout', function () {
|
describe('timeout', function () {
|
||||||
it('clears the timeout when the request is complete', function () {
|
it('clears the timeout when the request is complete', function () {
|
||||||
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
const clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
|
||||||
stub.autoRelease(clock);
|
stub.autoRelease(clock);
|
||||||
var tran = new Transport({
|
const tran = new Transport({
|
||||||
host: 'http://localhost:9200'
|
host: 'http://localhost:9200'
|
||||||
});
|
});
|
||||||
|
|
||||||
var server = nock('http://localhost:9200')
|
const server = nock('http://localhost:9200')
|
||||||
.get('/')
|
.get('/')
|
||||||
.reply(200, {
|
.reply(200, {
|
||||||
i: 'am here'
|
i: 'am here'
|
||||||
@ -282,11 +282,11 @@ describe('Transport + Mock server', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('timeout responds with a requestTimeout error', function (done) {
|
it('timeout responds with a requestTimeout error', function (done) {
|
||||||
var tran = new Transport({
|
const tran = new Transport({
|
||||||
host: 'http://localhost:9200'
|
host: 'http://localhost:9200'
|
||||||
});
|
});
|
||||||
|
|
||||||
var server = nock('http://localhost:9200')
|
const server = nock('http://localhost:9200')
|
||||||
.get('/')
|
.get('/')
|
||||||
.delay(1000)
|
.delay(1000)
|
||||||
.reply(200, {
|
.reply(200, {
|
||||||
@ -304,13 +304,13 @@ describe('Transport + Mock server', function () {
|
|||||||
|
|
||||||
describe('sniffOnConnectionFault', function () {
|
describe('sniffOnConnectionFault', function () {
|
||||||
it('schedules a sniff when sniffOnConnectionFault is set and a connection failes', function () {
|
it('schedules a sniff when sniffOnConnectionFault is set and a connection failes', function () {
|
||||||
var clock = sinon.useFakeTimers('setTimeout');
|
const clock = sinon.useFakeTimers('setTimeout');
|
||||||
stub.autoRelease(clock);
|
stub.autoRelease(clock);
|
||||||
|
|
||||||
var serverMock = nock('http://esbox.1.com')
|
const serverMock = nock('http://esbox.1.com')
|
||||||
.get('/')
|
.get('/')
|
||||||
.reply(200, function () {
|
.reply(200, function () {
|
||||||
var str = through2(function (chunk, enc, cb) {
|
const str = through2(function (chunk, enc, cb) {
|
||||||
cb(new Error('force error'));
|
cb(new Error('force error'));
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -324,7 +324,7 @@ describe('Transport + Mock server', function () {
|
|||||||
|
|
||||||
stub(ConnectionPool.prototype, '_onConnectionDied');
|
stub(ConnectionPool.prototype, '_onConnectionDied');
|
||||||
stub(Transport.prototype, 'sniff');
|
stub(Transport.prototype, 'sniff');
|
||||||
var tran = new Transport({
|
const tran = new Transport({
|
||||||
hosts: 'http://esbox.1.com',
|
hosts: 'http://esbox.1.com',
|
||||||
sniffOnConnectionFault: true,
|
sniffOnConnectionFault: true,
|
||||||
maxRetries: 0
|
maxRetries: 0
|
||||||
@ -343,7 +343,7 @@ describe('Transport + Mock server', function () {
|
|||||||
expect(tran.sniff.callCount).to.eql(0);
|
expect(tran.sniff.callCount).to.eql(0);
|
||||||
expect(_.size(clock.timers)).to.eql(1);
|
expect(_.size(clock.timers)).to.eql(1);
|
||||||
|
|
||||||
var timeout = _.values(clock.timers).pop();
|
const timeout = _.values(clock.timers).pop();
|
||||||
timeout.func();
|
timeout.func();
|
||||||
expect(tran.sniff.callCount).to.eql(1);
|
expect(tran.sniff.callCount).to.eql(1);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
var _ = require('../../../src/lib/utils');
|
const _ = require('../../../src/lib/utils');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
|
|
||||||
var stub = require('../../utils/auto_release_stub').make();
|
const stub = require('../../utils/auto_release_stub').make();
|
||||||
|
|
||||||
describe('Utils', function () {
|
describe('Utils', function () {
|
||||||
|
|
||||||
@ -238,14 +238,14 @@ describe('Utils', function () {
|
|||||||
describe('#deepMerge', function () {
|
describe('#deepMerge', function () {
|
||||||
|
|
||||||
it('returns the same object that was passed', function () {
|
it('returns the same object that was passed', function () {
|
||||||
var obj = {
|
const obj = {
|
||||||
foo: 'bar'
|
foo: 'bar'
|
||||||
};
|
};
|
||||||
expect(_.deepMerge(obj, { bar: 'baz' })).to.eql(obj);
|
expect(_.deepMerge(obj, { bar: 'baz' })).to.eql(obj);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('concats arrays', function () {
|
it('concats arrays', function () {
|
||||||
var obj = {
|
const obj = {
|
||||||
foo: ['bax', 'boz']
|
foo: ['bax', 'boz']
|
||||||
};
|
};
|
||||||
_.deepMerge(obj, { foo: ['boop'] });
|
_.deepMerge(obj, { foo: ['boop'] });
|
||||||
@ -253,7 +253,7 @@ describe('Utils', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('wont merge values of different types', function () {
|
it('wont merge values of different types', function () {
|
||||||
var obj = {
|
const obj = {
|
||||||
foo: ['stop', 'foo', 'stahp']
|
foo: ['stop', 'foo', 'stahp']
|
||||||
};
|
};
|
||||||
_.deepMerge(obj, { foo: 'string' });
|
_.deepMerge(obj, { foo: 'string' });
|
||||||
@ -261,7 +261,7 @@ describe('Utils', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('works recursively', function () {
|
it('works recursively', function () {
|
||||||
var obj = {
|
const obj = {
|
||||||
foo: 'bar',
|
foo: 'bar',
|
||||||
bax: {
|
bax: {
|
||||||
foo: ['bax', 'boz']
|
foo: ['bax', 'boz']
|
||||||
@ -275,8 +275,8 @@ describe('Utils', function () {
|
|||||||
|
|
||||||
describe('#createArray', function () {
|
describe('#createArray', function () {
|
||||||
it('accepts an array of things and simply returns a copy of it', function () {
|
it('accepts an array of things and simply returns a copy of it', function () {
|
||||||
var inp = [{ a: 1 }, 'pizza'];
|
const inp = [{ a: 1 }, 'pizza'];
|
||||||
var out = _.createArray(inp);
|
const out = _.createArray(inp);
|
||||||
expect(out).to.eql(inp);
|
expect(out).to.eql(inp);
|
||||||
expect(out).to.not.be(inp);
|
expect(out).to.not.be(inp);
|
||||||
});
|
});
|
||||||
@ -309,28 +309,28 @@ describe('Utils', function () {
|
|||||||
* _.funcEnum(object, key, opts, default);
|
* _.funcEnum(object, key, opts, default);
|
||||||
*/
|
*/
|
||||||
it('tests if the value at key in object is a function, returns it if so', function () {
|
it('tests if the value at key in object is a function, returns it if so', function () {
|
||||||
var config = {
|
const config = {
|
||||||
func: function () {}
|
func: function () {}
|
||||||
};
|
};
|
||||||
expect(_.funcEnum(config, 'func', {}, 'toString'))
|
expect(_.funcEnum(config, 'func', {}, 'toString'))
|
||||||
.to.be(config.func);
|
.to.be(config.func);
|
||||||
});
|
});
|
||||||
it('tests if the value at key in object is undefined, returns the option at key default if so', function () {
|
it('tests if the value at key in object is undefined, returns the option at key default if so', function () {
|
||||||
var config = {
|
const config = {
|
||||||
func: undefined
|
func: undefined
|
||||||
};
|
};
|
||||||
expect(_.funcEnum(config, 'func', {}, 'toString'))
|
expect(_.funcEnum(config, 'func', {}, 'toString'))
|
||||||
.to.be(Object.prototype.toString);
|
.to.be(Object.prototype.toString);
|
||||||
});
|
});
|
||||||
it('tests if the value at key in object is a string, returns the option at that key if so', function () {
|
it('tests if the value at key in object is a string, returns the option at that key if so', function () {
|
||||||
var config = {
|
const config = {
|
||||||
'config key name': 'toString'
|
'config key name': 'toString'
|
||||||
};
|
};
|
||||||
expect(_.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON'))
|
expect(_.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON'))
|
||||||
.to.be('pizza');
|
.to.be('pizza');
|
||||||
});
|
});
|
||||||
it('throws an informative error if the selection if invalid', function () {
|
it('throws an informative error if the selection if invalid', function () {
|
||||||
var config = {
|
const config = {
|
||||||
'config': 'val'
|
'config': 'val'
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -350,15 +350,15 @@ describe('Utils', function () {
|
|||||||
|
|
||||||
describe('#applyArgs', function () {
|
describe('#applyArgs', function () {
|
||||||
_.times(10, function (i) {
|
_.times(10, function (i) {
|
||||||
var method = i > 5 ? 'apply' : 'call';
|
const method = i > 5 ? 'apply' : 'call';
|
||||||
var argCount = i + 1;
|
const argCount = i + 1;
|
||||||
var slice = 1;
|
const slice = 1;
|
||||||
|
|
||||||
it('uses ' + method + ' with ' + i + ' args', function () {
|
it('uses ' + method + ' with ' + i + ' args', function () {
|
||||||
var func = function () {};
|
const func = function () {};
|
||||||
stub(func, method);
|
stub(func, method);
|
||||||
|
|
||||||
var args = _.map(new Array(i), function (val, i) { return i; });
|
const args = _.map(new Array(i), function (val, i) { return i; });
|
||||||
_.applyArgs(func, null, args);
|
_.applyArgs(func, null, args);
|
||||||
|
|
||||||
expect(func[method].callCount).to.eql(1);
|
expect(func[method].callCount).to.eql(1);
|
||||||
@ -371,11 +371,11 @@ describe('Utils', function () {
|
|||||||
|
|
||||||
it('slices the arguments properly before calling ' + method + ' with ' + argCount + ' args sliced at ' + slice,
|
it('slices the arguments properly before calling ' + method + ' with ' + argCount + ' args sliced at ' + slice,
|
||||||
function () {
|
function () {
|
||||||
var func = function () {};
|
const func = function () {};
|
||||||
stub(func, method);
|
stub(func, method);
|
||||||
|
|
||||||
var args = _.map(new Array(argCount), function (val, i) { return i; });
|
const args = _.map(new Array(argCount), function (val, i) { return i; });
|
||||||
var expected = args.slice(slice);
|
const expected = args.slice(slice);
|
||||||
_.applyArgs(func, null, args, slice);
|
_.applyArgs(func, null, args, slice);
|
||||||
|
|
||||||
expect(func[method].callCount).to.eql(1);
|
expect(func[method].callCount).to.eql(1);
|
||||||
@ -397,14 +397,14 @@ describe('Utils', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (require('stream').Writable) {
|
if (require('stream').Writable) {
|
||||||
var MockWritableStream = require('../../mocks/writable_stream');
|
const MockWritableStream = require('../../mocks/writable_stream');
|
||||||
it('ignores empty stream', function () {
|
it('ignores empty stream', function () {
|
||||||
var stream = new MockWritableStream();
|
const stream = new MockWritableStream();
|
||||||
expect(_.getUnwrittenFromStream(stream)).to.be('');
|
expect(_.getUnwrittenFromStream(stream)).to.be('');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('returns only what is in the buffer', function () {
|
it('returns only what is in the buffer', function () {
|
||||||
var stream = new MockWritableStream();
|
const stream = new MockWritableStream();
|
||||||
stream.write('hot');
|
stream.write('hot');
|
||||||
stream.write('dog');
|
stream.write('dog');
|
||||||
expect(_.getUnwrittenFromStream(stream)).to.be('dog');
|
expect(_.getUnwrittenFromStream(stream)).to.be('dog');
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
describe('Yaml Test Reader', function () {
|
describe('Yaml Test Reader', function () {
|
||||||
var YamlDoc = require('../../integration/yaml_suite/yaml_doc');
|
const YamlDoc = require('../../integration/yaml_suite/yaml_doc');
|
||||||
var compare = YamlDoc.compareRangeToVersion;
|
const compare = YamlDoc.compareRangeToVersion;
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
|
|
||||||
describe('version range comparison', function () {
|
describe('version range comparison', function () {
|
||||||
it('supports unbounded ranges', function () {
|
it('supports unbounded ranges', function () {
|
||||||
|
|||||||
@ -1,15 +1,15 @@
|
|||||||
|
|
||||||
var sinon = require('sinon');
|
const sinon = require('sinon');
|
||||||
|
|
||||||
exports.make = function () {
|
exports.make = function () {
|
||||||
var log = [];
|
const log = [];
|
||||||
afterEach(function () {
|
afterEach(function () {
|
||||||
var stub;
|
let stub;
|
||||||
while (stub = log.pop()) {
|
while (stub = log.pop()) {
|
||||||
stub.restore();
|
stub.restore();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
var stubber = function () {
|
const stubber = function () {
|
||||||
log.push(sinon.stub.apply(sinon, arguments));
|
log.push(sinon.stub.apply(sinon, arguments));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var expect = require('expect.js');
|
const expect = require('expect.js');
|
||||||
module.exports = function expectSubObject(obj, subObj) {
|
module.exports = function expectSubObject(obj, subObj) {
|
||||||
_.forOwn(subObj, function (val, prop) {
|
_.forOwn(subObj, function (val, prop) {
|
||||||
if (typeof obj[prop] === 'object') {
|
if (typeof obj[prop] === 'object') {
|
||||||
|
|||||||
@ -6,16 +6,16 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = JenkinsReporter;
|
module.exports = JenkinsReporter;
|
||||||
|
|
||||||
var Base = require('mocha/lib/reporters/base');
|
const Base = require('mocha/lib/reporters/base');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var chalk = require('chalk');
|
const chalk = require('chalk');
|
||||||
var makeJUnitXml = require('./make_j_unit_xml');
|
const makeJUnitXml = require('./make_j_unit_xml');
|
||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
var path = require('path');
|
const path = require('path');
|
||||||
var inspect = require('util').inspect;
|
const inspect = require('util').inspect;
|
||||||
|
|
||||||
var log = (function () {
|
const log = (function () {
|
||||||
var locked = _.bind(process.stdout.write, process.stdout);
|
const locked = _.bind(process.stdout.write, process.stdout);
|
||||||
return function (str) {
|
return function (str) {
|
||||||
if (typeof str !== 'string') {
|
if (typeof str !== 'string') {
|
||||||
str = inspect(str);
|
str = inspect(str);
|
||||||
@ -24,9 +24,9 @@ var log = (function () {
|
|||||||
};
|
};
|
||||||
}());
|
}());
|
||||||
|
|
||||||
var integration = _.find(process.argv, function (arg) { return arg.indexOf('test/integration') > -1; });
|
const integration = _.find(process.argv, function (arg) { return arg.indexOf('test/integration') > -1; });
|
||||||
var unit = _.find(process.argv, function (arg) { return arg.indexOf('test/unit') > -1; });
|
const unit = _.find(process.argv, function (arg) { return arg.indexOf('test/unit') > -1; });
|
||||||
var output;
|
let output;
|
||||||
|
|
||||||
if (unit) {
|
if (unit) {
|
||||||
output = path.join(__dirname, '../junit-node-unit.xml');
|
output = path.join(__dirname, '../junit-node-unit.xml');
|
||||||
@ -39,16 +39,16 @@ if (unit) {
|
|||||||
function JenkinsReporter(runner) {
|
function JenkinsReporter(runner) {
|
||||||
Base.call(this, runner);
|
Base.call(this, runner);
|
||||||
|
|
||||||
var stats = this.stats;
|
const stats = this.stats;
|
||||||
var pass = 0;
|
let pass = 0;
|
||||||
var pending = 0;
|
let pending = 0;
|
||||||
var fail = 0;
|
let fail = 0;
|
||||||
var rootSuite = {
|
const rootSuite = {
|
||||||
results: [],
|
results: [],
|
||||||
suites: []
|
suites: []
|
||||||
};
|
};
|
||||||
|
|
||||||
var stack = [rootSuite];
|
const stack = [rootSuite];
|
||||||
|
|
||||||
function indt() {
|
function indt() {
|
||||||
return (new Array(stack.length + 1)).join(' ');
|
return (new Array(stack.length + 1)).join(' ');
|
||||||
@ -105,7 +105,7 @@ function JenkinsReporter(runner) {
|
|||||||
log(chalk.red('x'));
|
log(chalk.red('x'));
|
||||||
}
|
}
|
||||||
|
|
||||||
var errMsg = void 0;
|
let errMsg = void 0;
|
||||||
|
|
||||||
if (test.err) {
|
if (test.err) {
|
||||||
errMsg = test.err.stack || test.err.toString();
|
errMsg = test.err.stack || test.err.toString();
|
||||||
@ -146,7 +146,7 @@ function JenkinsReporter(runner) {
|
|||||||
|
|
||||||
runner.on('hook end', function (hook) {
|
runner.on('hook end', function (hook) {
|
||||||
if (hook.title.indexOf('"after each"') > -1 && stack[0] && stack[0].results.length) {
|
if (hook.title.indexOf('"after each"') > -1 && stack[0] && stack[0].results.length) {
|
||||||
var result = _.last(stack[0].results);
|
const result = _.last(stack[0].results);
|
||||||
result.stdout += stack[0].stdout;
|
result.stdout += stack[0].stdout;
|
||||||
result.stderr += stack[0].stderr;
|
result.stderr += stack[0].stderr;
|
||||||
stack[0].stdout = stack[0].stderr = '';
|
stack[0].stdout = stack[0].stderr = '';
|
||||||
@ -155,10 +155,10 @@ function JenkinsReporter(runner) {
|
|||||||
|
|
||||||
runner.on('end', function () {
|
runner.on('end', function () {
|
||||||
restoreStdio();
|
restoreStdio();
|
||||||
var xml = makeJUnitXml('node ' + process.version, {
|
const xml = makeJUnitXml('node ' + process.version, {
|
||||||
stats: stats,
|
stats: stats,
|
||||||
suites: _.map(rootSuite.suites, function removeElements(suite) {
|
suites: _.map(rootSuite.suites, function removeElements(suite) {
|
||||||
var s = {
|
const s = {
|
||||||
name: suite.name,
|
name: suite.name,
|
||||||
start: suite.start,
|
start: suite.start,
|
||||||
time: suite.time || 0,
|
time: suite.time || 0,
|
||||||
@ -186,8 +186,8 @@ function JenkinsReporter(runner) {
|
|||||||
|
|
||||||
// overload the write methods on stdout and stderr
|
// overload the write methods on stdout and stderr
|
||||||
['stdout', 'stderr'].forEach(function (name) {
|
['stdout', 'stderr'].forEach(function (name) {
|
||||||
var obj = process[name];
|
const obj = process[name];
|
||||||
var orig = obj.write;
|
const orig = obj.write;
|
||||||
obj.write = function (chunk) {
|
obj.write = function (chunk) {
|
||||||
if (stack[0]) {
|
if (stack[0]) {
|
||||||
stack[0][name] = (stack[0][name] || '') + chunk;
|
stack[0][name] = (stack[0][name] || '') + chunk;
|
||||||
|
|||||||
@ -24,17 +24,17 @@
|
|||||||
*/
|
*/
|
||||||
module.exports = makeJUnitXml;
|
module.exports = makeJUnitXml;
|
||||||
|
|
||||||
var testXml = require('xmlbuilder');
|
const testXml = require('xmlbuilder');
|
||||||
var suites = testXml.create('testsuites');
|
const suites = testXml.create('testsuites');
|
||||||
var suiteCount = 0;
|
let suiteCount = 0;
|
||||||
var moment = require('moment');
|
const moment = require('moment');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var chalk = require('chalk');
|
const chalk = require('chalk');
|
||||||
|
|
||||||
function makeJUnitXml(runnerName, testDetails) {
|
function makeJUnitXml(runnerName, testDetails) {
|
||||||
_.each(testDetails.suites, function serializeSuite(suiteInfo) {
|
_.each(testDetails.suites, function serializeSuite(suiteInfo) {
|
||||||
|
|
||||||
var suite = suites.ele('testsuite', {
|
const suite = suites.ele('testsuite', {
|
||||||
package: 'elasticsearch-js',
|
package: 'elasticsearch-js',
|
||||||
id: suiteCount++,
|
id: suiteCount++,
|
||||||
name: suiteInfo.name,
|
name: suiteInfo.name,
|
||||||
@ -47,8 +47,8 @@ function makeJUnitXml(runnerName, testDetails) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
_.each(suiteInfo.results, function (testInfo) {
|
_.each(suiteInfo.results, function (testInfo) {
|
||||||
var section;
|
let section;
|
||||||
var integration = false;
|
let integration = false;
|
||||||
|
|
||||||
if (suiteInfo.name.match(/\/.*\.yaml$/)) {
|
if (suiteInfo.name.match(/\/.*\.yaml$/)) {
|
||||||
section = suiteInfo.name.split('/').slice(0, -1).join('/').replace(/\./g, '/');
|
section = suiteInfo.name.split('/').slice(0, -1).join('/').replace(/\./g, '/');
|
||||||
@ -61,7 +61,7 @@ function makeJUnitXml(runnerName, testDetails) {
|
|||||||
integration = true;
|
integration = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
var testcase = suite.ele('testcase', {
|
const testcase = suite.ele('testcase', {
|
||||||
name: testInfo.name,
|
name: testInfo.name,
|
||||||
time: (testInfo.time || 0) / 1000,
|
time: (testInfo.time || 0) / 1000,
|
||||||
classname: runnerName + (integration ? ' - integration' : '') + '.' + section
|
classname: runnerName + (integration ? ' - integration' : '') + '.' + section
|
||||||
@ -93,8 +93,8 @@ function makeJUnitXml(runnerName, testDetails) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function giveOutput(el, info) {
|
function giveOutput(el, info) {
|
||||||
var out = info.stdout.trim();
|
const out = info.stdout.trim();
|
||||||
var err = info.stderr.trim();
|
const err = info.stderr.trim();
|
||||||
|
|
||||||
if (out) {
|
if (out) {
|
||||||
el.ele('system-out', {}).cdata(chalk.stripColor(out));
|
el.ele('system-out', {}).cdata(chalk.stripColor(out));
|
||||||
|
|||||||
@ -1,16 +1,16 @@
|
|||||||
/* eslint-disable import/no-unresolved */
|
/* eslint-disable import/no-unresolved */
|
||||||
var express = require('express');
|
const express = require('express');
|
||||||
var http = require('http');
|
const http = require('http');
|
||||||
var fs = require('fs');
|
const fs = require('fs');
|
||||||
var _ = require('lodash');
|
const _ = require('lodash');
|
||||||
var async = require('async');
|
const async = require('async');
|
||||||
var root = require('path').join(__dirname, '../..');
|
const root = require('path').join(__dirname, '../..');
|
||||||
var browserify = require('browserify');
|
const browserify = require('browserify');
|
||||||
var pkg = require(root + '/package.json');
|
const pkg = require(root + '/package.json');
|
||||||
var unitSpecDir = root + '/test/unit/specs';
|
const unitSpecDir = root + '/test/unit/specs';
|
||||||
var browserBuildsDir = root + '/test/unit/browser_builds';
|
const browserBuildsDir = root + '/test/unit/browser_builds';
|
||||||
|
|
||||||
var testFiles = {};
|
const testFiles = {};
|
||||||
|
|
||||||
testFiles.unit = _(fs.readdirSync(unitSpecDir))
|
testFiles.unit = _(fs.readdirSync(unitSpecDir))
|
||||||
.difference([
|
.difference([
|
||||||
@ -33,12 +33,12 @@ testFiles.build = fs.readdirSync(browserBuildsDir)
|
|||||||
return browserBuildsDir + '/' + file;
|
return browserBuildsDir + '/' + file;
|
||||||
}
|
}
|
||||||
|
|
||||||
return null
|
return null;
|
||||||
})
|
})
|
||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
|
|
||||||
// generic aliasify instance
|
// generic aliasify instance
|
||||||
var aliasify = require('aliasify').configure({
|
const aliasify = require('aliasify').configure({
|
||||||
aliases: pkg.browser,
|
aliases: pkg.browser,
|
||||||
excludeExtensions: 'json',
|
excludeExtensions: 'json',
|
||||||
// verbose: false,
|
// verbose: false,
|
||||||
@ -46,7 +46,7 @@ var aliasify = require('aliasify').configure({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// queue for bundle requests, two at a time
|
// queue for bundle requests, two at a time
|
||||||
var bundleQueue = async.queue(function (task, done) {
|
const bundleQueue = async.queue(function (task, done) {
|
||||||
task(done);
|
task(done);
|
||||||
}, 2);
|
}, 2);
|
||||||
|
|
||||||
@ -54,16 +54,16 @@ var bundleQueue = async.queue(function (task, done) {
|
|||||||
function bundleTests(name) {
|
function bundleTests(name) {
|
||||||
return function (req, res, next) {
|
return function (req, res, next) {
|
||||||
bundleQueue.push(function (_cb) {
|
bundleQueue.push(function (_cb) {
|
||||||
var done = function (err) {
|
const done = function (err) {
|
||||||
if (err) { return next(err); }
|
if (err) { return next(err); }
|
||||||
_cb(err);
|
_cb(err);
|
||||||
};
|
};
|
||||||
|
|
||||||
res.set('Content-Type', 'application/javascript');
|
res.set('Content-Type', 'application/javascript');
|
||||||
|
|
||||||
var b = browserify(testFiles[name]);
|
const b = browserify(testFiles[name]);
|
||||||
b.transform(aliasify);
|
b.transform(aliasify);
|
||||||
var str = b.bundle({
|
const str = b.bundle({
|
||||||
insertGlobals: true
|
insertGlobals: true
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -81,7 +81,7 @@ function sendFile(file) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
var app = express();
|
const app = express();
|
||||||
|
|
||||||
app
|
app
|
||||||
.use(app.router)
|
.use(app.router)
|
||||||
|
|||||||
6
webpack_config/angular.js
vendored
6
webpack_config/angular.js
vendored
@ -1,5 +1,5 @@
|
|||||||
const DefinePlugin = require('webpack/lib/DefinePlugin')
|
const DefinePlugin = require('webpack/lib/DefinePlugin');
|
||||||
const { ignoreLoader, rel } = require('./lib')
|
const { ignoreLoader, rel } = require('./lib');
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
context: rel('src'),
|
context: rel('src'),
|
||||||
@ -22,4 +22,4 @@ module.exports = {
|
|||||||
'process.env.NODE_ENV': '"production"',
|
'process.env.NODE_ENV': '"production"',
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
}
|
};
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
const DefinePlugin = require('webpack/lib/DefinePlugin')
|
const DefinePlugin = require('webpack/lib/DefinePlugin');
|
||||||
const { ignoreLoader, rel } = require('./lib')
|
const { ignoreLoader, rel } = require('./lib');
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
context: rel('src'),
|
context: rel('src'),
|
||||||
@ -23,4 +23,4 @@ module.exports = {
|
|||||||
'process.env.NODE_ENV': '"production"',
|
'process.env.NODE_ENV': '"production"',
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
}
|
};
|
||||||
|
|||||||
6
webpack_config/jquery.js
vendored
6
webpack_config/jquery.js
vendored
@ -1,5 +1,5 @@
|
|||||||
const DefinePlugin = require('webpack/lib/DefinePlugin')
|
const DefinePlugin = require('webpack/lib/DefinePlugin');
|
||||||
const { ignoreLoader, rel } = require('./lib')
|
const { ignoreLoader, rel } = require('./lib');
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
context: rel('src'),
|
context: rel('src'),
|
||||||
@ -22,4 +22,4 @@ module.exports = {
|
|||||||
'process.env.NODE_ENV': '"production"',
|
'process.env.NODE_ENV': '"production"',
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
}
|
};
|
||||||
|
|||||||
@ -1,13 +1,13 @@
|
|||||||
|
|
||||||
const rel = require('path').resolve.bind(null, __dirname, '..')
|
const rel = require('path').resolve.bind(null, __dirname, '..');
|
||||||
|
|
||||||
function ignoreLoader(ignores) {
|
function ignoreLoader(ignores) {
|
||||||
return {
|
return {
|
||||||
loader: 'null-loader',
|
loader: 'null-loader',
|
||||||
test(path) {
|
test(path) {
|
||||||
return ignores.some(ignore => path.includes(ignore))
|
return ignores.some(ignore => path.includes(ignore));
|
||||||
},
|
},
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function jsLoader() {
|
function jsLoader() {
|
||||||
@ -15,7 +15,7 @@ function jsLoader() {
|
|||||||
loader: 'babel-loader',
|
loader: 'babel-loader',
|
||||||
test: /\.js$/,
|
test: /\.js$/,
|
||||||
include: rel('src'),
|
include: rel('src'),
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { ignoreLoader, jsLoader, rel }
|
module.exports = { ignoreLoader, jsLoader, rel };
|
||||||
|
|||||||
Reference in New Issue
Block a user