diff options
author | Mark Benvenuto <mark.benvenuto@mongodb.com> | 2016-05-28 17:55:12 -0400 |
---|---|---|
committer | Mark Benvenuto <mark.benvenuto@mongodb.com> | 2016-05-28 17:55:12 -0400 |
commit | 6dcdd23dd37ef12c87e71cf59ef01cd82432efe0 (patch) | |
tree | c8cfb5acb62c80f375bc37e7d4350382deea6a37 /jstests | |
parent | d4ac5673ea3f6cef4ce9dbcec90e31813997a528 (diff) | |
download | mongo-6dcdd23dd37ef12c87e71cf59ef01cd82432efe0.tar.gz |
SERVER-23971 Clang-Format code
Diffstat (limited to 'jstests')
667 files changed, 5954 insertions, 8410 deletions
diff --git a/jstests/aggregation/bugs/cond.js b/jstests/aggregation/bugs/cond.js index 2b4fa8ff16e..c48c6b724f0 100644 --- a/jstests/aggregation/bugs/cond.js +++ b/jstests/aggregation/bugs/cond.js @@ -68,16 +68,15 @@ t.save({noonSense: 'pm', mealCombined: 'yes'}); t.save({noonSense: 'pm', mealCombined: 'no'}); assert.eq(['breakfast', 'brunch', 'linner', 'dinner'], t.aggregate({ - $project: { - a: { - $cond: [ - {$eq: ['$noonSense', 'am']}, - {$cond: [{$eq: ['$mealCombined', 'yes']}, 'brunch', 'breakfast']}, - {$cond: [{$eq: ['$mealCombined', 'yes']}, 'linner', 'dinner']} - ] - } - } - }) - .map(function(x) { - return x.a; - })); + $project: { + a: { + $cond: [ + {$eq: ['$noonSense', 'am']}, + {$cond: [{$eq: ['$mealCombined', 'yes']}, 'brunch', 'breakfast']}, + {$cond: [{$eq: ['$mealCombined', 'yes']}, 'linner', 'dinner']} + ] + } + } + }).map(function(x) { + return x.a; + })); diff --git a/jstests/aggregation/bugs/firstlast.js b/jstests/aggregation/bugs/firstlast.js index ca9e963f6ca..54f0f8be0e9 100644 --- a/jstests/aggregation/bugs/firstlast.js +++ b/jstests/aggregation/bugs/firstlast.js @@ -104,17 +104,5 @@ assertFirstLast([1, 2], [6], [], '$b.c'); t.drop(); t.save({a: 1, b: 1}); t.save({a: 1, b: 2}); -assertFirstLast(1, - 0, - [], - { -$mod: - ['$b', 2] - }); -assertFirstLast(0, - 1, - [], - { -$mod: - [{$add: ['$b', 1]}, 2] - }); +assertFirstLast(1, 0, [], {$mod: ['$b', 2]}); +assertFirstLast(0, 1, [], {$mod: [{$add: ['$b', 1]}, 2]}); diff --git a/jstests/aggregation/bugs/match.js b/jstests/aggregation/bugs/match.js index fbc467812d7..2ee646dac7e 100644 --- a/jstests/aggregation/bugs/match.js +++ b/jstests/aggregation/bugs/match.js @@ -13,9 +13,7 @@ identityProjection = { /** Assert that an aggregation generated the expected error. */ function assertError(expectedCode, matchSpec) { - matchStage = { - $match: matchSpec - }; + matchStage = {$match: matchSpec}; // Check where matching is folded in to DocumentSourceCursor. assertErrorCode(t, [matchStage], expectedCode); // Check where matching is not folded in to DocumentSourceCursor. @@ -41,9 +39,7 @@ function assertResults(expectedResults, matchSpec) { if (expectedResults) { assertEqualResultsUnordered(expectedResults, findResults); } - matchStage = { - $match: matchSpec - }; + matchStage = {$match: matchSpec}; // Check where matching is folded in to DocumentSourceCursor. assertEqualResultsUnordered(findResults, t.aggregate(matchStage).toArray()); // Check where matching is not folded in to DocumentSourceCursor. @@ -176,11 +172,7 @@ function checkMatchResults(indexed) { // $and assertResults([{_id: 1, a: 2}], {$and: [{a: 2}, {_id: 1}]}); - assertResults([], - { - $and: - [{a: 1}, {_id: 1}] - }); + assertResults([], {$and: [{a: 1}, {_id: 1}]}); assertResults([{_id: 1, a: 2}, {_id: 2, a: 3}], {$and: [{$or: [{_id: 1}, {a: 3}]}, {$or: [{_id: 2}, {a: 2}]}]}); diff --git a/jstests/aggregation/bugs/server10176.js b/jstests/aggregation/bugs/server10176.js index 5a56585265d..b04db0c4319 100644 --- a/jstests/aggregation/bugs/server10176.js +++ b/jstests/aggregation/bugs/server10176.js @@ -33,28 +33,27 @@ load('jstests/aggregation/extras/utils.js'); // valid use of $abs: numbers become positive, null/undefined/nonexistent become null var results = coll.aggregate([{$project: {a: {$abs: "$a"}}}]).toArray(); - assert.eq(results, - [ - {_id: 0, a: 5}, - {_id: 1, a: 5}, - {_id: 2, a: 5.5}, - {_id: 3, a: 5.5}, - {_id: 4, a: 5}, - {_id: 5, a: 5}, - {_id: 6, a: NumberLong("5")}, - {_id: 7, a: NumberLong("5")}, - {_id: 8, a: 0}, - {_id: 9, a: 0}, - {_id: 10, a: 0}, - {_id: 11, a: NumberLong(Math.pow(2, 31))}, - {_id: 12, a: Math.pow(2, 31)}, - {_id: 13, a: NumberLong("1152921504606846977")}, - {_id: 14, a: NumberLong("1152921504606846977")}, - {_id: 15, a: null}, - {_id: 16, a: null}, - {_id: 17, a: NaN}, - {_id: 18, a: null}, - ]); + assert.eq(results, [ + {_id: 0, a: 5}, + {_id: 1, a: 5}, + {_id: 2, a: 5.5}, + {_id: 3, a: 5.5}, + {_id: 4, a: 5}, + {_id: 5, a: 5}, + {_id: 6, a: NumberLong("5")}, + {_id: 7, a: NumberLong("5")}, + {_id: 8, a: 0}, + {_id: 9, a: 0}, + {_id: 10, a: 0}, + {_id: 11, a: NumberLong(Math.pow(2, 31))}, + {_id: 12, a: Math.pow(2, 31)}, + {_id: 13, a: NumberLong("1152921504606846977")}, + {_id: 14, a: NumberLong("1152921504606846977")}, + {_id: 15, a: null}, + {_id: 16, a: null}, + {_id: 17, a: NaN}, + {_id: 18, a: null}, + ]); // Invalid // using $abs on string diff --git a/jstests/aggregation/bugs/server11118.js b/jstests/aggregation/bugs/server11118.js index da4e9862bad..3d2813ed8ae 100644 --- a/jstests/aggregation/bugs/server11118.js +++ b/jstests/aggregation/bugs/server11118.js @@ -9,9 +9,13 @@ function testFormat(date, formatStr, expectedStr) { db.dates.drop(); db.dates.insert({date: date}); - var res = db.dates.aggregate([{ - $project: {_id: 0, formatted: {$dateToString: {format: formatStr, date: "$date"}}} - }]).toArray(); + var res = + db.dates + .aggregate([{ + $project: + {_id: 0, formatted: {$dateToString: {format: formatStr, date: "$date"}}} + }]) + .toArray(); assert.eq(res[0].formatted, expectedStr); } @@ -36,18 +40,16 @@ function testDateValueError(dateVal, errCode) { var now = ISODate(); // Use all modifiers we can test with js provided function -testFormat(now, - "%%-%Y-%m-%d-%H-%M-%S-%L", - [ - "%", - now.getUTCFullYear().zeroPad(4), - (now.getUTCMonth() + 1).zeroPad(2), - now.getUTCDate().zeroPad(2), - now.getUTCHours().zeroPad(2), - now.getUTCMinutes().zeroPad(2), - now.getUTCSeconds().zeroPad(2), - now.getUTCMilliseconds().zeroPad(3) - ].join("-")); +testFormat(now, "%%-%Y-%m-%d-%H-%M-%S-%L", [ + "%", + now.getUTCFullYear().zeroPad(4), + (now.getUTCMonth() + 1).zeroPad(2), + now.getUTCDate().zeroPad(2), + now.getUTCHours().zeroPad(2), + now.getUTCMinutes().zeroPad(2), + now.getUTCSeconds().zeroPad(2), + now.getUTCMilliseconds().zeroPad(3) +].join("-")); // Padding tests var padme = ISODate("2001-02-03T04:05:06.007Z"); @@ -62,20 +64,18 @@ testFormat(padme, "%S", padme.getUTCSeconds().zeroPad(2)); testFormat(padme, "%L", padme.getUTCMilliseconds().zeroPad(3)); // no space and multiple characters between modifiers -testFormat(now, - "%d%d***%d***%d**%d*%d", - [ - now.getUTCDate().zeroPad(2), - now.getUTCDate().zeroPad(2), - "***", - now.getUTCDate().zeroPad(2), - "***", - now.getUTCDate().zeroPad(2), - "**", - now.getUTCDate().zeroPad(2), - "*", - now.getUTCDate().zeroPad(2) - ].join("")); +testFormat(now, "%d%d***%d***%d**%d*%d", [ + now.getUTCDate().zeroPad(2), + now.getUTCDate().zeroPad(2), + "***", + now.getUTCDate().zeroPad(2), + "***", + now.getUTCDate().zeroPad(2), + "**", + now.getUTCDate().zeroPad(2), + "*", + now.getUTCDate().zeroPad(2) +].join("")); // JS doesn't have equivalents of these format specifiers testFormat(ISODate('1999-01-02 03:04:05.006Z'), "%U-%w-%j", "00-7-002"); diff --git a/jstests/aggregation/bugs/server11675.js b/jstests/aggregation/bugs/server11675.js index 709120c27ca..a38570dc8cd 100644 --- a/jstests/aggregation/bugs/server11675.js +++ b/jstests/aggregation/bugs/server11675.js @@ -88,57 +88,57 @@ var server11675 = function() { return obj; }); var res = t.aggregate([ - {$match: {$text: {$search: 'apple banana'}}}, - {$sort: {textScore: {$meta: 'textScore'}}} - ]).toArray(); + {$match: {$text: {$search: 'apple banana'}}}, + {$sort: {textScore: {$meta: 'textScore'}}} + ]).toArray(); assert.eq(res, findRes); // Make sure {$meta: 'textScore'} can be used as a sub-expression var res = t.aggregate([ - {$match: {_id: 1, $text: {$search: 'apple'}}}, - { - $project: { - words: 1, - score: {$meta: 'textScore'}, - wordsTimesScore: {$multiply: ['$words', {$meta: 'textScore'}]} - } - } - ]).toArray(); + {$match: {_id: 1, $text: {$search: 'apple'}}}, + { + $project: { + words: 1, + score: {$meta: 'textScore'}, + wordsTimesScore: {$multiply: ['$words', {$meta: 'textScore'}]} + } + } + ]).toArray(); assert.eq(res[0].wordsTimesScore, res[0].words * res[0].score, tojson(res)); // And can be used in $group var res = t.aggregate([ - {$match: {_id: 1, $text: {$search: 'apple banana'}}}, - {$group: {_id: {$meta: 'textScore'}, score: {$first: {$meta: 'textScore'}}}} - ]).toArray(); + {$match: {_id: 1, $text: {$search: 'apple banana'}}}, + {$group: {_id: {$meta: 'textScore'}, score: {$first: {$meta: 'textScore'}}}} + ]).toArray(); assert.eq(res[0]._id, res[0].score, tojson(res)); // Make sure metadata crosses shard -> merger boundary var res = t.aggregate([ - {$match: {_id: 1, $text: {$search: 'apple'}}}, - {$project: {scoreOnShard: {$meta: 'textScore'}}}, - {$limit: 1} // force a split. later stages run on merger - , - {$project: {scoreOnShard: 1, scoreOnMerger: {$meta: 'textScore'}}} - ]).toArray(); + {$match: {_id: 1, $text: {$search: 'apple'}}}, + {$project: {scoreOnShard: {$meta: 'textScore'}}}, + {$limit: 1} // force a split. later stages run on merger + , + {$project: {scoreOnShard: 1, scoreOnMerger: {$meta: 'textScore'}}} + ]).toArray(); assert.eq(res[0].scoreOnMerger, res[0].scoreOnShard); var score = res[0].scoreOnMerger; // save for later tests // Make sure metadata crosses shard -> merger boundary even if not used on shard var res = t.aggregate([ - {$match: {_id: 1, $text: {$search: 'apple'}}}, - {$limit: 1} // force a split. later stages run on merger - , - {$project: {scoreOnShard: 1, scoreOnMerger: {$meta: 'textScore'}}} - ]).toArray(); + {$match: {_id: 1, $text: {$search: 'apple'}}}, + {$limit: 1} // force a split. later stages run on merger + , + {$project: {scoreOnShard: 1, scoreOnMerger: {$meta: 'textScore'}}} + ]).toArray(); assert.eq(res[0].scoreOnMerger, score); // Make sure metadata works if first $project doesn't use it. var res = t.aggregate([ - {$match: {_id: 1, $text: {$search: 'apple'}}}, - {$project: {_id: 1}}, - {$project: {_id: 1, score: {$meta: 'textScore'}}} - ]).toArray(); + {$match: {_id: 1, $text: {$search: 'apple'}}}, + {$project: {_id: 1}}, + {$project: {_id: 1, score: {$meta: 'textScore'}}} + ]).toArray(); assert.eq(res[0].score, score); // Make sure the metadata is 'missing()' when it doesn't exist because it was never created @@ -147,20 +147,20 @@ var server11675 = function() { // Make sure the metadata is 'missing()' when it doesn't exist because the document changed var res = t.aggregate([ - {$match: {_id: 1, $text: {$search: 'apple banana'}}}, - {$group: {_id: 1, score: {$first: {$meta: 'textScore'}}}}, - {$project: {_id: 1, scoreAgain: {$meta: 'textScore'}}}, - ]).toArray(); + {$match: {_id: 1, $text: {$search: 'apple banana'}}}, + {$group: {_id: 1, score: {$first: {$meta: 'textScore'}}}}, + {$project: {_id: 1, scoreAgain: {$meta: 'textScore'}}}, + ]).toArray(); assert(!("scoreAgain" in res[0])); // Make sure metadata works after a $unwind t.insert({_id: 5, text: 'mango', words: [1, 2, 3]}); var res = t.aggregate([ - {$match: {$text: {$search: 'mango'}}}, - {$project: {score: {$meta: "textScore"}, _id: 1, words: 1}}, - {$unwind: '$words'}, - {$project: {scoreAgain: {$meta: "textScore"}, score: 1}} - ]).toArray(); + {$match: {$text: {$search: 'mango'}}}, + {$project: {score: {$meta: "textScore"}, _id: 1, words: 1}}, + {$unwind: '$words'}, + {$project: {scoreAgain: {$meta: "textScore"}, score: 1}} + ]).toArray(); assert.eq(res[0].scoreAgain, res[0].score); // Error checking diff --git a/jstests/aggregation/bugs/server12015.js b/jstests/aggregation/bugs/server12015.js index af4ee75f92d..c237e4f6f90 100644 --- a/jstests/aggregation/bugs/server12015.js +++ b/jstests/aggregation/bugs/server12015.js @@ -12,10 +12,7 @@ load("jstests/aggregation/extras/utils.js"); // For orderedArrayEq. "use strict"; var coll = db.server12015; coll.drop(); - var indexSpec = { - a: 1, - b: 1 - }; + var indexSpec = {a: 1, b: 1}; assert.writeOK(coll.insert({_id: 0, a: 0, b: 0})); assert.writeOK(coll.insert({_id: 1, a: 0, b: 1})); diff --git a/jstests/aggregation/bugs/server14670.js b/jstests/aggregation/bugs/server14670.js index 92c6e98e8e1..dc8a750e9db 100644 --- a/jstests/aggregation/bugs/server14670.js +++ b/jstests/aggregation/bugs/server14670.js @@ -12,12 +12,12 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode. coll.insert({}); assertErrorCode(coll, - [{$project: {strLen: {$strLenBytes: 1}}}], + [{$project: {strLen: {$strLenBytes: 1}}}], 34473, "$strLenBytes requires a string argument."); assertErrorCode(coll, - [{$project: {strLen: {$strLenCP: 1}}}], + [{$project: {strLen: {$strLenCP: 1}}}], 34471, "$strLenCP requires a string argument."); }()); diff --git a/jstests/aggregation/bugs/server17943.js b/jstests/aggregation/bugs/server17943.js index 10dbac2c37a..7036a16b940 100644 --- a/jstests/aggregation/bugs/server17943.js +++ b/jstests/aggregation/bugs/server17943.js @@ -18,11 +18,7 @@ load('jstests/aggregation/extras/utils.js'); assert.writeOK(coll.insert({_id: 6})); // Create filter to only accept odd numbers. - filterDoc = { - input: '$a', - as: 'x', - cond: {$eq: [1, {$mod: ['$$x', 2]}]} - }; + filterDoc = {input: '$a', as: 'x', cond: {$eq: [1, {$mod: ['$$x', 2]}]}}; var expectedResults = [ {_id: 0, b: [1, 3, 5]}, {_id: 1, b: []}, @@ -45,57 +41,31 @@ load('jstests/aggregation/extras/utils.js'); assertErrorCode(coll, [{$project: {b: {$filter: filterDoc}}}], 28646); // Extra field(s). - filterDoc = { - input: '$a', - as: 'x', - cond: true, - extra: 1 - }; + filterDoc = {input: '$a', as: 'x', cond: true, extra: 1}; assertErrorCode(coll, [{$project: {b: {$filter: filterDoc}}}], 28647); // Missing 'input'. - filterDoc = { - as: 'x', - cond: true - }; + filterDoc = {as: 'x', cond: true}; assertErrorCode(coll, [{$project: {b: {$filter: filterDoc}}}], 28648); // Missing 'as'. - filterDoc = { - input: '$a', - cond: true - }; + filterDoc = {input: '$a', cond: true}; assertErrorCode(coll, [{$project: {b: {$filter: filterDoc}}}], 28649); // Missing 'cond'. - filterDoc = { - input: '$a', - as: 'x' - }; + filterDoc = {input: '$a', as: 'x'}; assertErrorCode(coll, [{$project: {b: {$filter: filterDoc}}}], 28650); // 'as' is not a valid variable name. - filterDoc = { - input: '$a', - as: '$x', - cond: true - }; + filterDoc = {input: '$a', as: '$x', cond: true}; assertErrorCode(coll, [{$project: {b: {$filter: filterDoc}}}], 16867); // 'input' is not an array. - filterDoc = { - input: 'string', - as: 'x', - cond: true - }; + filterDoc = {input: 'string', as: 'x', cond: true}; assertErrorCode(coll, [{$project: {b: {$filter: filterDoc}}}], 28651); coll.drop(); assert.writeOK(coll.insert({a: 'string'})); - filterDoc = { - input: '$a', - as: 'x', - cond: true - }; + filterDoc = {input: '$a', as: 'x', cond: true}; assertErrorCode(coll, [{$project: {b: {$filter: filterDoc}}}], 28651); }()); diff --git a/jstests/aggregation/bugs/server18198.js b/jstests/aggregation/bugs/server18198.js index 39cb37074e5..19b355f4953 100644 --- a/jstests/aggregation/bugs/server18198.js +++ b/jstests/aggregation/bugs/server18198.js @@ -16,14 +16,10 @@ }, runCommand: function(db, cmd, opts) { commandsRan.push({db: db, cmd: cmd, opts: opts}); - return { - ok: 1.0 - }; + return {ok: 1.0}; }, getReadPref: function() { - return { - mode: "secondaryPreferred" - }; + return {mode: "secondaryPreferred"}; }, getReadPrefMode: function() { return "secondaryPreferred"; diff --git a/jstests/aggregation/bugs/server18222.js b/jstests/aggregation/bugs/server18222.js index 1a46ff349c8..cea52b3970d 100644 --- a/jstests/aggregation/bugs/server18222.js +++ b/jstests/aggregation/bugs/server18222.js @@ -20,8 +20,11 @@ assert.writeOK(coll.insert({_id: 10, x: ['0']})); // Project field is_array to represent whether the field x was an array. - var results = - coll.aggregate([{$sort: {_id: 1}}, {$project: {isArray: {$isArray: '$x'}}}, ]).toArray(); + var results = coll.aggregate([ + {$sort: {_id: 1}}, + {$project: {isArray: {$isArray: '$x'}}}, + ]) + .toArray(); var expectedResults = [ {_id: 0, isArray: false}, {_id: 1, isArray: false}, diff --git a/jstests/aggregation/bugs/server19095.js b/jstests/aggregation/bugs/server19095.js index 30d2610aad9..875a7d16a9d 100644 --- a/jstests/aggregation/bugs/server19095.js +++ b/jstests/aggregation/bugs/server19095.js @@ -55,11 +55,10 @@ load("jstests/aggregation/extras/utils.js"); {_id: 1, a: null, "same": [{_id: 1, b: null}, {_id: 2}]}, {_id: 2, "same": [{_id: 1, b: null}, {_id: 2}]} ]; - testPipeline([{ - $lookup: {localField: "nonexistent", foreignField: "b", from: "from", as: "same"} - }], - expectedResults, - coll); + testPipeline( + [{$lookup: {localField: "nonexistent", foreignField: "b", from: "from", as: "same"}}], + expectedResults, + coll); // If foreignField is nonexistent, it is treated as if it is null. expectedResults = [ @@ -67,25 +66,22 @@ load("jstests/aggregation/extras/utils.js"); {_id: 1, a: null, "same": [{_id: 0, b: 1}, {_id: 1, b: null}, {_id: 2}]}, {_id: 2, "same": [{_id: 0, b: 1}, {_id: 1, b: null}, {_id: 2}]} ]; - testPipeline([{ - $lookup: {localField: "a", foreignField: "nonexistent", from: "from", as: "same"} - }], - expectedResults, - coll); + testPipeline( + [{$lookup: {localField: "a", foreignField: "nonexistent", from: "from", as: "same"}}], + expectedResults, + coll); // If there are no matches or the from coll doesn't exist, the result is an empty array. expectedResults = [{_id: 0, a: 1, "same": []}, {_id: 1, a: null, "same": []}, {_id: 2, "same": []}]; - testPipeline([{ - $lookup: {localField: "_id", foreignField: "nonexistent", from: "from", as: "same"} - }], - expectedResults, - coll); - testPipeline([{ - $lookup: {localField: "a", foreignField: "b", from: "nonexistent", as: "same"} - }], - expectedResults, - coll); + testPipeline( + [{$lookup: {localField: "_id", foreignField: "nonexistent", from: "from", as: "same"}}], + expectedResults, + coll); + testPipeline( + [{$lookup: {localField: "a", foreignField: "b", from: "nonexistent", as: "same"}}], + expectedResults, + coll); // If field name specified by "as" already exists, it is overwritten. expectedResults = [ @@ -106,13 +102,14 @@ load("jstests/aggregation/extras/utils.js"); }, {_id: 2, "c": [{_id: 1, b: null}, {_id: 2}], "d": [{_id: 1, b: null}, {_id: 2}]} ]; - testPipeline([ - {$lookup: {localField: "a", foreignField: "b", from: "from", as: "c"}}, - {$project: {"a": 1, "c": 1}}, - {$lookup: {localField: "a", foreignField: "b", from: "from", as: "d"}} - ], - expectedResults, - coll); + testPipeline( + [ + {$lookup: {localField: "a", foreignField: "b", from: "from", as: "c"}}, + {$project: {"a": 1, "c": 1}}, + {$lookup: {localField: "a", foreignField: "b", from: "from", as: "d"}} + ], + expectedResults, + coll); // // Coalescing with $unwind. @@ -126,12 +123,13 @@ load("jstests/aggregation/extras/utils.js"); {_id: 2, same: {_id: 1, b: null}}, {_id: 2, same: {_id: 2}} ]; - testPipeline([ - {$lookup: {localField: "a", foreignField: "b", from: "from", as: "same"}}, - {$unwind: {path: "$same"}} - ], - expectedResults, - coll); + testPipeline( + [ + {$lookup: {localField: "a", foreignField: "b", from: "from", as: "same"}}, + {$unwind: {path: "$same"}} + ], + expectedResults, + coll); // An $unwind on the "as" field, with includeArrayIndex. expectedResults = [ @@ -141,39 +139,51 @@ load("jstests/aggregation/extras/utils.js"); {_id: 2, same: {_id: 1, b: null}, index: NumberLong(0)}, {_id: 2, same: {_id: 2}, index: NumberLong(1)}, ]; - testPipeline([ - {$lookup: {localField: "a", foreignField: "b", from: "from", as: "same"}}, - {$unwind: {path: "$same", includeArrayIndex: "index"}} - ], - expectedResults, - coll); + testPipeline( + [ + {$lookup: {localField: "a", foreignField: "b", from: "from", as: "same"}}, + {$unwind: {path: "$same", includeArrayIndex: "index"}} + ], + expectedResults, + coll); // Normal $unwind with no matching documents. expectedResults = []; - testPipeline([ - {$lookup: {localField: "_id", foreignField: "nonexistent", from: "from", as: "same"}}, - {$unwind: {path: "$same"}} - ], - expectedResults, - coll); + testPipeline( + [ + {$lookup: {localField: "_id", foreignField: "nonexistent", from: "from", as: "same"}}, + {$unwind: {path: "$same"}} + ], + expectedResults, + coll); // $unwind with preserveNullAndEmptyArray with no matching documents. - expectedResults = [{_id: 0, a: 1}, {_id: 1, a: null}, {_id: 2}, ]; - testPipeline([ - {$lookup: {localField: "_id", foreignField: "nonexistent", from: "from", as: "same"}}, - {$unwind: {path: "$same", preserveNullAndEmptyArrays: true}} - ], - expectedResults, - coll); + expectedResults = [ + {_id: 0, a: 1}, + {_id: 1, a: null}, + {_id: 2}, + ]; + testPipeline( + [ + {$lookup: {localField: "_id", foreignField: "nonexistent", from: "from", as: "same"}}, + {$unwind: {path: "$same", preserveNullAndEmptyArrays: true}} + ], + expectedResults, + coll); // $unwind with preserveNullAndEmptyArray, some with matching documents, some without. - expectedResults = [{_id: 0, a: 1}, {_id: 1, a: null, same: {_id: 0, b: 1}}, {_id: 2}, ]; - testPipeline([ - {$lookup: {localField: "_id", foreignField: "b", from: "from", as: "same"}}, - {$unwind: {path: "$same", preserveNullAndEmptyArrays: true}} - ], - expectedResults, - coll); + expectedResults = [ + {_id: 0, a: 1}, + {_id: 1, a: null, same: {_id: 0, b: 1}}, + {_id: 2}, + ]; + testPipeline( + [ + {$lookup: {localField: "_id", foreignField: "b", from: "from", as: "same"}}, + {$unwind: {path: "$same", preserveNullAndEmptyArrays: true}} + ], + expectedResults, + coll); // $unwind with preserveNullAndEmptyArray and includeArrayIndex, some with matching // documents, some without. @@ -182,15 +192,16 @@ load("jstests/aggregation/extras/utils.js"); {_id: 1, a: null, same: {_id: 0, b: 1}, index: NumberLong(0)}, {_id: 2, index: null}, ]; - testPipeline([ - {$lookup: {localField: "_id", foreignField: "b", from: "from", as: "same"}}, - { - $unwind: - {path: "$same", preserveNullAndEmptyArrays: true, includeArrayIndex: "index"} - } - ], - expectedResults, - coll); + testPipeline( + [ + {$lookup: {localField: "_id", foreignField: "b", from: "from", as: "same"}}, + { + $unwind: + {path: "$same", preserveNullAndEmptyArrays: true, includeArrayIndex: "index"} + } + ], + expectedResults, + coll); // // Dependencies. @@ -203,12 +214,13 @@ load("jstests/aggregation/extras/utils.js"); {_id: 1, "same": [{_id: 1, b: null}, {_id: 2}]}, {_id: 2, "same": [{_id: 1, b: null}, {_id: 2}]} ]; - testPipeline([ - {$lookup: {localField: "a", foreignField: "b", from: "from", as: "same"}}, - {$project: {"same": 1}} - ], - expectedResults, - coll); + testPipeline( + [ + {$lookup: {localField: "a", foreignField: "b", from: "from", as: "same"}}, + {$project: {"same": 1}} + ], + expectedResults, + coll); // // Dotted field paths. @@ -277,12 +289,7 @@ load("jstests/aggregation/extras/utils.js"); } ]; expectedResults = [ - { - _id: 0, - a: {b: 1}, - same: {documents: {_id: 0, target: 1}}, - c: {d: {e: NumberLong(0)}} - }, + {_id: 0, a: {b: 1}, same: {documents: {_id: 0, target: 1}}, c: {d: {e: NumberLong(0)}}}, {_id: 1, same: {}, c: {d: {e: null}}}, ]; testPipeline(pipeline, expectedResults, coll); @@ -401,9 +408,8 @@ load("jstests/aggregation/extras/utils.js"); // An error is thrown if the from collection is sharded. assert(sharded.adminCommand({shardCollection: "test.from", key: {_id: 1}})); - assertErrorCode( - sharded.getDB('test').lookUp, - [{$lookup: {localField: "a", foreignField: "b", from: "from", as: "same"}}], - 28769); + assertErrorCode(sharded.getDB('test').lookUp, + [{$lookup: {localField: "a", foreignField: "b", from: "from", as: "same"}}], + 28769); sharded.stop(); }()); diff --git a/jstests/aggregation/bugs/server20163.js b/jstests/aggregation/bugs/server20163.js index 501a6cc546a..e61ba606c24 100644 --- a/jstests/aggregation/bugs/server20163.js +++ b/jstests/aggregation/bugs/server20163.js @@ -12,182 +12,127 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode. var zipObj = 3; assertErrorCode(coll, - [{$project: {zipped: {$zip: zipObj}}}], + [{$project: {zipped: {$zip: zipObj}}}], 34460, "$zip requires an object" + " as an argument."); - zipObj = { - inputs: [] - }; + zipObj = {inputs: []}; assertErrorCode(coll, - [{$project: {zipped: {$zip: zipObj}}}], + [{$project: {zipped: {$zip: zipObj}}}], 34465, "$zip requires at least" + " one input array"); - zipObj = { - inputs: {"a": "b"} - }; + zipObj = {inputs: {"a": "b"}}; assertErrorCode(coll, [{$project: {zipped: {$zip: zipObj}}}], 34461, "inputs is not an array"); - zipObj = { - inputs: ["$a"], - defaults: ["A"] - }; + zipObj = {inputs: ["$a"], defaults: ["A"]}; assertErrorCode(coll, - [{$project: {zipped: {$zip: zipObj}}}], + [{$project: {zipped: {$zip: zipObj}}}], 34466, "cannot specify defaults" + " unless useLongestLength is true."); - zipObj = { - inputs: ["$a"], - defaults: ["A", "B"], - useLongestLength: true - }; + zipObj = {inputs: ["$a"], defaults: ["A", "B"], useLongestLength: true}; assertErrorCode(coll, - [{$project: {zipped: {$zip: zipObj}}}], + [{$project: {zipped: {$zip: zipObj}}}], 34467, "inputs and defaults" + " must be the same length."); - zipObj = { - inputs: ["$a"], - defaults: {"a": "b"} - }; + zipObj = {inputs: ["$a"], defaults: {"a": "b"}}; assertErrorCode( coll, [{$project: {zipped: {$zip: zipObj}}}], 34462, "defaults is not an" + " array"); - zipObj = { - inputs: ["$a"], - defaults: ["A"], - useLongestLength: 1 - }; + zipObj = {inputs: ["$a"], defaults: ["A"], useLongestLength: 1}; assertErrorCode( coll, [{$project: {zipped: {$zip: zipObj}}}], 34463, "useLongestLength is not" + " a bool"); - zipObj = { - inputs: ["$a", "$b"], - defaults: ["A"], - notAField: 1 - }; + zipObj = {inputs: ["$a", "$b"], defaults: ["A"], notAField: 1}; assertErrorCode(coll, [{$project: {zipped: {$zip: zipObj}}}], 34464, "unknown argument"); - zipObj = { - inputs: ["A", "B"] - }; + zipObj = {inputs: ["A", "B"]}; assertErrorCode(coll, - [{$project: {zipped: {$zip: zipObj}}}], + [{$project: {zipped: {$zip: zipObj}}}], 34468, "an element of inputs" + " was not an array."); - zipObj = { - inputs: [[1, 2, 3], ["A", "B", "C"]] - }; + zipObj = {inputs: [[1, 2, 3], ["A", "B", "C"]]}; var res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); var output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, [[1, "A"], [2, "B"], [3, "C"]]); - zipObj = { - inputs: [[1, 2, 3], null] - }; + zipObj = {inputs: [[1, 2, 3], null]}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, null); - zipObj = { - inputs: [null, [1, 2, 3]] - }; + zipObj = {inputs: [null, [1, 2, 3]]}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, null); - zipObj = { - inputs: ["$missing", [1, 2, 3]] - }; + zipObj = {inputs: ["$missing", [1, 2, 3]]}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, null); - zipObj = { - inputs: [undefined, [1, 2, 3]] - }; + zipObj = {inputs: [undefined, [1, 2, 3]]}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, null); - zipObj = { - inputs: [[1, 2, 3], ["A", "B"]] - }; + zipObj = {inputs: [[1, 2, 3], ["A", "B"]]}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, [[1, "A"], [2, "B"]]); - zipObj = { - inputs: [["A", "B"], [1, 2, 3]] - }; + zipObj = {inputs: [["A", "B"], [1, 2, 3]]}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, [["A", 1], ["B", 2]]); - zipObj = { - inputs: [[], []] - }; + zipObj = {inputs: [[], []]}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, []); - zipObj = { - inputs: [["$short"], ["$long"]] - }; + zipObj = {inputs: [["$short"], ["$long"]]}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, [[['x', 'y'], [1, 2, 3]]]); - zipObj = { - inputs: ["$short", "$long"] - }; + zipObj = {inputs: ["$short", "$long"]}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, [['x', 1], ['y', 2]]); - zipObj = { - inputs: [["$long"]] - }; + zipObj = {inputs: [["$long"]]}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, [[[1, 2, 3]]]); - zipObj = { - inputs: [[1, 2, 3], ['a', 'b', 'c'], ['c', 'b', 'a']] - }; + zipObj = {inputs: [[1, 2, 3], ['a', 'b', 'c'], ['c', 'b', 'a']]}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, [[1, 'a', 'c'], [2, 'b', 'b'], [3, 'c', 'a']]); - zipObj = { - inputs: [[1, 2, 3], ["A", "B"]], - defaults: ["C", "D"], - useLongestLength: true - }; + zipObj = {inputs: [[1, 2, 3], ["A", "B"]], defaults: ["C", "D"], useLongestLength: true}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); assert.eq(output[0].zipped, [[1, "A"], [2, "B"], [3, "D"]]); - zipObj = { - inputs: [[1, 2, 3], ["A", "B"]], - useLongestLength: true - }; + zipObj = {inputs: [[1, 2, 3], ["A", "B"]], useLongestLength: true}; res = coll.aggregate([{$project: {zipped: {$zip: zipObj}}}]); output = res.toArray(); assert.eq(1, output.length); diff --git a/jstests/aggregation/bugs/server20169.js b/jstests/aggregation/bugs/server20169.js index f4d8735701e..27995b8030c 100644 --- a/jstests/aggregation/bugs/server20169.js +++ b/jstests/aggregation/bugs/server20169.js @@ -13,49 +13,49 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode. var rangeObj = [1]; assertErrorCode(coll, - [{$project: {range: {$range: rangeObj}}}], + [{$project: {range: {$range: rangeObj}}}], 28667, "range requires two" + " or three arguments"); rangeObj = ["a", 1]; assertErrorCode(coll, - [{$project: {range: {$range: rangeObj}}}], + [{$project: {range: {$range: rangeObj}}}], 34443, "range requires a" + " numeric starting value"); rangeObj = [1.1, 1]; assertErrorCode(coll, - [{$project: {range: {$range: rangeObj}}}], + [{$project: {range: {$range: rangeObj}}}], 34444, "range requires an" + " integral starting value"); rangeObj = [1, "a"]; assertErrorCode(coll, - [{$project: {range: {$range: rangeObj}}}], + [{$project: {range: {$range: rangeObj}}}], 34445, "range requires a" + " numeric ending value"); rangeObj = [1, 1.1]; assertErrorCode(coll, - [{$project: {range: {$range: rangeObj}}}], + [{$project: {range: {$range: rangeObj}}}], 34446, "range requires an" + " integral ending value"); rangeObj = [1, 3, "a"]; assertErrorCode(coll, - [{$project: {range: {$range: rangeObj}}}], + [{$project: {range: {$range: rangeObj}}}], 34447, "range requires a" + " numeric step value"); rangeObj = [1, 3, 1.1]; assertErrorCode(coll, - [{$project: {range: {$range: rangeObj}}}], + [{$project: {range: {$range: rangeObj}}}], 34448, "range requires an" + " integral step value"); rangeObj = [1, 3, 0]; assertErrorCode(coll, - [{$project: {range: {$range: rangeObj}}}], + [{$project: {range: {$range: rangeObj}}}], 34449, "range requires a" + " non-zero step value"); }()); diff --git a/jstests/aggregation/bugs/server21632.js b/jstests/aggregation/bugs/server21632.js index 5aa9a315b5f..c99834c6f73 100644 --- a/jstests/aggregation/bugs/server21632.js +++ b/jstests/aggregation/bugs/server21632.js @@ -35,10 +35,7 @@ // If there is only one document, we should get that document. var paddingStr = "abcdefghijklmnopqrstuvwxyz"; - var firstDoc = { - _id: 0, - paddingStr: paddingStr - }; + var firstDoc = {_id: 0, paddingStr: paddingStr}; assert.writeOK(coll.insert(firstDoc)); assert.eq([firstDoc], coll.aggregate([{$sample: {size: 1}}]).toArray()); assert.eq([firstDoc], coll.aggregate([{$sample: {size: 10}}]).toArray()); diff --git a/jstests/aggregation/bugs/server22093.js b/jstests/aggregation/bugs/server22093.js index aca39a4e789..61302bbf4cd 100644 --- a/jstests/aggregation/bugs/server22093.js +++ b/jstests/aggregation/bugs/server22093.js @@ -22,9 +22,8 @@ load('jstests/libs/analyze_plan.js'); assert.eq(simpleGroup.length, 1); assert.eq(simpleGroup[0]["count"], 15); - var explained = - coll.explain() - .aggregate([{$match: {foo: {$gt: 0}}}, {$group: {_id: null, count: {$sum: 1}}}]); + var explained = coll.explain().aggregate( + [{$match: {foo: {$gt: 0}}}, {$group: {_id: null, count: {$sum: 1}}}]); assert(planHasStage(explained.stages[0].$cursor.queryPlanner.winningPlan, "COUNT_SCAN")); diff --git a/jstests/aggregation/bugs/server22580.js b/jstests/aggregation/bugs/server22580.js index afbfdd00dcd..3a448173875 100644 --- a/jstests/aggregation/bugs/server22580.js +++ b/jstests/aggregation/bugs/server22580.js @@ -12,32 +12,32 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode. coll.insert({}); assertErrorCode(coll, - [{$project: {substr: {$substrCP: ["abc", 0, "a"]}}}], + [{$project: {substr: {$substrCP: ["abc", 0, "a"]}}}], 34452, "$substrCP" + " does not accept non-numeric types as a length."); assertErrorCode(coll, - [{$project: {substr: {$substrCP: ["abc", 0, NaN]}}}], + [{$project: {substr: {$substrCP: ["abc", 0, NaN]}}}], 34453, "$substrCP" + " does not accept non-integers as a length."); assertErrorCode(coll, - [{$project: {substr: {$substrCP: ["abc", "abc", 3]}}}], + [{$project: {substr: {$substrCP: ["abc", "abc", 3]}}}], 34450, "$substrCP does not accept non-numeric types as a starting index."); assertErrorCode(coll, - [{$project: {substr: {$substrCP: ["abc", 2.2, 3]}}}], + [{$project: {substr: {$substrCP: ["abc", 2.2, 3]}}}], 34451, "$substrCP" + " does not accept non-integers as a starting index."); assertErrorCode(coll, - [{$project: {substr: {$substrCP: ["abc", -1, 3]}}}], + [{$project: {substr: {$substrCP: ["abc", -1, 3]}}}], 34455, "$substrCP " + "does not accept negative integers as inputs."); assertErrorCode(coll, - [{$project: {substr: {$substrCP: ["abc", 1, -3]}}}], + [{$project: {substr: {$substrCP: ["abc", 1, -3]}}}], 34454, "$substrCP " + "does not accept negative integers as inputs."); }()); diff --git a/jstests/aggregation/bugs/server3253.js b/jstests/aggregation/bugs/server3253.js index 1adab9ca977..774712ecb2f 100644 --- a/jstests/aggregation/bugs/server3253.js +++ b/jstests/aggregation/bugs/server3253.js @@ -58,7 +58,7 @@ assert.eq([], listCollections(/tmp\.agg_out/)); // basic test test(input, - [{$project: {a: {$add: ['$_id', '$_id']}}}], + [{$project: {a: {$add: ['$_id', '$_id']}}}], [{_id: 1, a: 2}, {_id: 2, a: 4}, {_id: 3, a: 6}]); // test with indexes @@ -66,7 +66,7 @@ assert.eq(output.getIndexes().length, 1); output.ensureIndex({a: 1}); assert.eq(output.getIndexes().length, 2); test(input, - [{$project: {a: {$multiply: ['$_id', '$_id']}}}], + [{$project: {a: {$multiply: ['$_id', '$_id']}}}], [{_id: 1, a: 1}, {_id: 2, a: 4}, {_id: 3, a: 9}]); // test with empty result set and make sure old result is gone, but indexes remain @@ -81,13 +81,11 @@ test(input, [{$project: {b: "$_id"}}], [{_id: 1, b: 1}, {_id: 2, b: 2}, {_id: 3, // test with full text index output.ensureIndex({c: "text"}); assert.eq(output.getIndexes().length, 4); -test(input, - [{$project: {c: {$concat: ["hello there ", "_id"]}}}], - [ - {_id: 1, c: "hello there _id"}, - {_id: 2, c: "hello there _id"}, - {_id: 3, c: "hello there _id"} - ]); +test(input, [{$project: {c: {$concat: ["hello there ", "_id"]}}}], [ + {_id: 1, c: "hello there _id"}, + {_id: 2, c: "hello there _id"}, + {_id: 3, c: "hello there _id"} +]); // test with capped collection cappedOutput.drop(); diff --git a/jstests/aggregation/bugs/server4588.js b/jstests/aggregation/bugs/server4588.js index ba49c78e9ea..49f41283f6d 100644 --- a/jstests/aggregation/bugs/server4588.js +++ b/jstests/aggregation/bugs/server4588.js @@ -13,7 +13,12 @@ // Without includeArrayIndex. var actualResults = coll.aggregate([{$unwind: {path: "$x"}}]).toArray(); - var expectedResults = [{_id: 3, x: 1}, {_id: 3, x: 2}, {_id: 3, x: 3}, {_id: 4, x: 5}, ]; + var expectedResults = [ + {_id: 3, x: 1}, + {_id: 3, x: 2}, + {_id: 3, x: 3}, + {_id: 4, x: 5}, + ]; assert.eq(expectedResults, actualResults, "Incorrect results for normal $unwind"); // With includeArrayIndex, index inserted into a new field. @@ -28,9 +33,12 @@ // With both includeArrayIndex and preserveNullAndEmptyArrays. // TODO: update this test when SERVER-20168 is resolved. - actualResults = coll.aggregate([{ - $unwind: {path: "$x", includeArrayIndex: "index", preserveNullAndEmptyArrays: true} - }]).toArray(); + actualResults = + coll.aggregate([{ + $unwind: + {path: "$x", includeArrayIndex: "index", preserveNullAndEmptyArrays: true} + }]) + .toArray(); expectedResults = [ {_id: 0, index: null}, {_id: 1, x: null, index: null}, diff --git a/jstests/aggregation/bugs/server5044.js b/jstests/aggregation/bugs/server5044.js index 945f31c302c..f1f77a1991d 100644 --- a/jstests/aggregation/bugs/server5044.js +++ b/jstests/aggregation/bugs/server5044.js @@ -10,12 +10,12 @@ function test(data, popExpected, sampExpected) { assert.writeOK(t.insert({num: data[i]})); var res = t.aggregate({ - $group: { - _id: 1, - pop: {$stdDevPop: '$num'}, - samp: {$stdDevSamp: '$num'}, - } - }).next(); + $group: { + _id: 1, + pop: {$stdDevPop: '$num'}, + samp: {$stdDevSamp: '$num'}, + } + }).next(); if (popExpected === null) { assert.isnull(res.pop); diff --git a/jstests/aggregation/bugs/server6121.js b/jstests/aggregation/bugs/server6121.js index 97d5a4d72c9..b7ea33abdaa 100644 --- a/jstests/aggregation/bugs/server6121.js +++ b/jstests/aggregation/bugs/server6121.js @@ -22,20 +22,22 @@ db.s6121.drop(); db.s6121.save({date: new Timestamp(1341337661, 1)}); db.s6121.save({date: new Date(1341337661000)}); // Aggregate checking various combinations of the constant and the field -var s6121 = db.s6121.aggregate({ - $project: { - _id: 0, - dayOfMonth: {$dayOfMonth: '$date'}, - dayOfWeek: {$dayOfWeek: '$date'}, - dayOfYear: {$dayOfYear: '$date'}, - hour: {$hour: '$date'}, - minute: {$minute: '$date'}, - month: {$month: '$date'}, - second: {$second: '$date'}, - week: {$week: '$date'}, - year: {$year: '$date'} - } -}).toArray(); +var s6121 = db.s6121 + .aggregate({ + $project: { + _id: 0, + dayOfMonth: {$dayOfMonth: '$date'}, + dayOfWeek: {$dayOfWeek: '$date'}, + dayOfYear: {$dayOfYear: '$date'}, + hour: {$hour: '$date'}, + minute: {$minute: '$date'}, + month: {$month: '$date'}, + second: {$second: '$date'}, + week: {$week: '$date'}, + year: {$year: '$date'} + } + }) + .toArray(); // Assert the two entries are equal assert.eq(s6121[0], s6121[1], 's6121 failed'); diff --git a/jstests/aggregation/bugs/server6125.js b/jstests/aggregation/bugs/server6125.js index 746c191d8fe..bfc4f471318 100644 --- a/jstests/aggregation/bugs/server6125.js +++ b/jstests/aggregation/bugs/server6125.js @@ -10,9 +10,7 @@ // to make results array nested (problem 2) function nestArray(nstArray) { for (x = 0; x < nstArray.length; x++) { - nstArray[x].a = { - b: nstArray[x].a - }; + nstArray[x].a = {b: nstArray[x].a}; } } diff --git a/jstests/aggregation/bugs/server6131.js b/jstests/aggregation/bugs/server6131.js index 602894ab721..640eea2723e 100644 --- a/jstests/aggregation/bugs/server6131.js +++ b/jstests/aggregation/bugs/server6131.js @@ -11,11 +11,7 @@ t.drop(); // An empty array document is dropped. t.save({_id: 0, a: 1, b: [], c: 2}); -assertAggregationResults([], - { -$unwind: - '$b' - }); +assertAggregationResults([], {$unwind: '$b'}); // Values from a nonempty array in another document are unwound. t.save({_id: 1, b: [4, 5]}); @@ -29,48 +25,28 @@ t.drop(); // A nested empty array document is dropped. t.save({_id: 0, a: 1, b: {x: 10, y: [], z: 20}, c: 2}); -assertAggregationResults([], - { -$unwind: - '$b.y' - }); +assertAggregationResults([], {$unwind: '$b.y'}); t.drop(); // A null value document is dropped. t.save({_id: 0, a: 1, b: null, c: 2}); -assertAggregationResults([], - { -$unwind: - '$b' - }); +assertAggregationResults([], {$unwind: '$b'}); t.drop(); // A missing value causes the document to be dropped. t.save({_id: 0, a: 1, c: 2}); -assertAggregationResults([], - { -$unwind: - '$b' - }); +assertAggregationResults([], {$unwind: '$b'}); t.drop(); // A missing value in an existing nested object causes the document to be dropped. t.save({_id: 0, a: 1, b: {d: 4}, c: 2}); -assertAggregationResults([], - { -$unwind: - '$b.y' - }); +assertAggregationResults([], {$unwind: '$b.y'}); t.drop(); // A missing value in a missing nested object causes the document to be dropped. t.save({_id: 0, a: 1, b: 10, c: 2}); -assertAggregationResults([], - { -$unwind: - '$b.y' - }); +assertAggregationResults([], {$unwind: '$b.y'}); diff --git a/jstests/aggregation/bugs/server6179.js b/jstests/aggregation/bugs/server6179.js index 20158af7fb7..c05103a13b8 100644 --- a/jstests/aggregation/bugs/server6179.js +++ b/jstests/aggregation/bugs/server6179.js @@ -28,9 +28,11 @@ {movechunk: "test.data", find: {_id: 50}, to: s.getOther(s.getPrimaryShard("test")).name}); // Check that we get results rather than an error - var result = d.data.aggregate({$group: {_id: '$_id', i: {$first: '$i'}}}, - {$group: {_id: '$i', avg_id: {$avg: '$_id'}}}, - {$sort: {_id: 1}}).toArray(); + var result = d.data + .aggregate({$group: {_id: '$_id', i: {$first: '$i'}}}, + {$group: {_id: '$i', avg_id: {$avg: '$_id'}}}, + {$sort: {_id: 1}}) + .toArray(); expected = [ {"_id": 0, "avg_id": 45}, {"_id": 1, "avg_id": 46}, diff --git a/jstests/aggregation/bugs/server6189.js b/jstests/aggregation/bugs/server6189.js index 4cb615f0659..f8cb88194e2 100644 --- a/jstests/aggregation/bugs/server6189.js +++ b/jstests/aggregation/bugs/server6189.js @@ -11,36 +11,35 @@ function test(date, testSynthetics) { : 'ISODate("%Y-%m-%dT%H:%M:%S.%LZ")'; // Can't use aggregate helper or assertErrorCode because we need to handle multiple error types - var res = c.runCommand('aggregate', - { - pipeline: [{ - $project: { - _id: 0, - year: {$year: '$date'}, - month: {$month: '$date'}, - dayOfMonth: {$dayOfMonth: '$date'}, - hour: {$hour: '$date'}, - minute: {$minute: '$date'}, - second: {$second: '$date'} - - // server-6666 - , - millisecond: {$millisecond: '$date'} - - // server-9289 - , - millisecondPlusTen: {$millisecond: {$add: ['$date', 10]}} - - // $substr will call coerceToString - , - string: {$substr: ['$date', 0, 1000]} - - // server-11118 - , - format: {$dateToString: {format: ISOfmt, date: '$date'}} - } - }] - }); + var res = c.runCommand('aggregate', { + pipeline: [{ + $project: { + _id: 0, + year: {$year: '$date'}, + month: {$month: '$date'}, + dayOfMonth: {$dayOfMonth: '$date'}, + hour: {$hour: '$date'}, + minute: {$minute: '$date'}, + second: {$second: '$date'} + + // server-6666 + , + millisecond: {$millisecond: '$date'} + + // server-9289 + , + millisecondPlusTen: {$millisecond: {$add: ['$date', 10]}} + + // $substr will call coerceToString + , + string: {$substr: ['$date', 0, 1000]} + + // server-11118 + , + format: {$dateToString: {format: ISOfmt, date: '$date'}} + } + }] + }); if (date.valueOf() < 0 && _isWindows() && res.code == 16422) { // some versions of windows (but not all) fail with dates before 1970 @@ -55,20 +54,19 @@ function test(date, testSynthetics) { } assert.commandWorked(res); - assert.eq(res.result[0], - { - year: date.getUTCFullYear(), - month: date.getUTCMonth() + 1 // jan == 1 - , - dayOfMonth: date.getUTCDate(), - hour: date.getUTCHours(), - minute: date.getUTCMinutes(), - second: date.getUTCSeconds(), - millisecond: date.getUTCMilliseconds(), - millisecondPlusTen: ((date.getUTCMilliseconds() + 10) % 1000), - string: date.tojson().slice(9, 28), - format: date.tojson() - }); + assert.eq(res.result[0], { + year: date.getUTCFullYear(), + month: date.getUTCMonth() + 1 // jan == 1 + , + dayOfMonth: date.getUTCDate(), + hour: date.getUTCHours(), + minute: date.getUTCMinutes(), + second: date.getUTCSeconds(), + millisecond: date.getUTCMilliseconds(), + millisecondPlusTen: ((date.getUTCMilliseconds() + 10) % 1000), + string: date.tojson().slice(9, 28), + format: date.tojson() + }); if (testSynthetics) { // Tests with this set all have the same value for these fields diff --git a/jstests/aggregation/bugs/server6190.js b/jstests/aggregation/bugs/server6190.js index d32a652e74b..ea7bfe1601b 100644 --- a/jstests/aggregation/bugs/server6190.js +++ b/jstests/aggregation/bugs/server6190.js @@ -8,8 +8,9 @@ t.drop(); t.save({}); function week(date) { - return t.aggregate({$project: {a: {$week: date}}}, - {$match: {a: {$type: 16 /* Int type expected */}}}) + return t + .aggregate({$project: {a: {$week: date}}}, + {$match: {a: {$type: 16 /* Int type expected */}}}) .toArray()[0] .a; } diff --git a/jstests/aggregation/bugs/server6195.js b/jstests/aggregation/bugs/server6195.js index cca80a14ad5..13dccd10877 100644 --- a/jstests/aggregation/bugs/server6195.js +++ b/jstests/aggregation/bugs/server6195.js @@ -27,7 +27,7 @@ assertErrorCode(c, {$project: {str: {$concat: [1]}}}, 16702); assertErrorCode(c, {$project: {str: {$concat: [NumberInt(1)]}}}, 16702); assertErrorCode(c, {$project: {str: {$concat: [NumberLong(1)]}}}, 16702); assertErrorCode(c, {$project: {str: {$concat: [true]}}}, 16702); -assertErrorCode(c, {$project: {str: {$concat: [function(){}]}}}, 16702); +assertErrorCode(c, {$project: {str: {$concat: [function() {}]}}}, 16702); assertErrorCode(c, {$project: {str: {$concat: [{}]}}}, 16702); assertErrorCode(c, {$project: {str: {$concat: [[]]}}}, 16702); assertErrorCode(c, {$project: {str: {$concat: [new Timestamp(0, 0)]}}}, 16702); diff --git a/jstests/aggregation/bugs/server6529.js b/jstests/aggregation/bugs/server6529.js index 1bc4119c547..94af2f1fc72 100644 --- a/jstests/aggregation/bugs/server6529.js +++ b/jstests/aggregation/bugs/server6529.js @@ -13,16 +13,16 @@ assertErrorCode(c, {$group: {_id: {a: 1}}}, 17390); // but any amount of nesting in a project should work assert.eq(c.aggregate({$project: {_id: 0, a: {b: {c: {d: {e: {f: {g: 1}}}}}}}}).toArray(), - [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); + [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); assert.eq(c.aggregate({$project: {_id: 0, a: {b: {c: {d: {e: {f: 1}}}}}}}).toArray(), - [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); + [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); assert.eq(c.aggregate({$project: {_id: 0, a: {b: {c: {d: {e: 1}}}}}}).toArray(), - [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); + [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); assert.eq(c.aggregate({$project: {_id: 0, a: {b: {c: {d: 1}}}}}).toArray(), - [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); + [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); assert.eq(c.aggregate({$project: {_id: 0, a: {b: {c: 1}}}}).toArray(), - [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); + [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); assert.eq(c.aggregate({$project: {_id: 0, a: {b: 1}}}).toArray(), - [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); + [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); assert.eq(c.aggregate({$project: {_id: 0, a: 1}}).toArray(), - [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); + [{a: {b: {c: {d: {e: {f: {g: 19}}}}}}}]); diff --git a/jstests/aggregation/bugs/server6531.js b/jstests/aggregation/bugs/server6531.js index 7d117ce6905..7d020d79219 100644 --- a/jstests/aggregation/bugs/server6531.js +++ b/jstests/aggregation/bugs/server6531.js @@ -10,12 +10,8 @@ for (var x = 0; x < 10; x++) { } function test(variant) { - query = { - loc: {$within: {$center: [[5, 5], 3]}} - }; - sort = { - _id: 1 - }; + query = {loc: {$within: {$center: [[5, 5], 3]}}}; + sort = {_id: 1}; aggOut = c.aggregate({$match: query}, {$sort: sort}); cursor = c.find(query).sort(sort); diff --git a/jstests/aggregation/bugs/server6556.js b/jstests/aggregation/bugs/server6556.js index 636bef6b02c..261dc5a35b5 100644 --- a/jstests/aggregation/bugs/server6556.js +++ b/jstests/aggregation/bugs/server6556.js @@ -7,17 +7,17 @@ c.save({foo: "as\0df"}); // compare the whole string, they should match assert.eq(c.aggregate({$project: {_id: 0, matches: {$eq: ["as\0df", "$foo"]}}}).toArray(), - [{matches: true}]); + [{matches: true}]); // compare with the substring containing only the up to the null, they should not match assert.eq(c.aggregate({ - $project: {_id: 0, matches: {$eq: ["as\0df", {$substrBytes: ["$foo", 0, 3]}]}} -}).toArray(), - [{matches: false}]); + $project: {_id: 0, matches: {$eq: ["as\0df", {$substrBytes: ["$foo", 0, 3]}]}} + }).toArray(), + [{matches: false}]); // partial the other way shouldnt work either assert.eq(c.aggregate({$project: {_id: 0, matches: {$eq: ["as", "$foo"]}}}).toArray(), - [{matches: false}]); + [{matches: false}]); // neither should one that differs after the null assert.eq(c.aggregate({$project: {_id: 0, matches: {$eq: ["as\0de", "$foo"]}}}).toArray(), - [{matches: false}]); + [{matches: false}]); // should assert on fieldpaths with a null assert.throws(c.aggregate, {$project: {_id: 0, matches: {$eq: ["as\0df", "$f\0oo"]}}}); diff --git a/jstests/aggregation/bugs/server7781.js b/jstests/aggregation/bugs/server7781.js index 230a8a64c9f..0a4831fb800 100644 --- a/jstests/aggregation/bugs/server7781.js +++ b/jstests/aggregation/bugs/server7781.js @@ -30,10 +30,7 @@ for (var i = 0; i < cmdOut.length; i++) { massaged = {}; Object.extend(massaged, cmdOut[i].obj, /*deep=*/true); - massaged.stats = { - 'dis': cmdOut[i].dis, - 'loc': cmdOut[i].loc - }; + massaged.stats = {'dis': cmdOut[i].dis, 'loc': cmdOut[i].loc}; if (!friendlyEqual(massaged, aggOut[i])) { allSame = false; // don't bail yet since we want to print all differences @@ -87,12 +84,7 @@ // test with defaults var queryPoint = pointMaker.mkPt(0.25); // stick to center of map - geoCmd = { - geoNear: coll, - near: queryPoint, - includeLocs: true, - spherical: true - }; + geoCmd = {geoNear: coll, near: queryPoint, includeLocs: true, spherical: true}; aggCmd = { $geoNear: { near: queryPoint, diff --git a/jstests/aggregation/bugs/server9840.js b/jstests/aggregation/bugs/server9840.js index b3a73cfc3d7..4316730370a 100644 --- a/jstests/aggregation/bugs/server9840.js +++ b/jstests/aggregation/bugs/server9840.js @@ -27,62 +27,57 @@ test({$add: ['$two', '$$CURRENT.three']}, 5); test({$add: ['$$CURRENT.two', '$$ROOT.nested.four']}, 6); // $let simple -test({$let: {vars: {a: 10}, in: '$$a'}}, 10); -test({$let: {vars: {a: '$zero'}, in: '$$a'}}, 0); -test({$let: {vars: {a: {$add: ['$one', '$two']}, b: 10}, in: {$multiply: ['$$a', '$$b']}}}, 30); +test({$let: {vars: {a: 10}, in : '$$a'}}, 10); +test({$let: {vars: {a: '$zero'}, in : '$$a'}}, 0); +test({$let: {vars: {a: {$add: ['$one', '$two']}, b: 10}, in : {$multiply: ['$$a', '$$b']}}}, 30); // $let changing CURRENT -test({$let: {vars: {CURRENT: '$$ROOT.nested'}, in: {$multiply: ['$four', '$$ROOT.two']}}}, 8); -test( - { - $let: { - vars: {CURRENT: '$$CURRENT.nested'}, // using original value of CURRENT - in: {$multiply: ['$four', '$$ROOT.two']} - } - }, - 8); -test( - { - $let: { - vars: {CURRENT: '$nested'}, // same as last - in: {$multiply: ['$four', '$$ROOT.two']} - } - }, - 8); -test( - { - $let: { - vars: {CURRENT: {$const: {ten: 10}}}, // "artificial" object - in: {$multiply: ['$ten', '$$ROOT.two']} - } - }, - 20); -test( - { - $let: { - vars: {CURRENT: '$three'}, // sets current to the number 3 (not an object) - in: {$multiply: ['$$CURRENT', '$$ROOT.two']} - } - }, - 6); +test({$let: {vars: {CURRENT: '$$ROOT.nested'}, in : {$multiply: ['$four', '$$ROOT.two']}}}, 8); +test({ + $let: { + vars: {CURRENT: '$$CURRENT.nested'}, // using original value of CURRENT + in : {$multiply: ['$four', '$$ROOT.two']} + } +}, + 8); +test({ + $let: { + vars: {CURRENT: '$nested'}, // same as last + in : {$multiply: ['$four', '$$ROOT.two']} + } +}, + 8); +test({ + $let: { + vars: {CURRENT: {$const: {ten: 10}}}, // "artificial" object + in : {$multiply: ['$ten', '$$ROOT.two']} + } +}, + 20); +test({ + $let: { + vars: {CURRENT: '$three'}, // sets current to the number 3 (not an object) + in : {$multiply: ['$$CURRENT', '$$ROOT.two']} + } +}, + 6); // swapping with $let (ensures there is no ordering dependency in vars) -test( - { - $let: { - vars: {x: 6, y: 10}, - in: { - $let: { - vars: {x: '$$y', y: '$$x'}, // now {x:10, y:6} - in: {$subtract: ['$$x', '$$y']} - } - } - } - }, // not commutative! - 4); // 10-6 not 6-10 or 6-6 +test({ + $let: { + vars: {x: 6, y: 10}, + in : { + $let: { + vars: {x: '$$y', y: '$$x'}, // now {x:10, y:6} + in : {$subtract: ['$$x', '$$y']} + } + } + } +}, // not commutative! + 4); // 10-6 not 6-10 or 6-6 // unicode is allowed -test({$let: {vars: {'日本語': 10}, in: '$$日本語'}}, 10); // Japanese for "Japanese language" +test({$let: {vars: {'日本語': 10}, in : '$$日本語'}}, 10); // Japanese for "Japanese language" // Can use ROOT and CURRENT directly with no subfield (SERVER-5916) t.drop(); @@ -90,15 +85,15 @@ t.insert({_id: 'obj'}); assert.eq(t.aggregate({$project: {_id: 0, obj: '$$ROOT'}}).toArray(), [{obj: {_id: 'obj'}}]); assert.eq(t.aggregate({$project: {_id: 0, obj: '$$CURRENT'}}).toArray(), [{obj: {_id: 'obj'}}]); assert.eq(t.aggregate({$group: {_id: 0, objs: {$push: '$$ROOT'}}}).toArray(), - [{_id: 0, objs: [{_id: 'obj'}]}]); + [{_id: 0, objs: [{_id: 'obj'}]}]); assert.eq(t.aggregate({$group: {_id: 0, objs: {$push: '$$CURRENT'}}}).toArray(), - [{_id: 0, objs: [{_id: 'obj'}]}]); + [{_id: 0, objs: [{_id: 'obj'}]}]); // check name validity checks -assertErrorCode(t, {$project: {a: {$let: {vars: {ROOT: 1}, in: '$$ROOT'}}}}, 16867); -assertErrorCode(t, {$project: {a: {$let: {vars: {FOO: 1}, in: '$$FOO'}}}}, 16867); -assertErrorCode(t, {$project: {a: {$let: {vars: {_underbar: 1}, in: '$$FOO'}}}}, 16867); -assertErrorCode(t, {$project: {a: {$let: {vars: {'a.b': 1}, in: '$$FOO'}}}}, 16868); -assertErrorCode(t, {$project: {a: {$let: {vars: {'a b': 1}, in: '$$FOO'}}}}, 16868); +assertErrorCode(t, {$project: {a: {$let: {vars: {ROOT: 1}, in : '$$ROOT'}}}}, 16867); +assertErrorCode(t, {$project: {a: {$let: {vars: {FOO: 1}, in : '$$FOO'}}}}, 16867); +assertErrorCode(t, {$project: {a: {$let: {vars: {_underbar: 1}, in : '$$FOO'}}}}, 16867); +assertErrorCode(t, {$project: {a: {$let: {vars: {'a.b': 1}, in : '$$FOO'}}}}, 16868); +assertErrorCode(t, {$project: {a: {$let: {vars: {'a b': 1}, in : '$$FOO'}}}}, 16868); assertErrorCode(t, {$project: {a: '$$_underbar'}}, 16870); assertErrorCode(t, {$project: {a: '$$with spaces'}}, 16871); diff --git a/jstests/aggregation/bugs/server9841.js b/jstests/aggregation/bugs/server9841.js index 5bf9b32db93..28e6037caf1 100644 --- a/jstests/aggregation/bugs/server9841.js +++ b/jstests/aggregation/bugs/server9841.js @@ -16,27 +16,26 @@ function test(expression, expected) { assert.eq(result, [{res: expected}]); } -test({$map: {input: "$simple", as: "var", in: '$$var'}}, [1, 2, 3, 4]); -test({$map: {input: "$simple", as: "var", in: {$add: [10, '$$var']}}}, [11, 12, 13, 14]); +test({$map: {input: "$simple", as: "var", in : '$$var'}}, [1, 2, 3, 4]); +test({$map: {input: "$simple", as: "var", in : {$add: [10, '$$var']}}}, [11, 12, 13, 14]); -test({$map: {input: "$nested", as: "var", in: '$$var.a'}}, [1, 2]); -test({$map: {input: "$nested", as: "CURRENT", in: '$a'}}, [1, 2]); +test({$map: {input: "$nested", as: "var", in : '$$var.a'}}, [1, 2]); +test({$map: {input: "$nested", as: "CURRENT", in : '$a'}}, [1, 2]); -test({$map: {input: "$mixed", as: "var", in: '$$var.a'}}, +test({$map: {input: "$mixed", as: "var", in : '$$var.a'}}, [1, null, 2, null]); // missing becomes null -test({$map: {input: "$null", as: "var", in: '$$var'}}, null); +test({$map: {input: "$null", as: "var", in : '$$var'}}, null); // can't set ROOT -assertErrorCode(t, {$project: {a: {$map: {input: "$simple", as: "ROOT", in: '$$ROOT'}}}}, 16867); +assertErrorCode(t, {$project: {a: {$map: {input: "$simple", as: "ROOT", in : '$$ROOT'}}}}, 16867); // error on non-array -assertErrorCode(t, {$project: {a: {$map: {input: "$notArray", as: "var", in: '$$var'}}}}, 16883); +assertErrorCode(t, {$project: {a: {$map: {input: "$notArray", as: "var", in : '$$var'}}}}, 16883); // parse errors (missing or extra fields) -assertErrorCode(t, - {$project: {a: {$map: {x: 1, input: "$simple", as: "var", in: '$$var'}}}}, - 16879); -assertErrorCode(t, {$project: {a: {$map: {as: "var", in: '$$var'}}}}, 16880); -assertErrorCode(t, {$project: {a: {$map: {input: "$simple", in: '$$var'}}}}, 16881); +assertErrorCode( + t, {$project: {a: {$map: {x: 1, input: "$simple", as: "var", in : '$$var'}}}}, 16879); +assertErrorCode(t, {$project: {a: {$map: {as: "var", in : '$$var'}}}}, 16880); +assertErrorCode(t, {$project: {a: {$map: {input: "$simple", in : '$$var'}}}}, 16881); assertErrorCode(t, {$project: {a: {$map: {input: "$simple", as: "var"}}}}, 16882); diff --git a/jstests/aggregation/bugs/substr.js b/jstests/aggregation/bugs/substr.js index 9b514eb4679..8581aaf5601 100644 --- a/jstests/aggregation/bugs/substr.js +++ b/jstests/aggregation/bugs/substr.js @@ -108,18 +108,18 @@ assertSubstring('cde', '$z', {$add: ['$b', 1]}, {$add: [2, '$d']}); assert.eq( 'e', t.aggregate({ - $project: { - a: { - $substrBytes: [ - { - $substrBytes: - [{$substrBytes: [{$substrBytes: ['abcdefghij', 1, 6]}, 2, 5]}, 0, 3] - }, - 1, - 1 - ] - } - } - }) + $project: { + a: { + $substrBytes: [ + { + $substrBytes: + [{$substrBytes: [{$substrBytes: ['abcdefghij', 1, 6]}, 2, 5]}, 0, 3] + }, + 1, + 1 + ] + } + } + }) .toArray()[0] .a); diff --git a/jstests/aggregation/bugs/upperlower.js b/jstests/aggregation/bugs/upperlower.js index 60bcba8db20..a393bf3bd72 100644 --- a/jstests/aggregation/bugs/upperlower.js +++ b/jstests/aggregation/bugs/upperlower.js @@ -6,8 +6,9 @@ t.drop(); t.save({}); function assertResult(expectedUpper, expectedLower, string) { - result = t.aggregate({$project: {upper: {$toUpper: string}, lower: {$toLower: string}}}) - .toArray()[0]; + result = t.aggregate({ + $project: {upper: {$toUpper: string}, lower: {$toLower: string}} + }).toArray()[0]; assert.eq(expectedUpper, result.upper); assert.eq(expectedLower, result.lower); } diff --git a/jstests/aggregation/expressions/expression_mod.js b/jstests/aggregation/expressions/expression_mod.js index 923324797ed..63469ca8177 100644 --- a/jstests/aggregation/expressions/expression_mod.js +++ b/jstests/aggregation/expressions/expression_mod.js @@ -17,47 +17,44 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp // The $match portion ensures they are of the correct type as the shell turns the ints back to // doubles at the end so we can not check types with assert. coll.save({}); - var result = - coll.aggregate( - { - $project: { - _id: 0, - dub_dub: {$mod: [138.5, 3.0]}, - dub_int: {$mod: [138.5, NumberLong(3)]}, - dub_long: {$mod: [138.5, NumberInt(3)]}, - int_dub: {$mod: [NumberInt(8), 3.25]}, - int_dubint: {$mod: [NumberInt(8), 3.0]}, - int_int: {$mod: [NumberInt(8), NumberInt(3)]}, - int_long: {$mod: [NumberInt(8), NumberLong(3)]}, - long_dub: {$mod: [NumberLong(8), 3.25]}, - long_dubint: {$mod: [NumberLong(8), 3.0]}, - long_dublong: {$mod: [NumberLong(500000000000), 450000000000.0]}, - long_int: {$mod: [NumberLong(8), NumberInt(3)]}, - long_long: {$mod: [NumberLong(8), NumberLong(3)]}, - verylong_verylong: - {$mod: [NumberLong(800000000000), NumberLong(300000000000)]} - } - }, - { - $match: { - // 1 is NumberDouble - dub_dub: {$type: 1}, - dub_int: {$type: 1}, - dub_long: {$type: 1}, - int_dub: {$type: 1}, - // 16 is NumberInt - int_dubint: {$type: 16}, - int_int: {$type: 16}, - // 18 is NumberLong - int_long: {$type: 18}, - long_dub: {$type: 1}, - long_dubint: {$type: 18}, - long_dublong: {$type: 1}, - long_int: {$type: 18}, - long_long: {$type: 18}, - verylong_verylong: {$type: 18} - } - }); + var result = coll.aggregate({ + $project: { + _id: 0, + dub_dub: {$mod: [138.5, 3.0]}, + dub_int: {$mod: [138.5, NumberLong(3)]}, + dub_long: {$mod: [138.5, NumberInt(3)]}, + int_dub: {$mod: [NumberInt(8), 3.25]}, + int_dubint: {$mod: [NumberInt(8), 3.0]}, + int_int: {$mod: [NumberInt(8), NumberInt(3)]}, + int_long: {$mod: [NumberInt(8), NumberLong(3)]}, + long_dub: {$mod: [NumberLong(8), 3.25]}, + long_dubint: {$mod: [NumberLong(8), 3.0]}, + long_dublong: {$mod: [NumberLong(500000000000), 450000000000.0]}, + long_int: {$mod: [NumberLong(8), NumberInt(3)]}, + long_long: {$mod: [NumberLong(8), NumberLong(3)]}, + verylong_verylong: {$mod: [NumberLong(800000000000), NumberLong(300000000000)]} + } + }, + { + $match: { + // 1 is NumberDouble + dub_dub: {$type: 1}, + dub_int: {$type: 1}, + dub_long: {$type: 1}, + int_dub: {$type: 1}, + // 16 is NumberInt + int_dubint: {$type: 16}, + int_int: {$type: 16}, + // 18 is NumberLong + int_long: {$type: 18}, + long_dub: {$type: 1}, + long_dubint: {$type: 18}, + long_dublong: {$type: 1}, + long_int: {$type: 18}, + long_long: {$type: 18}, + verylong_verylong: {$type: 18} + } + }); // Correct answers (it is mainly the types that are important here). var expectedResult = [{ diff --git a/jstests/aggregation/expressions/in.js b/jstests/aggregation/expressions/in.js index 7839c95d32e..ba09b0f8fac 100644 --- a/jstests/aggregation/expressions/in.js +++ b/jstests/aggregation/expressions/in.js @@ -5,13 +5,11 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode. (function() { "use strict"; - var coll = db.in; + var coll = db.in ; coll.drop(); function testExpression(options) { - var pipeline = { - $project: {included: {$in: ["$elementField", {$literal: options.array}]}} - }; + var pipeline = {$project: {included: {$in: ["$elementField", {$literal: options.array}]}}}; coll.drop(); assert.writeOK(coll.insert({elementField: options.element})); @@ -20,9 +18,7 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode. assert.eq(res[0].included, options.elementIsIncluded); if (options.queryFormShouldBeEquivalent) { - var query = { - elementField: {$in: options.array} - }; + var query = {elementField: {$in: options.array}}; res = coll.find(query).toArray(); if (options.elementIsIncluded) { @@ -33,12 +29,8 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode. } } - testExpression({ - element: 1, - array: [1, 2, 3], - elementIsIncluded: true, - queryFormShouldBeEquivalent: true - }); + testExpression( + {element: 1, array: [1, 2, 3], elementIsIncluded: true, queryFormShouldBeEquivalent: true}); testExpression({ element: "A", @@ -119,38 +111,24 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode. coll.drop(); coll.insert({}); - var pipeline = { - $project: {included: {$in: [[1, 2], 1]}} - }; + var pipeline = {$project: {included: {$in: [[1, 2], 1]}}}; assertErrorCode(coll, pipeline, 40081, "$in requires an array as a second argument"); - pipeline = { - $project: {included: {$in: [1, null]}} - }; + pipeline = {$project: {included: {$in: [1, null]}}}; assertErrorCode(coll, pipeline, 40081, "$in requires an array as a second argument"); - pipeline = { - $project: {included: {$in: [1, "$notAField"]}} - }; + pipeline = {$project: {included: {$in: [1, "$notAField"]}}}; assertErrorCode(coll, pipeline, 40081, "$in requires an array as a second argument"); - pipeline = { - $project: {included: {$in: null}} - }; + pipeline = {$project: {included: {$in: null}}}; assertErrorCode(coll, pipeline, 16020, "$in requires two arguments"); - pipeline = { - $project: {included: {$in: [1]}} - }; + pipeline = {$project: {included: {$in: [1]}}}; assertErrorCode(coll, pipeline, 16020, "$in requires two arguments"); - pipeline = { - $project: {included: {$in: []}} - }; + pipeline = {$project: {included: {$in: []}}}; assertErrorCode(coll, pipeline, 16020, "$in requires two arguments"); - pipeline = { - $project: {included: {$in: [1, 2, 3]}} - }; + pipeline = {$project: {included: {$in: [1, 2, 3]}}}; assertErrorCode(coll, pipeline, 16020, "$in requires two arguments"); }()); diff --git a/jstests/aggregation/expressions/indexof_array.js b/jstests/aggregation/expressions/indexof_array.js index bfc9ef71a15..3fb445e5066 100644 --- a/jstests/aggregation/expressions/indexof_array.js +++ b/jstests/aggregation/expressions/indexof_array.js @@ -46,23 +46,15 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp }; assertErrorCode(coll, pipeline, 40090); - pipeline = { - $project: {output: {$indexOfArray: [[1, 2, 3], 2, "bad"]}} - }; + pipeline = {$project: {output: {$indexOfArray: [[1, 2, 3], 2, "bad"]}}}; assertErrorCode(coll, pipeline, 40096); - pipeline = { - $project: {output: {$indexOfArray: [[1, 2, 3], 2, 0, "bad"]}} - }; + pipeline = {$project: {output: {$indexOfArray: [[1, 2, 3], 2, 0, "bad"]}}}; assertErrorCode(coll, pipeline, 40096); - pipeline = { - $project: {output: {$indexOfArray: [[1, 2, 3], 2, -1]}} - }; + pipeline = {$project: {output: {$indexOfArray: [[1, 2, 3], 2, -1]}}}; assertErrorCode(coll, pipeline, 40097); - pipeline = { - $project: {output: {$indexOfArray: [[1, 2, 3], 2, 1, -1]}} - }; + pipeline = {$project: {output: {$indexOfArray: [[1, 2, 3], 2, 1, -1]}}}; assertErrorCode(coll, pipeline, 40097); }()); diff --git a/jstests/aggregation/expressions/indexof_bytes.js b/jstests/aggregation/expressions/indexof_bytes.js index ac3cefda790..d484ad50948 100644 --- a/jstests/aggregation/expressions/indexof_bytes.js +++ b/jstests/aggregation/expressions/indexof_bytes.js @@ -17,9 +17,7 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp var start = indexOfSpec.length > 2 ? indexOfSpec[2] : 0; // Use $strLenBytes because JavaScript's length property is based off of UTF-16, not the // actual number of bytes. - var end = indexOfSpec.length > 3 ? indexOfSpec[3] : { - $strLenBytes: input - }; + var end = indexOfSpec.length > 3 ? indexOfSpec[3] : {$strLenBytes: input}; var substrExpr = { $indexOfBytes: [{$substrBytes: [input, start, {$subtract: [end, start]}]}, token] @@ -127,23 +125,15 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp }; assertErrorCode(coll, pipeline, 40092); - pipeline = { - $project: {output: {$indexOfBytes: ["abc", "b", "bad"]}} - }; + pipeline = {$project: {output: {$indexOfBytes: ["abc", "b", "bad"]}}}; assertErrorCode(coll, pipeline, 40096); - pipeline = { - $project: {output: {$indexOfBytes: ["abc", "b", 0, "bad"]}} - }; + pipeline = {$project: {output: {$indexOfBytes: ["abc", "b", 0, "bad"]}}}; assertErrorCode(coll, pipeline, 40096); - pipeline = { - $project: {output: {$indexOfBytes: ["abc", "b", -1]}} - }; + pipeline = {$project: {output: {$indexOfBytes: ["abc", "b", -1]}}}; assertErrorCode(coll, pipeline, 40097); - pipeline = { - $project: {output: {$indexOfBytes: ["abc", "b", 1, -1]}} - }; + pipeline = {$project: {output: {$indexOfBytes: ["abc", "b", 1, -1]}}}; assertErrorCode(coll, pipeline, 40097); }()); diff --git a/jstests/aggregation/expressions/indexof_codepoints.js b/jstests/aggregation/expressions/indexof_codepoints.js index 20b9534b050..506b1a13cfa 100644 --- a/jstests/aggregation/expressions/indexof_codepoints.js +++ b/jstests/aggregation/expressions/indexof_codepoints.js @@ -15,9 +15,7 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp var input = indexOfSpec[0]; var token = indexOfSpec[1]; var start = indexOfSpec.length > 2 ? indexOfSpec[2] : 0; - var end = indexOfSpec.length > 3 ? indexOfSpec[3] : { - $strLenCP: input - }; + var end = indexOfSpec.length > 3 ? indexOfSpec[3] : {$strLenCP: input}; var substrExpr = { $indexOfCP: [{$substrCP: [input, start, {$subtract: [end, start]}]}, token] @@ -107,23 +105,15 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp }; assertErrorCode(coll, pipeline, 40094); - pipeline = { - $project: {output: {$indexOfCP: ["abc", "b", "bad"]}} - }; + pipeline = {$project: {output: {$indexOfCP: ["abc", "b", "bad"]}}}; assertErrorCode(coll, pipeline, 40096); - pipeline = { - $project: {output: {$indexOfCP: ["abc", "b", 0, "bad"]}} - }; + pipeline = {$project: {output: {$indexOfCP: ["abc", "b", 0, "bad"]}}}; assertErrorCode(coll, pipeline, 40096); - pipeline = { - $project: {output: {$indexOfCP: ["abc", "b", -1]}} - }; + pipeline = {$project: {output: {$indexOfCP: ["abc", "b", -1]}}}; assertErrorCode(coll, pipeline, 40097); - pipeline = { - $project: {output: {$indexOfCP: ["abc", "b", 1, -1]}} - }; + pipeline = {$project: {output: {$indexOfCP: ["abc", "b", 1, -1]}}}; assertErrorCode(coll, pipeline, 40097); }()); diff --git a/jstests/aggregation/expressions/reduce.js b/jstests/aggregation/expressions/reduce.js index 73bb0cfa16f..54a66fc8b56 100644 --- a/jstests/aggregation/expressions/reduce.js +++ b/jstests/aggregation/expressions/reduce.js @@ -11,15 +11,15 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp coll, { $reduce: - {input: [1, 2, 3], initialValue: {$literal: 0}, in: {$sum: ["$$this", "$$value"]}} + {input: [1, 2, 3], initialValue: {$literal: 0}, in : {$sum: ["$$this", "$$value"]}} }, 6); - testExpression(coll, {$reduce: {input: [], initialValue: {$literal: 0}, in: 10}}, 0); + testExpression(coll, {$reduce: {input: [], initialValue: {$literal: 0}, in : 10}}, 0); testExpression( coll, { $reduce: - {input: [1, 2, 3], initialValue: [], in: {$concatArrays: ["$$value", ["$$this"]]}} + {input: [1, 2, 3], initialValue: [], in : {$concatArrays: ["$$value", ["$$this"]]}} }, [1, 2, 3]); testExpression(coll, @@ -27,7 +27,7 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp $reduce: { input: [1, 2], initialValue: [], - in: {$concatArrays: ["$$value", ["$$value.notAField"]]} + in : {$concatArrays: ["$$value", ["$$value.notAField"]]} } }, [[], []]); @@ -38,14 +38,14 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp $reduce: { input: [[1, 2, 3], [4, 5]], initialValue: 1, - in: { + in : { $multiply: [ "$$value", { $reduce: { input: "$$this", initialValue: 0, - in: {$sum: ["$$value", "$$this"]} + in : {$sum: ["$$value", "$$this"]} } } ] @@ -56,43 +56,43 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp // A nested $reduce using a $let to allow the inner $reduce to access the variables of the // outer. - testExpression( - coll, - { - $reduce: { - input: [[0, 1], [2, 3]], - initialValue: {allElements: [], sumOfInner: {$literal: 0}}, - in: { - $let: { - vars: {outerValue: "$$value", innerArray: "$$this"}, - in: { - $reduce: { - input: "$$innerArray", - initialValue: "$$outerValue", - in: { - allElements: - {$concatArrays: ["$$value.allElements", ["$$this"]]}, - sumOfInner: {$sum: ["$$value.sumOfInner", "$$this"]} - } - } - } - } - } - } - }, - {allElements: [0, 1, 2, 3], sumOfInner: 6}); + testExpression(coll, + { + $reduce: { + input: [[0, 1], [2, 3]], + initialValue: {allElements: [], sumOfInner: {$literal: 0}}, + in : { + $let: { + vars: {outerValue: "$$value", innerArray: "$$this"}, + in : { + $reduce: { + input: "$$innerArray", + initialValue: "$$outerValue", + in : { + allElements: { + $concatArrays: + ["$$value.allElements", ["$$this"]] + }, + sumOfInner: + {$sum: ["$$value.sumOfInner", "$$this"]} + } + } + } + } + } + } + }, + {allElements: [0, 1, 2, 3], sumOfInner: 6}); // Nullish input produces null as an output. - testExpression(coll, {$reduce: {input: null, initialValue: {$literal: 0}, in: 5}}, null); + testExpression(coll, {$reduce: {input: null, initialValue: {$literal: 0}, in : 5}}, null); testExpression( - coll, {$reduce: {input: "$nonexistent", initialValue: {$literal: 0}, in: 5}}, null); + coll, {$reduce: {input: "$nonexistent", initialValue: {$literal: 0}, in : 5}}, null); // Error cases for $reduce. // $reduce requires an object. - var pipeline = { - $project: {reduced: {$reduce: 0}} - }; + var pipeline = {$project: {reduced: {$reduce: 0}}}; assertErrorCode(coll, pipeline, 40075); // Unknown field specified. @@ -102,7 +102,7 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp $reduce: { input: {$literal: 0}, initialValue: {$literal: 0}, - in: {$literal: 0}, + in : {$literal: 0}, notAField: {$literal: 0} } } @@ -111,15 +111,11 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp assertErrorCode(coll, pipeline, 40076); // $reduce requires input to be specified. - pipeline = { - $project: {reduced: {$reduce: {initialValue: {$literal: 0}, in: {$literal: 0}}}} - }; + pipeline = {$project: {reduced: {$reduce: {initialValue: {$literal: 0}, in : {$literal: 0}}}}}; assertErrorCode(coll, pipeline, 40077); // $reduce requires initialValue to be specified. - pipeline = { - $project: {reduced: {$reduce: {input: {$literal: 0}, in: {$literal: 0}}}} - }; + pipeline = {$project: {reduced: {$reduce: {input: {$literal: 0}, in : {$literal: 0}}}}}; assertErrorCode(coll, pipeline, 40078); // $reduce requires in to be specified. @@ -129,14 +125,10 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp assertErrorCode(coll, pipeline, 40079); // $$value is undefined in the non-'in' arguments of $reduce. - pipeline = { - $project: {reduced: {$reduce: {input: "$$value", initialValue: [], in: []}}} - }; + pipeline = {$project: {reduced: {$reduce: {input: "$$value", initialValue: [], in : []}}}}; assertErrorCode(coll, pipeline, 17276); // $$this is undefined in the non-'in' arguments of $reduce. - pipeline = { - $project: {reduced: {$reduce: {input: "$$this", initialValue: [], in: []}}} - }; + pipeline = {$project: {reduced: {$reduce: {input: "$$this", initialValue: [], in : []}}}}; assertErrorCode(coll, pipeline, 17276); }()); diff --git a/jstests/aggregation/expressions/split.js b/jstests/aggregation/expressions/split.js index bfed38314b4..7d3402bde4e 100644 --- a/jstests/aggregation/expressions/split.js +++ b/jstests/aggregation/expressions/split.js @@ -38,35 +38,23 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode and testExp testExpression(coll, {$split: ["a", "$a"]}, null); // Ensure that $split errors when given more or less than two arguments. - var pipeline = { - $project: {split: {$split: []}} - }; + var pipeline = {$project: {split: {$split: []}}}; assertErrorCode(coll, pipeline, 16020); - pipeline = { - $project: {split: {$split: ["a"]}} - }; + pipeline = {$project: {split: {$split: ["a"]}}}; assertErrorCode(coll, pipeline, 16020); - pipeline = { - $project: {split: {$split: ["a", "b", "c"]}} - }; + pipeline = {$project: {split: {$split: ["a", "b", "c"]}}}; assertErrorCode(coll, pipeline, 16020); // Ensure that $split errors when given non-string input. - pipeline = { - $project: {split: {$split: [1, "abc"]}} - }; + pipeline = {$project: {split: {$split: [1, "abc"]}}}; assertErrorCode(coll, pipeline, 40085); - pipeline = { - $project: {split: {$split: ["abc", 1]}} - }; + pipeline = {$project: {split: {$split: ["abc", 1]}}}; assertErrorCode(coll, pipeline, 40086); // Ensure that $split errors when given an empty separator. - pipeline = { - $project: {split: {$split: ["abc", ""]}} - }; + pipeline = {$project: {split: {$split: ["abc", ""]}}}; assertErrorCode(coll, pipeline, 40087); }()); diff --git a/jstests/aggregation/expressions/switch.js b/jstests/aggregation/expressions/switch.js index 9a6dbbb529d..64cd9e1db2f 100644 --- a/jstests/aggregation/expressions/switch.js +++ b/jstests/aggregation/expressions/switch.js @@ -99,8 +99,7 @@ pipeline = { "$project": { "_id": 0, - "output": - {"$switch": {"branches": [{"case": true, "then": null}], "default": false}} + "output": {"$switch": {"branches": [{"case": true, "then": null}], "default": false}} } }; res = coll.aggregate(pipeline).toArray(); @@ -125,8 +124,7 @@ pipeline = { "$project": { "_id": 0, - "output": - {"$switch": {"branches": [{"case": null, "then": false}], "default": null}} + "output": {"$switch": {"branches": [{"case": null, "then": false}], "default": null}} } }; res = coll.aggregate(pipeline).toArray(); diff --git a/jstests/aggregation/expressions/switch_errors.js b/jstests/aggregation/expressions/switch_errors.js index cf6dc0f4f93..0d9023fb250 100644 --- a/jstests/aggregation/expressions/switch_errors.js +++ b/jstests/aggregation/expressions/switch_errors.js @@ -8,24 +8,16 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode. var coll = db.switch; coll.drop(); - var pipeline = { - "$project": {"output": {"$switch": "not an object"}} - }; + var pipeline = {"$project": {"output": {"$switch": "not an object"}}}; assertErrorCode(coll, pipeline, 40060, "$switch requires an object as an argument."); - pipeline = { - "$project": {"output": {"$switch": {"branches": "not an array"}}} - }; + pipeline = {"$project": {"output": {"$switch": {"branches": "not an array"}}}}; assertErrorCode(coll, pipeline, 40061, "$switch requires 'branches' to be an array."); - pipeline = { - "$project": {"output": {"$switch": {"branches": ["not an object"]}}} - }; + pipeline = {"$project": {"output": {"$switch": {"branches": ["not an object"]}}}}; assertErrorCode(coll, pipeline, 40062, "$switch requires each branch to be an object."); - pipeline = { - "$project": {"output": {"$switch": {"branches": [{}]}}} - }; + pipeline = {"$project": {"output": {"$switch": {"branches": [{}]}}}}; assertErrorCode(coll, pipeline, 40064, "$switch requires each branch have a 'case'."); pipeline = { @@ -47,19 +39,13 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode. }; assertErrorCode(coll, pipeline, 40063, "$switch found a branch with an unknown argument"); - pipeline = { - "$project": {"output": {"$switch": {"notAnArgument": 1}}} - }; + pipeline = {"$project": {"output": {"$switch": {"notAnArgument": 1}}}}; assertErrorCode(coll, pipeline, 40067, "$switch found an unknown argument"); - pipeline = { - "$project": {"output": {"$switch": {"branches": []}}} - }; + pipeline = {"$project": {"output": {"$switch": {"branches": []}}}}; assertErrorCode(coll, pipeline, 40068, "$switch requires at least one branch"); - pipeline = { - "$project": {"output": {"$switch": {}}} - }; + pipeline = {"$project": {"output": {"$switch": {}}}}; assertErrorCode(coll, pipeline, 40068, "$switch requires at least one branch"); coll.insert({x: 1}); diff --git a/jstests/aggregation/extras/mrabench.js b/jstests/aggregation/extras/mrabench.js index fe731ecd28b..78be64a2064 100644 --- a/jstests/aggregation/extras/mrabench.js +++ b/jstests/aggregation/extras/mrabench.js @@ -11,10 +11,7 @@ function rollupMap() { } function rollupReduce(key, values) { - var res = { - total: 0, - unique: 0 - }; + var res = {total: 0, unique: 0}; for (var i = 0; i < values.length; i++) { res.total += values[i].total; res.unique += values[i].unique; @@ -41,15 +38,13 @@ function rollupWeeklyMR() { function rollupMonthlyA() { resMonthlyA = db.runCommand({ aggregate: "gen.monthly.ip", - pipeline: - [{$group: {_id: {month: "_id.t"}, total: {$sum: "$value"}, unique: {$sum: 1}}}] + pipeline: [{$group: {_id: {month: "_id.t"}, total: {$sum: "$value"}, unique: {$sum: 1}}}] }); } function rollupWeeklyA() { resWeeklyA = db.runCommand({ aggregate: "gen.weekly.ip", - pipeline: - [{$group: {_id: {month: "_id.t"}, total: {$sum: "$value"}, unique: {$sum: 1}}}] + pipeline: [{$group: {_id: {month: "_id.t"}, total: {$sum: "$value"}, unique: {$sum: 1}}}] }); } diff --git a/jstests/aggregation/extras/testutils.js b/jstests/aggregation/extras/testutils.js index bb753921906..bd05ea835f0 100644 --- a/jstests/aggregation/extras/testutils.js +++ b/jstests/aggregation/extras/testutils.js @@ -39,7 +39,13 @@ assert(!resultsEq(t1result, t1resultf2, verbose), 't2a failed'); assert(!resultsEq(t1resultf2, t1result, verbose), 't2b failed'); var t1resultf3 = [ - {"_id": ObjectId("4dc07fedd8420ab8d0d4066d"), "pageViews": 5, "tags": ["fun", ]}, + { + "_id": ObjectId("4dc07fedd8420ab8d0d4066d"), + "pageViews": 5, + "tags": [ + "fun", + ] + }, {"_id": ObjectId("4dc07fedd8420ab8d0d4066e"), "pageViews": 7, "tags": ["fun", "nasty"]}, {"_id": ObjectId("4dc07fedd8420ab8d0d4066f"), "pageViews": 6, "tags": ["filthy"]} ]; diff --git a/jstests/aggregation/extras/utils.js b/jstests/aggregation/extras/utils.js index 33cfe9b2b2b..7fca7aa0ca3 100644 --- a/jstests/aggregation/extras/utils.js +++ b/jstests/aggregation/extras/utils.js @@ -259,13 +259,9 @@ function assertErrorCode(coll, pipe, code, errmsg) { assert.eq(res.code, code); // Test with cursors - var cmd = { - pipeline: pipe - }; + var cmd = {pipeline: pipe}; // cmd.cursor = {}; - cmd.cursor = { - batchSize: 0 - }; + cmd.cursor = {batchSize: 0}; var cursorRes = coll.runCommand("aggregate", cmd); if (cursorRes.ok) { diff --git a/jstests/aggregation/mongos_slaveok.js b/jstests/aggregation/mongos_slaveok.js index 91a0533d59e..9ccf383335e 100644 --- a/jstests/aggregation/mongos_slaveok.js +++ b/jstests/aggregation/mongos_slaveok.js @@ -26,10 +26,7 @@ var res = testDB.runCommand({aggregate: 'user', pipeline: [{$project: {x: 1}}]}); assert(res.ok, 'aggregate command failed: ' + tojson(res)); - var profileQuery = { - op: 'command', - ns: 'test.user', 'command.aggregate': 'user' - }; + var profileQuery = {op: 'command', ns: 'test.user', 'command.aggregate': 'user'}; var profileDoc = secNode.getDB('test').system.profile.findOne(profileQuery); assert(profileDoc != null); diff --git a/jstests/aggregation/sources/graphLookup/airports.js b/jstests/aggregation/sources/graphLookup/airports.js index 7cf0142c631..71a38e268b8 100644 --- a/jstests/aggregation/sources/graphLookup/airports.js +++ b/jstests/aggregation/sources/graphLookup/airports.js @@ -30,45 +30,39 @@ local.insert({}); // Perform a simple $graphLookup and ensure it retrieves every result. - var res = local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: "PWM", - connectFromField: "connects", - connectToField: "_id", - as: "connections" - } - }).toArray()[0]; - - // "foreign" represents a connected graph. - assert.eq(res.connections.length, airports.length); - - // Perform a $graphLookup and ensure it correctly computes the shortest path to a node when more - // than one path exists. - res = local.aggregate( - { + var res = local + .aggregate({ $graphLookup: { from: "foreign", - startWith: "BOS", + startWith: "PWM", connectFromField: "connects", connectToField: "_id", - depthField: "hops", as: "connections" } - }, - {$unwind: "$connections"}, - {$project: {_id: "$connections._id", hops: "$connections.hops"}}).toArray(); + }) + .toArray()[0]; + + // "foreign" represents a connected graph. + assert.eq(res.connections.length, airports.length); + + // Perform a $graphLookup and ensure it correctly computes the shortest path to a node when more + // than one path exists. + res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: "BOS", + connectFromField: "connects", + connectToField: "_id", + depthField: "hops", + as: "connections" + } + }, + {$unwind: "$connections"}, + {$project: {_id: "$connections._id", hops: "$connections.hops"}}) + .toArray(); - var expectedDistances = { - BOS: 0, - PWM: 1, - JFK: 1, - LGA: 1, - ORD: 2, - SFO: 2, - MIA: 3, - ATL: 4 - }; + var expectedDistances = {BOS: 0, PWM: 1, JFK: 1, LGA: 1, ORD: 2, SFO: 2, MIA: 3, ATL: 4}; assert.eq(res.length, airports.length); res.forEach(function(c) { @@ -78,15 +72,17 @@ // Disconnect the graph, and ensure we don't find the other side. foreign.remove({_id: "JFK"}); - res = db.local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: "ATL", - connectFromField: "connects", - connectToField: "_id", - as: "connections" - } - }).toArray()[0]; + res = db.local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: "ATL", + connectFromField: "connects", + connectToField: "_id", + as: "connections" + } + }) + .toArray()[0]; // ATL should now connect to itself, MIA, and SFO. assert.eq(res.connections.length, 3); diff --git a/jstests/aggregation/sources/graphLookup/basic.js b/jstests/aggregation/sources/graphLookup/basic.js index 8ee26a64f9f..15c8ef85e22 100644 --- a/jstests/aggregation/sources/graphLookup/basic.js +++ b/jstests/aggregation/sources/graphLookup/basic.js @@ -19,59 +19,67 @@ assert.writeOK(local.insert({starting: 50})); // Perform a simple $graphLookup and ensure it retrieves every result. - var res = local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: "$starting", - connectFromField: "neighbors", - connectToField: "_id", - as: "integers" - } - }).toArray()[0]; + var res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: "$starting", + connectFromField: "neighbors", + connectToField: "_id", + as: "integers" + } + }) + .toArray()[0]; assert.eq(res.integers.length, 100); // Perform a $graphLookup and ensure it respects "maxDepth". - res = local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: "$starting", - connectFromField: "neighbors", - connectToField: "_id", - maxDepth: 5, - as: "integers" - } - }).toArray()[0]; + res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: "$starting", + connectFromField: "neighbors", + connectToField: "_id", + maxDepth: 5, + as: "integers" + } + }) + .toArray()[0]; // At depth zero, we retrieve one integer, and two for every depth thereafter. assert.eq(res.integers.length, 11); // Perform a $graphLookup and ensure it properly evaluates "startWith". - res = local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: {$add: ["$starting", 3]}, - connectFromField: "neighbors", - connectToField: "_id", - maxDepth: 0, - as: "integers" - } - }).toArray()[0]; + res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: {$add: ["$starting", 3]}, + connectFromField: "neighbors", + connectToField: "_id", + maxDepth: 0, + as: "integers" + } + }) + .toArray()[0]; assert.eq(res.integers.length, 1); assert.eq(res.integers[0]._id, 53); // Perform a $graphLookup and ensure it properly expands "startWith". - res = local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: {$literal: [1, 2, 3]}, - connectFromField: "neighbors", - connectToField: "_id", - maxDepth: 0, - as: "integers" - } - }).toArray()[0]; + res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: {$literal: [1, 2, 3]}, + connectFromField: "neighbors", + connectToField: "_id", + maxDepth: 0, + as: "integers" + } + }) + .toArray()[0]; assert.eq(res.integers.length, 3); @@ -83,15 +91,17 @@ assert.writeOK(foreign.insert({_id: 51})); assert.writeOK(foreign.insert({_id: null, neighbors: [50, 52]})); - res = local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: "$starting", - connectFromField: "neighbors", - connectToField: "_id", - as: "integers" - } - }).toArray()[0]; + res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: "$starting", + connectFromField: "neighbors", + connectToField: "_id", + as: "integers" + } + }) + .toArray()[0]; // Our result should be missing the values with _id from 52 to 99. assert.eq(res.integers.length, 52); @@ -103,29 +113,33 @@ assert.writeOK(foreign.update({_id: 99}, {$set: {neighbors: [98, 0]}})); assert.writeOK(foreign.update({_id: 0}, {$set: {neighbors: [99, 1]}})); - res = local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: "$starting", - connectFromField: "neighbors", - connectToField: "_id", - as: "integers" - } - }).toArray()[0]; + res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: "$starting", + connectFromField: "neighbors", + connectToField: "_id", + as: "integers" + } + }) + .toArray()[0]; assert.eq(res.integers.length, 100); // Perform a $graphLookup and ensure that "depthField" is properly populated. - res = local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: "$starting", - connectFromField: "neighbors", - connectToField: "_id", - depthField: "distance", - as: "integers" - } - }).toArray()[0]; + res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: "$starting", + connectFromField: "neighbors", + connectToField: "_id", + depthField: "distance", + as: "integers" + } + }) + .toArray()[0]; assert.eq(res.integers.length, 100); diff --git a/jstests/aggregation/sources/graphLookup/error.js b/jstests/aggregation/sources/graphLookup/error.js index 70e9d2a8079..721bce5eb3e 100644 --- a/jstests/aggregation/sources/graphLookup/error.js +++ b/jstests/aggregation/sources/graphLookup/error.js @@ -165,8 +165,7 @@ load("jstests/aggregation/extras/utils.js"); // For "assertErrorCode". assertErrorCode(local, pipeline, 40105, "connectToField was not specified"); pipeline = { - $graphLookup: - {from: "foreign", startWith: {$const: 0}, connectToField: "a", as: "output"} + $graphLookup: {from: "foreign", startWith: {$const: 0}, connectToField: "a", as: "output"} }; assertErrorCode(local, pipeline, 40105, "connectFromField was not specified"); @@ -211,9 +210,7 @@ load("jstests/aggregation/extras/utils.js"); // For "assertErrorCode". var initial = []; for (var i = 0; i < 8; i++) { - var obj = { - _id: i - }; + var obj = {_id: i}; obj['longString'] = new Array(14 * 1024 * 1024).join('x'); initial.push(i); @@ -238,10 +235,7 @@ load("jstests/aggregation/extras/utils.js"); // For "assertErrorCode". var bulk = foreign.initializeUnorderedBulkOp(); for (var i = 0; i < 14; i++) { - var obj = { - from: 0, - to: 1 - }; + var obj = {from: 0, to: 1}; obj['s'] = new Array(7 * 1024 * 1024).join(' '); bulk.insert(obj); } @@ -264,26 +258,24 @@ load("jstests/aggregation/extras/utils.js"); // For "assertErrorCode". var bulk = foreign.initializeUnorderedBulkOp(); for (var i = 0; i < 13; i++) { - var obj = { - from: 0, - to: 1 - }; + var obj = {from: 0, to: 1}; obj['s'] = new Array(7 * 1024 * 1024).join(' '); bulk.insert(obj); } assert.writeOK(bulk.execute()); - var res = local.aggregate( - { - $graphLookup: { - from: "foreign", - startWith: {$literal: 0}, - connectToField: "from", - connectFromField: "to", - as: "out" - } - }, - {$unwind: {path: "$out"}}).toArray(); + var res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: {$literal: 0}, + connectToField: "from", + connectFromField: "to", + as: "out" + } + }, + {$unwind: {path: "$out"}}) + .toArray(); assert.eq(res.length, 13); }()); diff --git a/jstests/aggregation/sources/graphLookup/nested_objects.js b/jstests/aggregation/sources/graphLookup/nested_objects.js index e95d99f293f..b2e3f5ac59a 100644 --- a/jstests/aggregation/sources/graphLookup/nested_objects.js +++ b/jstests/aggregation/sources/graphLookup/nested_objects.js @@ -19,15 +19,17 @@ assert.writeOK(local.insert({starting: 0})); - var res = local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: "$starting", - connectFromField: "neighbors.id", - connectToField: "_id", - as: "integers" - } - }).toArray()[0]; + var res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: "$starting", + connectFromField: "neighbors.id", + connectToField: "_id", + as: "integers" + } + }) + .toArray()[0]; assert.eq(res.integers.length, 100); foreign.drop(); @@ -39,15 +41,17 @@ } assert.writeOK(bulk.execute()); - var res = local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: "$starting", - connectFromField: "value", - connectToField: "previous.neighbor", - as: "integers" - } - }).toArray()[0]; + var res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: "$starting", + connectFromField: "value", + connectToField: "previous.neighbor", + as: "integers" + } + }) + .toArray()[0]; assert.eq(res.integers.length, 100); foreign.drop(); @@ -62,14 +66,16 @@ } assert.writeOK(bulk.execute()); - var res = local.aggregate({ - $graphLookup: { - from: "foreign", - startWith: "$starting", - connectFromField: "values.neighbor", - connectToField: "previous.neighbor", - as: "integers" - } - }).toArray()[0]; + var res = local + .aggregate({ + $graphLookup: { + from: "foreign", + startWith: "$starting", + connectFromField: "values.neighbor", + connectToField: "previous.neighbor", + as: "integers" + } + }) + .toArray()[0]; assert.eq(res.integers.length, 100); }()); diff --git a/jstests/aggregation/sources/graphLookup/sharded.js b/jstests/aggregation/sources/graphLookup/sharded.js index 26fbbc2e9f0..d54e2be01c8 100644 --- a/jstests/aggregation/sources/graphLookup/sharded.js +++ b/jstests/aggregation/sources/graphLookup/sharded.js @@ -24,7 +24,8 @@ load("jstests/aggregation/extras/utils.js"); // For assertErrorCode. assert.writeOK(local.insert({})); var res = st.s.getDB("graphLookup") - .local.aggregate({ + .local + .aggregate({ $graphLookup: { from: "foreign", startWith: {$literal: 0}, diff --git a/jstests/aggregation/sources/graphLookup/socialite.js b/jstests/aggregation/sources/graphLookup/socialite.js index 21027f21b0b..6efe2672540 100644 --- a/jstests/aggregation/sources/graphLookup/socialite.js +++ b/jstests/aggregation/sources/graphLookup/socialite.js @@ -30,18 +30,20 @@ // Find the social network of "Darren", that is, people Darren follows, and people who are // followed by someone Darren follows, etc. - var res = users.aggregate({$match: {fullname: "Darren"}}, - { - $graphLookup: { - from: "followers", - startWith: "$_id", - connectFromField: "_t", - connectToField: "_f", - as: "network" - } - }, - {$unwind: "$network"}, - {$project: {_id: "$network._t"}}).toArray(); + var res = users + .aggregate({$match: {fullname: "Darren"}}, + { + $graphLookup: { + from: "followers", + startWith: "$_id", + connectFromField: "_t", + connectToField: "_f", + as: "network" + } + }, + {$unwind: "$network"}, + {$project: {_id: "$network._t"}}) + .toArray(); // "djw" is followed, directly or indirectly, by "jsr" and "bmw". assert.eq(res.length, 2); diff --git a/jstests/aggregation/testSlave.js b/jstests/aggregation/testSlave.js index 21a798a1ad2..0a03d68a49b 100644 --- a/jstests/aggregation/testSlave.js +++ b/jstests/aggregation/testSlave.js @@ -7,9 +7,7 @@ replTest.awaitReplication(); var primary = replTest.getPrimary().getDB('test'); var secondary = replTest.getSecondary().getDB('test'); -var options = { - writeConcern: {w: 2} -}; +var options = {writeConcern: {w: 2}}; primary.agg.insert({}, options); primary.agg.insert({}, options); primary.agg.insert({}, options); diff --git a/jstests/aggregation/testall.js b/jstests/aggregation/testall.js index 5771cbefaef..c58d3e1e023 100644 --- a/jstests/aggregation/testall.js +++ b/jstests/aggregation/testall.js @@ -370,7 +370,10 @@ db.p11.save({ var p11 = db.runCommand({ aggregate: "p11", - pipeline: [{$unwind: "$items.authors"}, {$project: {name: 1, author: "$items.authors"}}, ] + pipeline: [ + {$unwind: "$items.authors"}, + {$project: {name: 1, author: "$items.authors"}}, + ] }); p11result = [ @@ -418,8 +421,14 @@ assert.docEq(p13.result, p13result, 'p13 failed'); var p14 = db.runCommand({ aggregate: "article", pipeline: [{ - $project: - {theRemainder: {$mod: [{$ifNull: ["$other.foo", "$other.bar"]}, "$pageViews", ]}} + $project: { + theRemainder: { + $mod: [ + {$ifNull: ["$other.foo", "$other.bar"]}, + "$pageViews", + ] + } + } }] }); @@ -788,9 +797,21 @@ g5.result.forEach(function(obj) { var g5result = [ {"_id": {"tags": "filthy"}, "authors": ["jane"]}, - {"_id": {"tags": "fun"}, "authors": ["bob", "dave", ]}, + { + "_id": {"tags": "fun"}, + "authors": [ + "bob", + "dave", + ] + }, {"_id": {"tags": "good"}, "authors": ["bob"]}, - {"_id": {"tags": "nasty"}, "authors": ["dave", "jane", ]} + { + "_id": {"tags": "nasty"}, + "authors": [ + "dave", + "jane", + ] + } ]; assert.docEq(g5.result, g5result, 'g5 failed'); diff --git a/jstests/aggregation/testshard1.js b/jstests/aggregation/testshard1.js index 0d773351f1d..516325cbe5c 100644 --- a/jstests/aggregation/testshard1.js +++ b/jstests/aggregation/testshard1.js @@ -46,26 +46,9 @@ being added as arrays within arrays. var count = 0; var strings = [ - "one", - "two", - "three", - "four", - "five", - "six", - "seven", - "eight", - "nine", - "ten", - "eleven", - "twelve", - "thirteen", - "fourteen", - "fifteen", - "sixteen", - "seventeen", - "eighteen", - "nineteen", - "twenty" + "one", "two", "three", "four", "five", "six", "seven", + "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", + "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty" ]; jsTestLog("Bulk inserting data"); @@ -94,13 +77,11 @@ for (var i = 0; i < shards.length; i++) { } jsTestLog('a project and group in shards, result combined in mongos'); -var a1 = aggregateNoOrder( - db.ts1, - [ - {$project: {cMod10: {$mod: ["$counter", 10]}, number: 1, counter: 1}}, - {$group: {_id: "$cMod10", numberSet: {$addToSet: "$number"}, avgCounter: {$avg: "$cMod10"}}}, - {$sort: {_id: 1}} - ]); +var a1 = aggregateNoOrder(db.ts1, [ + {$project: {cMod10: {$mod: ["$counter", 10]}, number: 1, counter: 1}}, + {$group: {_id: "$cMod10", numberSet: {$addToSet: "$number"}, avgCounter: {$avg: "$cMod10"}}}, + {$sort: {_id: 1}} +]); for (i = 0; i < 10; ++i) { assert.eq(a1[i].avgCounter, a1[i]._id, 'agg sharded test avgCounter failed'); @@ -115,7 +96,7 @@ assert.eq(a2[0].total, (nItems / 2) * (1 + nItems), 'agg sharded test counter su jsTestLog('A group combining all documents into one, averaging a null field.'); assert.eq(aggregateOrdered(db.ts1, [{$group: {_id: null, avg: {$avg: "$missing"}}}]), - [{_id: null, avg: null}]); + [{_id: null, avg: null}]); jsTestLog('an initial group starts the group in the shards, and combines them in mongos'); var a3 = @@ -126,19 +107,18 @@ for (i = 0; i < strings.length; ++i) { } jsTestLog('a match takes place in the shards; just returning the results from mongos'); -var a4 = aggregateNoOrder(db.ts1, - [{ - $match: { - $or: [ - {counter: 55}, - {counter: 1111}, - {counter: 2222}, - {counter: 33333}, - {counter: 99999}, - {counter: 55555} - ] - } - }]); +var a4 = aggregateNoOrder(db.ts1, [{ + $match: { + $or: [ + {counter: 55}, + {counter: 1111}, + {counter: 2222}, + {counter: 33333}, + {counter: 99999}, + {counter: 55555} + ] + } + }]); assert.eq(a4.length, 6, tojson(a4)); for (i = 0; i < 6; ++i) { @@ -192,13 +172,15 @@ function testAvgStdDev() { jsTestLog('testing $avg and $stdDevPop in sharded $group'); // Note: not using aggregateOrdered since it requires exact results. $stdDevPop can vary // slightly between runs if a migration occurs. This is why we use assert.close below. - var res = db.ts1.aggregate([{ - $group: { - _id: null, - avg: {$avg: '$counter'}, - stdDevPop: {$stdDevPop: '$counter'}, - } - }]).toArray(); + var res = db.ts1 + .aggregate([{ + $group: { + _id: null, + avg: {$avg: '$counter'}, + stdDevPop: {$stdDevPop: '$counter'}, + } + }]) + .toArray(); // http://en.wikipedia.org/wiki/Arithmetic_progression#Sum var avg = (1 + nItems) / 2; assert.close(res[0].avg, avg, '', 10 /*decimal places*/); @@ -233,10 +215,7 @@ db.literal.save({dollar: false}); result = aggregateOrdered( db.literal, - [{ - $project: - {_id: 0, cost: {$cond: ['$dollar', {$literal: '$1.00'}, {$literal: '$.99'}]}} - }]); + [{$project: {_id: 0, cost: {$cond: ['$dollar', {$literal: '$1.00'}, {$literal: '$.99'}]}}}]); assert.eq([{cost: '$.99'}], result); diff --git a/jstests/aggregation/unwind.js b/jstests/aggregation/unwind.js index ba6ffa44a86..ffd2a3da9c6 100644 --- a/jstests/aggregation/unwind.js +++ b/jstests/aggregation/unwind.js @@ -12,7 +12,6 @@ t.insert({_id: 6, x: 4}); var res = t.aggregate([{$unwind: "$x"}, {$sort: {_id: 1}}]).toArray(); assert.eq(4, res.length); -assert.eq([1, 2, 3, 4], - res.map(function(z) { - return z.x; - })); +assert.eq([1, 2, 3, 4], res.map(function(z) { + return z.x; +})); diff --git a/jstests/auth/access_control_with_unreachable_configs.js b/jstests/auth/access_control_with_unreachable_configs.js index 6c833d5c844..7e173475f7a 100644 --- a/jstests/auth/access_control_with_unreachable_configs.js +++ b/jstests/auth/access_control_with_unreachable_configs.js @@ -3,10 +3,7 @@ // are user documents stored in the configuration information, it must assume that // there are. -var dopts = { - smallfiles: "", - nopreallocj: "" -}; +var dopts = {smallfiles: "", nopreallocj: ""}; var st = new ShardingTest({ shards: 1, mongos: 1, diff --git a/jstests/auth/arbiter.js b/jstests/auth/arbiter.js index 75b7b67a9ad..df9f85a8015 100644 --- a/jstests/auth/arbiter.js +++ b/jstests/auth/arbiter.js @@ -19,16 +19,9 @@ replTest.initiate({ var primaryAdmin = replTest.nodes[0].getDB("admin"); var arbiterAdmin = replTest.nodes[2].getDB("admin"); -var cmd0 = { - getCmdLineOpts: 1 -}; -var cmd1 = { - getParameter: 1, - logLevel: 1 -}; -var cmd2 = { - serverStatus: 1 -}; +var cmd0 = {getCmdLineOpts: 1}; +var cmd1 = {getParameter: 1, logLevel: 1}; +var cmd2 = {serverStatus: 1}; assert.commandFailedWithCode(primaryAdmin.runCommand(cmd0), 13); assert.commandFailedWithCode(primaryAdmin.runCommand(cmd1), 13); diff --git a/jstests/auth/auth_options.js b/jstests/auth/auth_options.js index d2f89d12a0f..aa8bd7ee9eb 100644 --- a/jstests/auth/auth_options.js +++ b/jstests/auth/auth_options.js @@ -3,9 +3,7 @@ var baseName = "jstests_auth_auth_options"; load('jstests/libs/command_line/test_parsed_options.js'); jsTest.log("Testing \"auth\" command line option"); -var expectedResult = { - "parsed": {"security": {"authorization": "enabled"}} -}; +var expectedResult = {"parsed": {"security": {"authorization": "enabled"}}}; testGetCmdLineOptsMongod({auth: ""}, expectedResult); diff --git a/jstests/auth/auth_schema_upgrade.js b/jstests/auth/auth_schema_upgrade.js index d80fbe6bbad..b63eea34788 100644 --- a/jstests/auth/auth_schema_upgrade.js +++ b/jstests/auth/auth_schema_upgrade.js @@ -69,10 +69,7 @@ testAuthSchemaUpgrade(conn); MongoRunner.stopMongod(conn); jsTest.log('Test authSchemUpgrade sharded'); -var dopts = { - smallfiles: "", - nopreallocj: "" -}; +var dopts = {smallfiles: "", nopreallocj: ""}; var st = new ShardingTest({ shards: 1, mongos: 1, diff --git a/jstests/auth/authz_modifications_access_control.js b/jstests/auth/authz_modifications_access_control.js index bb294796a7f..7f7b01e12ba 100644 --- a/jstests/auth/authz_modifications_access_control.js +++ b/jstests/auth/authz_modifications_access_control.js @@ -5,8 +5,8 @@ function runTest(conn) { var authzErrorCode = 13; - conn.getDB('admin') - .createUser({user: 'userAdmin', pwd: 'pwd', roles: ['userAdminAnyDatabase']}); + conn.getDB('admin').createUser( + {user: 'userAdmin', pwd: 'pwd', roles: ['userAdminAnyDatabase']}); var userAdminConn = new Mongo(conn.host); userAdminConn.getDB('admin').auth('userAdmin', 'pwd'); @@ -62,11 +62,7 @@ function runTest(conn) { (function() { jsTestLog("Testing role creation, of user-defined roles with same name as built-in roles"); - var cmdObj = { - createRole: "readWrite", - roles: [], - privileges: [] - }; + var cmdObj = {createRole: "readWrite", roles: [], privileges: []}; var res = adminUserAdmin.runCommand(cmdObj); assert.commandFailed(res, tojson(cmdObj)); diff --git a/jstests/auth/basic_role_auth.js b/jstests/auth/basic_role_auth.js index f44a331fa95..7188aa7e4f6 100644 --- a/jstests/auth/basic_role_auth.js +++ b/jstests/auth/basic_role_auth.js @@ -36,36 +36,12 @@ var AUTH_INFO = { }; // Constants that lists the privileges of a given role. -var READ_PERM = { - query: 1, - index_r: 1, - killCursor: 1 -}; -var READ_WRITE_PERM = { - insert: 1, - update: 1, - remove: 1, - query: 1, - index_r: 1, - index_w: 1, - killCursor: 1 -}; -var ADMIN_PERM = { - index_r: 1, - index_w: 1, - profile_r: 1 -}; -var UADMIN_PERM = { - user_r: 1, - user_w: 1 -}; -var CLUSTER_PERM = { - killOp: 1, - currentOp: 1, - fsync_unlock: 1, - killCursor: 1, - profile_r: 1 -}; +var READ_PERM = {query: 1, index_r: 1, killCursor: 1}; +var READ_WRITE_PERM = + {insert: 1, update: 1, remove: 1, query: 1, index_r: 1, index_w: 1, killCursor: 1}; +var ADMIN_PERM = {index_r: 1, index_w: 1, profile_r: 1}; +var UADMIN_PERM = {user_r: 1, user_w: 1}; +var CLUSTER_PERM = {killOp: 1, currentOp: 1, fsync_unlock: 1, killCursor: 1, profile_r: 1}; /** * Checks whether an error occurs after running an operation. @@ -101,91 +77,79 @@ var checkErr = function(shouldPass, opFunc) { * fsync_unlock. */ var testOps = function(db, allowedActions) { - checkErr(allowedActions.hasOwnProperty('insert'), - function() { - var res = db.user.insert({y: 1}); - if (res.hasWriteError()) - throw Error("insert failed: " + tojson(res.getRawResponse())); - }); - - checkErr(allowedActions.hasOwnProperty('update'), - function() { - var res = db.user.update({y: 1}, {z: 3}); - if (res.hasWriteError()) - throw Error("update failed: " + tojson(res.getRawResponse())); - }); - - checkErr(allowedActions.hasOwnProperty('remove'), - function() { - var res = db.user.remove({y: 1}); - if (res.hasWriteError()) - throw Error("remove failed: " + tojson(res.getRawResponse())); - }); - - checkErr(allowedActions.hasOwnProperty('query'), - function() { - db.user.findOne({y: 1}); - }); - - checkErr(allowedActions.hasOwnProperty('killOp'), - function() { - var errorCodeUnauthorized = 13; - var res = db.killOp(1); - - if (res.code == errorCodeUnauthorized) { - throw Error("unauthorized killOp"); - } - }); - - checkErr(allowedActions.hasOwnProperty('currentOp'), - function() { - var errorCodeUnauthorized = 13; - var res = db.currentOp(); - - if (res.code == errorCodeUnauthorized) { - throw Error("unauthorized currentOp"); - } - }); - - checkErr(allowedActions.hasOwnProperty('index_r'), - function() { - db.system.indexes.findOne(); - }); - - checkErr(allowedActions.hasOwnProperty('index_w'), - function() { - var res = db.user.ensureIndex({x: 1}); - if (res.code == 13) { // Unauthorized - throw Error("unauthorized currentOp"); - } - }); - - checkErr(allowedActions.hasOwnProperty('profile_r'), - function() { - db.system.profile.findOne(); - }); - - checkErr(allowedActions.hasOwnProperty('profile_w'), - function() { - var res = db.system.profile.insert({x: 1}); - if (res.hasWriteError()) { - throw Error("profile insert failed: " + tojson(res.getRawResponse())); - } - }); - - checkErr(allowedActions.hasOwnProperty('user_r'), - function() { - var result = db.runCommand({usersInfo: 1}); - if (!result.ok) { - throw new Error(tojson(result)); - } - }); - - checkErr(allowedActions.hasOwnProperty('user_w'), - function() { - db.createUser({user: 'a', pwd: 'a', roles: jsTest.basicUserRoles}); - assert(db.dropUser('a')); - }); + checkErr(allowedActions.hasOwnProperty('insert'), function() { + var res = db.user.insert({y: 1}); + if (res.hasWriteError()) + throw Error("insert failed: " + tojson(res.getRawResponse())); + }); + + checkErr(allowedActions.hasOwnProperty('update'), function() { + var res = db.user.update({y: 1}, {z: 3}); + if (res.hasWriteError()) + throw Error("update failed: " + tojson(res.getRawResponse())); + }); + + checkErr(allowedActions.hasOwnProperty('remove'), function() { + var res = db.user.remove({y: 1}); + if (res.hasWriteError()) + throw Error("remove failed: " + tojson(res.getRawResponse())); + }); + + checkErr(allowedActions.hasOwnProperty('query'), function() { + db.user.findOne({y: 1}); + }); + + checkErr(allowedActions.hasOwnProperty('killOp'), function() { + var errorCodeUnauthorized = 13; + var res = db.killOp(1); + + if (res.code == errorCodeUnauthorized) { + throw Error("unauthorized killOp"); + } + }); + + checkErr(allowedActions.hasOwnProperty('currentOp'), function() { + var errorCodeUnauthorized = 13; + var res = db.currentOp(); + + if (res.code == errorCodeUnauthorized) { + throw Error("unauthorized currentOp"); + } + }); + + checkErr(allowedActions.hasOwnProperty('index_r'), function() { + db.system.indexes.findOne(); + }); + + checkErr(allowedActions.hasOwnProperty('index_w'), function() { + var res = db.user.ensureIndex({x: 1}); + if (res.code == 13) { // Unauthorized + throw Error("unauthorized currentOp"); + } + }); + + checkErr(allowedActions.hasOwnProperty('profile_r'), function() { + db.system.profile.findOne(); + }); + + checkErr(allowedActions.hasOwnProperty('profile_w'), function() { + var res = db.system.profile.insert({x: 1}); + if (res.hasWriteError()) { + throw Error("profile insert failed: " + tojson(res.getRawResponse())); + } + }); + + checkErr(allowedActions.hasOwnProperty('user_r'), function() { + var result = db.runCommand({usersInfo: 1}); + if (!result.ok) { + throw new Error(tojson(result)); + } + }); + + checkErr(allowedActions.hasOwnProperty('user_w'), function() { + db.createUser({user: 'a', pwd: 'a', roles: jsTest.basicUserRoles}); + assert(db.dropUser('a')); + }); // Test for kill cursor (function() { @@ -206,33 +170,31 @@ var testOps = function(db, allowedActions) { // before proceeding. db.runCommand({whatsmyuri: 1}); - checkErr(!allowedActions.hasOwnProperty('killCursor'), - function() { - while (cursor.hasNext()) { - var next = cursor.next(); - - // This is a failure in mongos case. Standalone case will fail - // when next() was called. - if (next.code == 16336) { - // could not find cursor in cache for id - throw next.$err; - } - } - }); + checkErr(!allowedActions.hasOwnProperty('killCursor'), function() { + while (cursor.hasNext()) { + var next = cursor.next(); + + // This is a failure in mongos case. Standalone case will fail + // when next() was called. + if (next.code == 16336) { + // could not find cursor in cache for id + throw next.$err; + } + } + }); }); // TODO: enable test after SERVER-5813 is fixed. var isMongos = db.runCommand({isdbgrid: 1}).isdbgrid; // Note: fsyncUnlock is not supported in mongos. if (!isMongos) { - checkErr(allowedActions.hasOwnProperty('fsync_unlock'), - function() { - var res = db.fsyncUnlock(); - var errorCodeUnauthorized = 13; - - if (res.code == errorCodeUnauthorized) { - throw Error("unauthorized unauthorized fsyncUnlock"); - } - }); + checkErr(allowedActions.hasOwnProperty('fsync_unlock'), function() { + var res = db.fsyncUnlock(); + var errorCodeUnauthorized = 13; + + if (res.code == errorCodeUnauthorized) { + throw Error("unauthorized unauthorized fsyncUnlock"); + } + }); } }; diff --git a/jstests/auth/clac_system_colls.js b/jstests/auth/clac_system_colls.js index 527f6c29e5d..26a315db252 100644 --- a/jstests/auth/clac_system_colls.js +++ b/jstests/auth/clac_system_colls.js @@ -23,10 +23,7 @@ function runTest(admindb) { {resource: {db: admindb.getName(), collection: sysCollections[i]}, actions: ['find']}); } - var findPriv = { - resource: {db: admindb.getName(), collection: ""}, - actions: ['find'] - }; + var findPriv = {resource: {db: admindb.getName(), collection: ""}, actions: ['find']}; admindb.createRole({role: "FindInDB", roles: [], privileges: [findPriv]}); admindb.createRole({role: "FindOnSysRes", roles: [], privileges: sysPrivs}); diff --git a/jstests/auth/commands_builtin_roles.js b/jstests/auth/commands_builtin_roles.js index 1d5f5f59756..2fb65de8663 100644 --- a/jstests/auth/commands_builtin_roles.js +++ b/jstests/auth/commands_builtin_roles.js @@ -135,14 +135,8 @@ function checkForNonExistentRoles() { } } -var opts = { - auth: "", - enableExperimentalStorageDetailsCmd: "" -}; -var impls = { - createUsers: createUsers, - runOneTest: runOneTest -}; +var opts = {auth: "", enableExperimentalStorageDetailsCmd: ""}; +var impls = {createUsers: createUsers, runOneTest: runOneTest}; checkForNonExistentRoles(); diff --git a/jstests/auth/commands_user_defined_roles.js b/jstests/auth/commands_user_defined_roles.js index 8a7402f033d..8dff4e050be 100644 --- a/jstests/auth/commands_user_defined_roles.js +++ b/jstests/auth/commands_user_defined_roles.js @@ -102,10 +102,7 @@ function runOneTest(conn, t) { var actions = p.actions; for (var k = 0; k < actions.length; k++) { - var privDoc = { - resource: resource, - actions: [actions[k]] - }; + var privDoc = {resource: resource, actions: [actions[k]]}; msg = testInsufficientPrivileges(conn, t, testcase, [privDoc]); if (msg) { failures.push(t.testname + ": " + msg); @@ -157,14 +154,8 @@ function createUsers(conn) { adminDb.logout(); } -var opts = { - auth: "", - enableExperimentalStorageDetailsCmd: "" -}; -var impls = { - createUsers: createUsers, - runOneTest: runOneTest -}; +var opts = {auth: "", enableExperimentalStorageDetailsCmd: ""}; +var impls = {createUsers: createUsers, runOneTest: runOneTest}; // run all tests standalone var conn = MongoRunner.runMongod(opts); diff --git a/jstests/auth/copyauth.js b/jstests/auth/copyauth.js index f9baf5dee79..91e17edc669 100644 --- a/jstests/auth/copyauth.js +++ b/jstests/auth/copyauth.js @@ -57,11 +57,10 @@ function ClusterSpawnHelper(clusterType, startWithAuth, startWithTransitionToAut replSetTest.startSet(); replSetTest.initiate(); if (startWithAuth) { - authutil.asCluster(replSetTest.nodes, - replSetTestConfig.nodeOptions.keyFile, - function() { - replSetTest.awaitReplication(); - }); + authutil.asCluster( + replSetTest.nodes, replSetTestConfig.nodeOptions.keyFile, function() { + replSetTest.awaitReplication(); + }); } else { replSetTest.awaitReplication(); } @@ -122,8 +121,8 @@ function copydbBetweenClustersTest(configObj) { if (configObj.isSourceUsingAuth) { // Create a super user so we can create a regular user and not be locked out afterwards - source.conn.getDB("admin") - .createUser({user: "sourceSuperUser", pwd: "sourceSuperUser", roles: ["root"]}); + source.conn.getDB("admin").createUser( + {user: "sourceSuperUser", pwd: "sourceSuperUser", roles: ["root"]}); source.conn.getDB("admin").auth("sourceSuperUser", "sourceSuperUser"); source.conn.getDB(baseName)[baseName].save({i: 1}); @@ -157,8 +156,8 @@ function copydbBetweenClustersTest(configObj) { configObj.isTargetUsingTransitionToAuth); if (configObj.isTargetUsingAuth) { - target.conn.getDB("admin") - .createUser({user: "targetSuperUser", pwd: "targetSuperUser", roles: ["root"]}); + target.conn.getDB("admin").createUser( + {user: "targetSuperUser", pwd: "targetSuperUser", roles: ["root"]}); var readWhenLoggedOut = function() { target.conn.getDB(baseName)[baseName].findOne(); diff --git a/jstests/auth/copyauth_between_shards.js b/jstests/auth/copyauth_between_shards.js index 219d38c7f0f..419d548f969 100644 --- a/jstests/auth/copyauth_between_shards.js +++ b/jstests/auth/copyauth_between_shards.js @@ -4,11 +4,7 @@ var baseName = "jstests_clone_copyauth_between_shards"; function copydbWithinShardedCluster(useReplSets, passCredentials, useAuth) { - var clusterConfig = { - shards: 1, - mongos: 1, - config: 1 - }; + var clusterConfig = {shards: 1, mongos: 1, config: 1}; if (useAuth) { clusterConfig.auth = ""; diff --git a/jstests/auth/indexSystemUsers.js b/jstests/auth/indexSystemUsers.js index ef7187dfe46..fd33e906974 100644 --- a/jstests/auth/indexSystemUsers.js +++ b/jstests/auth/indexSystemUsers.js @@ -18,17 +18,15 @@ assert.eq(13, res.code); // unauthorized assert.writeError(adminDB.exploit.system.indexes.insert( {ns: "admin.system.users", key: {haxx: 1.0}, name: "haxx_1", unique: true, dropDups: true})); // Make sure that no indexes were built. -var collectionInfosCursor = - adminDB.runCommand("listCollections", - { - filter: { - $and: [ - {name: /^admin\.system\.users\.\$/}, - {name: {$ne: "admin.system.users.$_id_"}}, - {name: {$ne: "admin.system.users.$user_1_db_1"}} - ] - } - }); +var collectionInfosCursor = adminDB.runCommand("listCollections", { + filter: { + $and: [ + {name: /^admin\.system\.users\.\$/}, + {name: {$ne: "admin.system.users.$_id_"}}, + {name: {$ne: "admin.system.users.$user_1_db_1"}} + ] + } +}); assert.eq([], new DBCommandCursor(adminDB.getMongo(), collectionInfosCursor).toArray()); adminDB.logout(); diff --git a/jstests/auth/js_scope_leak.js b/jstests/auth/js_scope_leak.js index f1d5d192876..847919debf1 100644 --- a/jstests/auth/js_scope_leak.js +++ b/jstests/auth/js_scope_leak.js @@ -21,8 +21,7 @@ function missingOrEquals(string) { 'var global = function(){return this;}.call();' // Uncomment the next line when debugging. // + 'print(global.hasOwnProperty("someGlobal") ? someGlobal : "MISSING" );' - + - 'return !global.hasOwnProperty("someGlobal")' + + + 'return !global.hasOwnProperty("someGlobal")' + ' || someGlobal == unescape("' + escape(string) + '");' + '}()'; } diff --git a/jstests/auth/lib/commands_lib.js b/jstests/auth/lib/commands_lib.js index 2cc54f30eff..7725f9987de 100644 --- a/jstests/auth/lib/commands_lib.js +++ b/jstests/auth/lib/commands_lib.js @@ -86,14 +86,8 @@ var commandNotSupportedCode = 115; var shard0name = "shard0000"; // useful shorthand when defining the tests below -var roles_write = { - readWrite: 1, - readWriteAnyDatabase: 1, - dbOwner: 1, - restore: 1, - root: 1, - __system: 1 -}; +var roles_write = + {readWrite: 1, readWriteAnyDatabase: 1, dbOwner: 1, restore: 1, root: 1, __system: 1}; var roles_read = { read: 1, readAnyDatabase: 1, @@ -104,25 +98,9 @@ var roles_read = { root: 1, __system: 1 }; -var roles_readAny = { - readAnyDatabase: 1, - readWriteAnyDatabase: 1, - backup: 1, - root: 1, - __system: 1 -}; -var roles_dbAdmin = { - dbAdmin: 1, - dbAdminAnyDatabase: 1, - dbOwner: 1, - root: 1, - __system: 1 -}; -var roles_dbAdminAny = { - dbAdminAnyDatabase: 1, - root: 1, - __system: 1 -}; +var roles_readAny = {readAnyDatabase: 1, readWriteAnyDatabase: 1, backup: 1, root: 1, __system: 1}; +var roles_dbAdmin = {dbAdmin: 1, dbAdminAnyDatabase: 1, dbOwner: 1, root: 1, __system: 1}; +var roles_dbAdminAny = {dbAdminAnyDatabase: 1, root: 1, __system: 1}; var roles_writeDbAdmin = { readWrite: 1, readWriteAnyDatabase: 1, @@ -132,12 +110,7 @@ var roles_writeDbAdmin = { root: 1, __system: 1 }; -var roles_writeDbAdminAny = { - readWriteAnyDatabase: 1, - dbAdminAnyDatabase: 1, - root: 1, - __system: 1 -}; +var roles_writeDbAdminAny = {readWriteAnyDatabase: 1, dbAdminAnyDatabase: 1, root: 1, __system: 1}; var roles_readDbAdmin = { read: 1, readAnyDatabase: 1, @@ -149,31 +122,11 @@ var roles_readDbAdmin = { root: 1, __system: 1 }; -var roles_readDbAdminAny = { - readAnyDatabase: 1, - readWriteAnyDatabase: 1, - dbAdminAnyDatabase: 1, - root: 1, - __system: 1 -}; -var roles_monitoring = { - clusterMonitor: 1, - clusterAdmin: 1, - root: 1, - __system: 1 -}; -var roles_hostManager = { - hostManager: 1, - clusterAdmin: 1, - root: 1, - __system: 1 -}; -var roles_clusterManager = { - clusterManager: 1, - clusterAdmin: 1, - root: 1, - __system: 1 -}; +var roles_readDbAdminAny = + {readAnyDatabase: 1, readWriteAnyDatabase: 1, dbAdminAnyDatabase: 1, root: 1, __system: 1}; +var roles_monitoring = {clusterMonitor: 1, clusterAdmin: 1, root: 1, __system: 1}; +var roles_hostManager = {hostManager: 1, clusterAdmin: 1, root: 1, __system: 1}; +var roles_clusterManager = {clusterManager: 1, clusterAdmin: 1, root: 1, __system: 1}; var roles_all = { read: 1, readAnyDatabase: 1, @@ -653,8 +606,7 @@ var authCommandsLib = { { runOnDb: secondDbName, roles: roles_readAny, - privileges: - [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + privileges: [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] } ] }, @@ -668,10 +620,9 @@ var authCommandsLib = { { runOnDb: firstDbName, roles: Object.extend({restore: 1}, roles_writeDbAdmin), - privileges: [{ - resource: {db: firstDbName, collection: "x"}, - actions: ["createCollection"] - }] + privileges: [ + {resource: {db: firstDbName, collection: "x"}, actions: ["createCollection"]} + ] }, { runOnDb: firstDbName, @@ -890,8 +841,7 @@ var authCommandsLib = { { runOnDb: firstDbName, roles: roles_read, - privileges: - [{resource: {db: firstDbName, collection: "coll"}, actions: ["find"]}] + privileges: [{resource: {db: firstDbName, collection: "coll"}, actions: ["find"]}] }, { runOnDb: secondDbName, @@ -1161,8 +1111,7 @@ var authCommandsLib = { { runOnDb: secondDbName, roles: roles_readAny, - privileges: - [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + privileges: [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] } ] }, @@ -1187,8 +1136,7 @@ var authCommandsLib = { { runOnDb: secondDbName, roles: roles_readAny, - privileges: - [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + privileges: [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] } ] }, @@ -1350,8 +1298,7 @@ var authCommandsLib = { { runOnDb: secondDbName, roles: roles_readAny, - privileges: - [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + privileges: [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] } ] }, @@ -1619,8 +1566,7 @@ var authCommandsLib = { { runOnDb: secondDbName, roles: roles_readAny, - privileges: - [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + privileges: [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] } ] }, @@ -1860,10 +1806,9 @@ var authCommandsLib = { { runOnDb: secondDbName, roles: roles_dbAdminAny, - privileges: [{ - resource: {db: secondDbName, collection: ""}, - actions: ["enableProfiler"] - }] + privileges: [ + {resource: {db: secondDbName, collection: ""}, actions: ["enableProfiler"]} + ] } ] }, @@ -1908,8 +1853,7 @@ var authCommandsLib = { }, { testname: "renameCollection_sameDb", - command: - {renameCollection: firstDbName + ".x", to: firstDbName + ".y", dropTarget: true}, + command: {renameCollection: firstDbName + ".x", to: firstDbName + ".y", dropTarget: true}, setup: function(db) { db.getSisterDB(firstDbName).x.save({}); }, @@ -2003,8 +1947,7 @@ var authCommandsLib = { { runOnDb: firstDbName, roles: roles_dbAdmin, - privileges: - [{resource: {db: firstDbName, collection: "x"}, actions: ["reIndex"]}] + privileges: [{resource: {db: firstDbName, collection: "x"}, actions: ["reIndex"]}] }, { runOnDb: secondDbName, @@ -2058,10 +2001,9 @@ var authCommandsLib = { runOnDb: secondDbName, roles: {dbAdminAnyDatabase: 1, hostManager: 1, clusterAdmin: 1, root: 1, __system: 1}, - privileges: [{ - resource: {db: secondDbName, collection: ""}, - actions: ["repairDatabase"] - }] + privileges: [ + {resource: {db: secondDbName, collection: ""}, actions: ["repairDatabase"]} + ] } ] }, diff --git a/jstests/auth/localhostAuthBypass.js b/jstests/auth/localhostAuthBypass.js index 6cb315650ef..cd56e3bc160 100644 --- a/jstests/auth/localhostAuthBypass.js +++ b/jstests/auth/localhostAuthBypass.js @@ -79,17 +79,13 @@ var assertCannotRunCommands = function(mongo) { {param: "userCacheInvalidationIntervalSecs", val: 300} ]; params.forEach(function(p) { - var cmd = { - setParameter: 1 - }; + var cmd = {setParameter: 1}; cmd[p.param] = p.val; assert.commandFailedWithCode( mongo.getDB("admin").runCommand(cmd), authorizeErrorCode, "setParameter: " + p.param); }); params.forEach(function(p) { - var cmd = { - getParameter: 1 - }; + var cmd = {getParameter: 1}; cmd[p.param] = 1; assert.commandFailedWithCode( mongo.getDB("admin").runCommand(cmd), authorizeErrorCode, "getParameter: " + p.param); @@ -167,8 +163,8 @@ var runNonlocalTest = function(host) { assertCannotRunCommands(mongo); assert.throws(function() { - mongo.getDB("admin") - .createUser({user: username, pwd: password, roles: jsTest.adminUserRoles}); + mongo.getDB("admin").createUser( + {user: username, pwd: password, roles: jsTest.adminUserRoles}); }); assert.throws(function() { mongo.getDB("$external") diff --git a/jstests/auth/log_user_basic.js b/jstests/auth/log_user_basic.js index 817d83ac519..9e782fed9f5 100644 --- a/jstests/auth/log_user_basic.js +++ b/jstests/auth/log_user_basic.js @@ -26,10 +26,7 @@ if (0) { return null; } - var logInfo = { - id: res[1], - users: {} - }; + var logInfo = {id: res[1], users: {}}; var userLog = null; res = ID_USER_PATTERN.exec(line); @@ -64,11 +61,7 @@ if (0) { users: {} // contains authenticated users represented as a map of db to user names. }; - var connInfo2 = { - id: null, - mongo: conn2, - users: {} - }; + var connInfo2 = {id: null, mongo: conn2, users: {}}; var conn1Auth = [{user: 'foo', pwd: 'bar', db: 'test'}, {user: 'chun', pwd: 'li', db: 'sf'}]; diff --git a/jstests/auth/pseudo_commands.js b/jstests/auth/pseudo_commands.js index 510f8c71e53..2a882f219c8 100644 --- a/jstests/auth/pseudo_commands.js +++ b/jstests/auth/pseudo_commands.js @@ -68,10 +68,7 @@ function runTest(conn) { __system: true }; - var privilege = { - resource: {cluster: true}, - actions: ['inprog'] - }; + var privilege = {resource: {cluster: true}, actions: ['inprog']}; var testFunc = function(shouldPass) { var passed = true; @@ -110,10 +107,7 @@ function runTest(conn) { __system: true }; - var privilege = { - resource: {cluster: true}, - actions: ['killop'] - }; + var privilege = {resource: {cluster: true}, actions: ['killop']}; var testFunc = function(shouldPass) { var passed = true; @@ -159,10 +153,7 @@ function runTest(conn) { __system: true }; - var privilege = { - resource: {cluster: true}, - actions: ['unlock'] - }; + var privilege = {resource: {cluster: true}, actions: ['unlock']}; var testFunc = function(shouldPass) { var passed = true; diff --git a/jstests/auth/renameSystemCollections.js b/jstests/auth/renameSystemCollections.js index dffee963499..32b2478095d 100644 --- a/jstests/auth/renameSystemCollections.js +++ b/jstests/auth/renameSystemCollections.js @@ -7,12 +7,7 @@ var testDB2 = conn.getDB("testdb2"); var CodeUnauthorized = 13; -var backdoorUserDoc = { - user: 'backdoor', - db: 'admin', - pwd: 'hashed', - roles: ['root'] -}; +var backdoorUserDoc = {user: 'backdoor', db: 'admin', pwd: 'hashed', roles: ['root']}; adminDB.createUser({user: 'userAdmin', pwd: 'password', roles: ['userAdminAnyDatabase']}); diff --git a/jstests/auth/repl.js b/jstests/auth/repl.js index 17ab3c2db20..d6a1a9ce6ec 100644 --- a/jstests/auth/repl.js +++ b/jstests/auth/repl.js @@ -3,10 +3,7 @@ var baseName = "jstests_auth_repl"; var rsName = baseName + "_rs"; var rtName = baseName + "_rt"; -var mongoOptions = { - auth: null, - keyFile: "jstests/libs/key1" -}; +var mongoOptions = {auth: null, keyFile: "jstests/libs/key1"}; var authErrCode = 13; var AuthReplTest = function(spec) { @@ -178,11 +175,9 @@ jsTest.log("1 test replica sets"); var rs = new ReplSetTest({name: rsName, nodes: 2}); var nodes = rs.startSet(mongoOptions); rs.initiate(); -authutil.asCluster(nodes, - "jstests/libs/key1", - function() { - rs.awaitReplication(); - }); +authutil.asCluster(nodes, "jstests/libs/key1", function() { + rs.awaitReplication(); +}); var primary = rs.getPrimary(); var secondary = rs.getSecondary(); @@ -196,11 +191,9 @@ jsTest.log("2 test initial sync"); rs = new ReplSetTest({name: rsName, nodes: 1, nodeOptions: mongoOptions}); nodes = rs.startSet(); rs.initiate(); -authutil.asCluster(nodes, - "jstests/libs/key1", - function() { - rs.awaitReplication(); - }); +authutil.asCluster(nodes, "jstests/libs/key1", function() { + rs.awaitReplication(); +}); primary = rs.getPrimary(); diff --git a/jstests/auth/repl_auth.js b/jstests/auth/repl_auth.js index bafaafd8f7b..aa851840bc5 100644 --- a/jstests/auth/repl_auth.js +++ b/jstests/auth/repl_auth.js @@ -16,11 +16,11 @@ var admin = setupConn.getDB('admin'); admin.createUser({user: 'admin', pwd: 'password', roles: jsTest.adminUserRoles}); admin.auth('admin', 'password'); -setupConn.getDB('foo') - .createUser({user: 'foo', pwd: 'foopwd', roles: jsTest.basicUserRoles}, {w: NUM_NODES}); +setupConn.getDB('foo').createUser({user: 'foo', pwd: 'foopwd', roles: jsTest.basicUserRoles}, + {w: NUM_NODES}); setupConn.getDB('foo').logout(); -setupConn.getDB('bar') - .createUser({user: 'bar', pwd: 'barpwd', roles: jsTest.basicUserRoles}, {w: NUM_NODES}); +setupConn.getDB('bar').createUser({user: 'bar', pwd: 'barpwd', roles: jsTest.basicUserRoles}, + {w: NUM_NODES}); setupConn.getDB('bar').logout(); var replConn0 = new Mongo(rsTest.getURL()); diff --git a/jstests/auth/resource_pattern_matching.js b/jstests/auth/resource_pattern_matching.js index 5a4da66871c..36d6711ea52 100644 --- a/jstests/auth/resource_pattern_matching.js +++ b/jstests/auth/resource_pattern_matching.js @@ -135,7 +135,7 @@ function run_tests(granter, verifier) { run_test("specific", granter, verifier, - [{resource: {db: "a", collection: "a"}, actions: ["find"]}], + [{resource: {db: "a", collection: "a"}, actions: ["find"]}], { "a.a": should_find, "a.b": should_fail_find, @@ -143,50 +143,39 @@ function run_tests(granter, verifier) { "b.b": should_fail_find }); - run_test("glob_collection", - granter, - verifier, - [{resource: {db: "a", collection: ""}, actions: ["find"]}], - { - "a.a": should_find, - "a.b": should_find, - "b.a": should_fail_find, - "b.b": should_fail_find - }); + run_test( + "glob_collection", + granter, + verifier, + [{resource: {db: "a", collection: ""}, actions: ["find"]}], + {"a.a": should_find, "a.b": should_find, "b.a": should_fail_find, "b.b": should_fail_find}); - run_test("glob_database", - granter, - verifier, - [{resource: {db: "", collection: "a"}, actions: ["find"]}], - { - "a.a": should_find, - "a.b": should_fail_find, - "b.a": should_find, - "b.b": should_fail_find - }); + run_test( + "glob_database", + granter, + verifier, + [{resource: {db: "", collection: "a"}, actions: ["find"]}], + {"a.a": should_find, "a.b": should_fail_find, "b.a": should_find, "b.b": should_fail_find}); run_test("glob_all", granter, verifier, - [{resource: {db: "", collection: ""}, actions: ["find"]}], + [{resource: {db: "", collection: ""}, actions: ["find"]}], {"a.a": should_find, "a.b": should_find, "b.a": should_find, "b.b": should_find}); - run_test("any_resource", - granter, - verifier, - [{resource: {anyResource: true}, actions: ["find"]}], - { - "a.a": should_find, - "a.b": should_find, - "b.a": should_find, - "b.b": should_find, - "c.a": should_find - }); + run_test( + "any_resource", granter, verifier, [{resource: {anyResource: true}, actions: ["find"]}], { + "a.a": should_find, + "a.b": should_find, + "b.a": should_find, + "b.b": should_find, + "c.a": should_find + }); run_test("no_global_access", granter, verifier, - [{resource: {db: "$", collection: "cmd"}, actions: ["find"]}], + [{resource: {db: "$", collection: "cmd"}, actions: ["find"]}], { "a.a": function(testdb, testcol) { var r = testdb.stats(); diff --git a/jstests/auth/role_management_commands.js b/jstests/auth/role_management_commands.js index 9847818e3b1..af2f7709bf1 100644 --- a/jstests/auth/role_management_commands.js +++ b/jstests/auth/role_management_commands.js @@ -180,12 +180,10 @@ function runTest(conn) { (function testGrantPrivilegesToRole() { jsTestLog("Testing grantPrivilegesToRole"); - adminUserAdmin.grantPrivilegesToRole( - 'adminRole', - [ - {resource: {cluster: true}, actions: ['serverStatus']}, - {resource: {db: "", collection: ""}, actions: ['find']} - ]); + adminUserAdmin.grantPrivilegesToRole('adminRole', [ + {resource: {cluster: true}, actions: ['serverStatus']}, + {resource: {db: "", collection: ""}, actions: ['find']} + ]); assert.doesNotThrow(function() { db.foo.findOne(); }); @@ -197,12 +195,10 @@ function runTest(conn) { assert.commandWorked(db.adminCommand('serverStatus')); testUserAdmin.updateUser('testUser', {roles: ['testRole2']}); - testUserAdmin.grantPrivilegesToRole( - 'testRole2', - [ - {resource: {db: 'test', collection: ''}, actions: ['insert', 'update']}, - {resource: {db: 'test', collection: 'foo'}, actions: ['find']} - ]); + testUserAdmin.grantPrivilegesToRole('testRole2', [ + {resource: {db: 'test', collection: ''}, actions: ['insert', 'update']}, + {resource: {db: 'test', collection: 'foo'}, actions: ['find']} + ]); assert.doesNotThrow(function() { db.foo.findOne(); }); @@ -219,7 +215,7 @@ function runTest(conn) { testUserAdmin.revokePrivilegesFromRole( 'testRole2', - [{resource: {db: 'test', collection: ''}, actions: ['insert', 'update', 'find']}]); + [{resource: {db: 'test', collection: ''}, actions: ['insert', 'update', 'find']}]); assert.doesNotThrow(function() { db.foo.findOne(); }); diff --git a/jstests/auth/role_management_commands_edge_cases.js b/jstests/auth/role_management_commands_edge_cases.js index 122221ce234..5af309a1a7a 100644 --- a/jstests/auth/role_management_commands_edge_cases.js +++ b/jstests/auth/role_management_commands_edge_cases.js @@ -243,10 +243,7 @@ function runTest(conn) { db.grantPrivilegesToRole("role1", []); }); - var basicPriv = { - resource: {db: 'test', collection: ""}, - actions: ['find'] - }; + var basicPriv = {resource: {db: 'test', collection: ""}, actions: ['find']}; // Invalid first argument assert.throws(function() { @@ -302,10 +299,7 @@ function runTest(conn) { "readWrite", [{resource: {db: 'test', collection: ''}, actions: ['find']}]); }); - var basicPriv = { - resource: {db: 'test', collection: ""}, - actions: ['find'] - }; + var basicPriv = {resource: {db: 'test', collection: ""}, actions: ['find']}; // Invalid first argument assert.throws(function() { diff --git a/jstests/auth/server-4892.js b/jstests/auth/server-4892.js index ef0c95c868e..4926ea7e131 100644 --- a/jstests/auth/server-4892.js +++ b/jstests/auth/server-4892.js @@ -46,44 +46,42 @@ function expectNumLiveCursors(mongod, expectedNumLiveCursors) { expectedNumLiveCursors + ")"); } -withMongod({noauth: ""}, - function setupTest(mongod) { - var admin, somedb, conn; - conn = new Mongo(mongod.host); - admin = conn.getDB('admin'); - somedb = conn.getDB('somedb'); - admin.createUser({user: 'admin', pwd: 'admin', roles: jsTest.adminUserRoles}); - admin.auth('admin', 'admin'); - somedb.createUser({user: 'frim', pwd: 'fram', roles: jsTest.basicUserRoles}); - somedb.data.drop(); - for (var i = 0; i < 10; ++i) { - assert.writeOK(somedb.data.insert({val: i})); - } - admin.logout(); - }); +withMongod({noauth: ""}, function setupTest(mongod) { + var admin, somedb, conn; + conn = new Mongo(mongod.host); + admin = conn.getDB('admin'); + somedb = conn.getDB('somedb'); + admin.createUser({user: 'admin', pwd: 'admin', roles: jsTest.adminUserRoles}); + admin.auth('admin', 'admin'); + somedb.createUser({user: 'frim', pwd: 'fram', roles: jsTest.basicUserRoles}); + somedb.data.drop(); + for (var i = 0; i < 10; ++i) { + assert.writeOK(somedb.data.insert({val: i})); + } + admin.logout(); +}); -withMongod({auth: ""}, - function runTest(mongod) { - var conn = new Mongo(mongod.host); - var somedb = conn.getDB('somedb'); - somedb.auth('frim', 'fram'); +withMongod({auth: ""}, function runTest(mongod) { + var conn = new Mongo(mongod.host); + var somedb = conn.getDB('somedb'); + somedb.auth('frim', 'fram'); - expectNumLiveCursors(mongod, 0); + expectNumLiveCursors(mongod, 0); - var cursor = somedb.data.find({}, {'_id': 1}).batchSize(1); - cursor.next(); - expectNumLiveCursors(mongod, 1); + var cursor = somedb.data.find({}, {'_id': 1}).batchSize(1); + cursor.next(); + expectNumLiveCursors(mongod, 1); - cursor = null; - // NOTE(schwerin): We assume that after setting cursor = null, there are no remaining - // references - // to the cursor, and that gc() will deterministically garbage collect it. - gc(); + cursor = null; + // NOTE(schwerin): We assume that after setting cursor = null, there are no remaining + // references + // to the cursor, and that gc() will deterministically garbage collect it. + gc(); - // NOTE(schwerin): dbKillCursors gets piggybacked on subsequent messages on the - // connection, so we - // have to force a message to the server. - somedb.data.findOne(); + // NOTE(schwerin): dbKillCursors gets piggybacked on subsequent messages on the + // connection, so we + // have to force a message to the server. + somedb.data.findOne(); - expectNumLiveCursors(mongod, 0); - }); + expectNumLiveCursors(mongod, 0); +}); diff --git a/jstests/auth/show_log_auth.js b/jstests/auth/show_log_auth.js index b318e0536ad..05df5f20610 100644 --- a/jstests/auth/show_log_auth.js +++ b/jstests/auth/show_log_auth.js @@ -11,14 +11,18 @@ function assertStartsWith(s, prefix) { assert.eq(s.substr(0, prefix.length), prefix); } -assertStartsWith(print.captureAllOutput(function() { - shellHelper.show('logs'); -}).output[0], +assertStartsWith(print + .captureAllOutput(function() { + shellHelper.show('logs'); + }) + .output[0], 'Error while trying to show logs'); -assertStartsWith(print.captureAllOutput(function() { - shellHelper.show('log ' + baseName); -}).output[0], +assertStartsWith(print + .captureAllOutput(function() { + shellHelper.show('log ' + baseName); + }) + .output[0], 'Error while trying to show ' + baseName + ' log'); db.auth("admin", "pass"); diff --git a/jstests/auth/upgrade_noauth_to_keyfile.js b/jstests/auth/upgrade_noauth_to_keyfile.js index 372ae61af2b..da517fef031 100644 --- a/jstests/auth/upgrade_noauth_to_keyfile.js +++ b/jstests/auth/upgrade_noauth_to_keyfile.js @@ -12,17 +12,11 @@ load('jstests/multiVersion/libs/multi_rs.js'); var keyFilePath = 'jstests/libs/key1'; // Disable auth explicitly - var noAuthOptions = { - noauth: '' - }; + var noAuthOptions = {noauth: ''}; // Undefine the flags we're replacing, otherwise upgradeSet will keep old values. - var transitionToAuthOptions = { - noauth: undefined, - clusterAuthMode: 'keyFile', - keyFile: keyFilePath, - transitionToAuth: '' - }; + var transitionToAuthOptions = + {noauth: undefined, clusterAuthMode: 'keyFile', keyFile: keyFilePath, transitionToAuth: ''}; var keyFileOptions = { clusterAuthMode: 'keyFile', keyFile: keyFilePath, diff --git a/jstests/auth/upgrade_noauth_to_keyfile_with_sharding.js b/jstests/auth/upgrade_noauth_to_keyfile_with_sharding.js index f6ecfec9abb..8cfca96933a 100644 --- a/jstests/auth/upgrade_noauth_to_keyfile_with_sharding.js +++ b/jstests/auth/upgrade_noauth_to_keyfile_with_sharding.js @@ -7,18 +7,13 @@ load('jstests/ssl/libs/ssl_helpers.js'); 'use strict'; // Disable auth explicitly - var noAuthOptions = { - noauth: '' - }; + var noAuthOptions = {noauth: ''}; var transitionToAuthOptions = { clusterAuthMode: 'keyFile', keyFile: KEYFILE, transitionToAuth: '' }; - var keyFileOptions = { - clusterAuthMode: 'keyFile', - keyFile: KEYFILE - }; + var keyFileOptions = {clusterAuthMode: 'keyFile', keyFile: KEYFILE}; print('=== Testing no-auth/transitionToAuth cluster ==='); mixedShardTest(noAuthOptions, transitionToAuthOptions, true); diff --git a/jstests/auth/user_defined_roles.js b/jstests/auth/user_defined_roles.js index 0190ad9385e..c786018dbb5 100644 --- a/jstests/auth/user_defined_roles.js +++ b/jstests/auth/user_defined_roles.js @@ -12,8 +12,8 @@ function runTest(conn) { conn.getDB('admin').createUser({user: 'admin', pwd: 'pwd', roles: ['root']}); conn.getDB('admin').auth('admin', 'pwd'); - conn.getDB('admin') - .createUser({user: 'userAdmin', pwd: 'pwd', roles: ['userAdminAnyDatabase']}); + conn.getDB('admin').createUser( + {user: 'userAdmin', pwd: 'pwd', roles: ['userAdminAnyDatabase']}); conn.getDB('admin').logout(); var userAdminConn = new Mongo(conn.host); @@ -99,12 +99,11 @@ function runTest(conn) { testDB.updateUser('testUser', {customData: {zipCode: 10036}}); }); assert.eq(null, testDB.getUser('testUser').customData); - testUserAdmin.grantPrivilegesToRole( - 'testRole1', - [{ - resource: {db: 'test', collection: ''}, - actions: ['changeOwnPassword', 'changeOwnCustomData'] - }]); + testUserAdmin.grantPrivilegesToRole('testRole1', + [{ + resource: {db: 'test', collection: ''}, + actions: ['changeOwnPassword', 'changeOwnCustomData'] + }]); testDB.changeUserPassword('testUser', 'password'); assert(!testDB.auth('testUser', 'pwd')); assert(testDB.auth('testUser', 'password')); @@ -124,11 +123,9 @@ function runTest(conn) { assert.eq(10036, testDB.getUser('testUser').customData.zipCode); // Test changeAnyPassword/changeAnyCustomData - testUserAdmin.grantPrivilegesToRole('testRole2', - [{ - resource: {db: 'test', collection: ''}, - actions: ['changePassword', 'changeCustomData'] - }]); + testUserAdmin.grantPrivilegesToRole('testRole2', [ + {resource: {db: 'test', collection: ''}, actions: ['changePassword', 'changeCustomData']} + ]); testDB.changeUserPassword('testUser', 'pwd'); assert(!testDB.auth('testUser', 'password')); assert(testDB.auth('testUser', 'pwd')); @@ -137,8 +134,8 @@ function runTest(conn) { // Test privileges on the cluster resource assert.commandFailed(testDB.runCommand({serverStatus: 1})); - adminUserAdmin.grantPrivilegesToRole( - 'adminRole', [{resource: {cluster: true}, actions: ['serverStatus']}]); + adminUserAdmin.grantPrivilegesToRole('adminRole', + [{resource: {cluster: true}, actions: ['serverStatus']}]); assert.commandWorked(testDB.serverStatus()); } diff --git a/jstests/auth/user_defined_roles_on_secondaries.js b/jstests/auth/user_defined_roles_on_secondaries.js index 959b76a3cae..0bf3894d0ab 100644 --- a/jstests/auth/user_defined_roles_on_secondaries.js +++ b/jstests/auth/user_defined_roles_on_secondaries.js @@ -87,13 +87,12 @@ rstest.add(); rstest.reInitiate(); - rstest.getPrimary().getDB("db1").createRole( - { - role: "r3", - roles: ["r1", "r2"], - privileges: [{resource: {db: "db1", collection: "log"}, actions: ["update"]}] - }, - {w: 2}); + rstest.getPrimary().getDB("db1").createRole({ + role: "r3", + roles: ["r1", "r2"], + privileges: [{resource: {db: "db1", collection: "log"}, actions: ["update"]}] + }, + {w: 2}); // Verify that both members of the set see the same role graph. rstest.nodes.forEach(function(node) { diff --git a/jstests/auth/user_management_commands.js b/jstests/auth/user_management_commands.js index e835aa4b348..a5cca448576 100644 --- a/jstests/auth/user_management_commands.js +++ b/jstests/auth/user_management_commands.js @@ -113,14 +113,13 @@ function runTest(conn) { assert.commandFailedWithCode(db.runCommand({collMod: 'foo', usePowerOf2Sizes: true}), authzErrorCode); - testUserAdmin.grantRolesToUser('spencer', - [ - 'readWrite', - 'dbAdmin', - {role: 'readWrite', db: 'test'}, - {role: 'testRole', db: 'test'}, - 'readWrite' - ]); + testUserAdmin.grantRolesToUser('spencer', [ + 'readWrite', + 'dbAdmin', + {role: 'readWrite', db: 'test'}, + {role: 'testRole', db: 'test'}, + 'readWrite' + ]); assert.commandWorked(db.runCommand({collMod: 'foo', usePowerOf2Sizes: true})); assert.writeOK(db.foo.update({}, {$inc: {a: 1}})); @@ -135,13 +134,11 @@ function runTest(conn) { (function testRevokeRolesFromUser() { jsTestLog("Testing revokeRolesFromUser"); - testUserAdmin.revokeRolesFromUser( - 'spencer', - [ - 'readWrite', - {role: 'dbAdmin', db: 'test2'}, // role user doesnt have - "testRole" - ]); + testUserAdmin.revokeRolesFromUser('spencer', [ + 'readWrite', + {role: 'dbAdmin', db: 'test2'}, // role user doesnt have + "testRole" + ]); assert.commandWorked(db.runCommand({collMod: 'foo', usePowerOf2Sizes: true})); hasAuthzError(db.foo.update({}, {$inc: {a: 1}})); diff --git a/jstests/concurrency/fsm_background_workloads/background_base.js b/jstests/concurrency/fsm_background_workloads/background_base.js index febc3a5d0dd..abcf751e029 100644 --- a/jstests/concurrency/fsm_background_workloads/background_base.js +++ b/jstests/concurrency/fsm_background_workloads/background_base.js @@ -31,10 +31,7 @@ var $config = (function() { } }; - var transitions = { - wait: {checkForTermination: 1}, - checkForTermination: {wait: 1} - }; + var transitions = {wait: {checkForTermination: 1}, checkForTermination: {wait: 1}}; var teardown = function teardown(db, collName, cluster) { db.getSiblingDB('config').fsm_background.drop(); diff --git a/jstests/concurrency/fsm_example_inheritance.js b/jstests/concurrency/fsm_example_inheritance.js index 01d95a0d9d6..8c45525d7e3 100644 --- a/jstests/concurrency/fsm_example_inheritance.js +++ b/jstests/concurrency/fsm_example_inheritance.js @@ -4,21 +4,20 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_example.js'); // for $config // extendWorkload takes a $config object and a callback, and returns an extended $config object. -var $config = extendWorkload($config, - function($config, $super) { - // In the callback, $super is the base workload definition we're - // extending, - // and $config is the extended workload definition we're creating. +var $config = extendWorkload($config, function($config, $super) { + // In the callback, $super is the base workload definition we're + // extending, + // and $config is the extended workload definition we're creating. - // You can replace any properties on $config, including methods you - // want to override. - $config.setup = function(db, collName, cluster) { - // Overridden methods should usually call the corresponding - // method on $super. - $super.setup.apply(this, arguments); + // You can replace any properties on $config, including methods you + // want to override. + $config.setup = function(db, collName, cluster) { + // Overridden methods should usually call the corresponding + // method on $super. + $super.setup.apply(this, arguments); - db[collName].ensureIndex({exampleIndexedField: 1}); - }; + db[collName].ensureIndex({exampleIndexedField: 1}); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_libs/cluster.js b/jstests/concurrency/fsm_libs/cluster.js index 5a350c9836d..a587d8f323a 100644 --- a/jstests/concurrency/fsm_libs/cluster.js +++ b/jstests/concurrency/fsm_libs/cluster.js @@ -97,10 +97,7 @@ var Cluster = function(options) { var initialized = false; var clusterStartTime; - var _conns = { - mongos: [], - mongod: [] - }; + var _conns = {mongos: [], mongod: []}; var nextConn = 0; var replSets = []; @@ -342,11 +339,7 @@ var Cluster = function(options) { return ''; } - var cluster = { - mongos: [], - config: [], - shards: {} - }; + var cluster = {mongos: [], config: [], shards: {}}; var i = 0; var mongos = st.s0; diff --git a/jstests/concurrency/fsm_libs/composer.js b/jstests/concurrency/fsm_libs/composer.js index 495648fb01a..99cfb64f34d 100644 --- a/jstests/concurrency/fsm_libs/composer.js +++ b/jstests/concurrency/fsm_libs/composer.js @@ -51,12 +51,11 @@ var composer = (function() { } var args = configs[workload]; - Object.keys(args.states) - .forEach(function(state) { - if (state !== args.startState) { - otherStates.push({workload: workload, state: state}); - } - }); + Object.keys(args.states).forEach(function(state) { + if (state !== args.startState) { + otherStates.push({workload: workload, state: state}); + } + }); }); var next = getRandomElem(otherStates, Random.rand()); @@ -70,8 +69,6 @@ var composer = (function() { return items[Math.floor(randVal * items.length)]; } - return { - run: runCombinedFSM - }; + return {run: runCombinedFSM}; })(); diff --git a/jstests/concurrency/fsm_libs/fsm.js b/jstests/concurrency/fsm_libs/fsm.js index 0a3e4a45bf4..e7a3eafb946 100644 --- a/jstests/concurrency/fsm_libs/fsm.js +++ b/jstests/concurrency/fsm_libs/fsm.js @@ -21,11 +21,7 @@ var fsm = (function() { // See fsm_libs/cluster.js for the format of args.cluster. var connCache; if (args.passConnectionCache) { - connCache = { - mongos: [], - config: [], - shards: {} - }; + connCache = {mongos: [], config: [], shards: {}}; connCache.mongos = args.cluster.mongos.map(connStr => new Mongo(connStr)); connCache.config = args.cluster.config.map(connStr => new Mongo(connStr)); @@ -87,8 +83,5 @@ var fsm = (function() { assert(false, 'not reached'); } - return { - run: runFSM, - _getWeightedRandomChoice: getWeightedRandomChoice - }; + return {run: runFSM, _getWeightedRandomChoice: getWeightedRandomChoice}; })(); diff --git a/jstests/concurrency/fsm_libs/parse_config.js b/jstests/concurrency/fsm_libs/parse_config.js index b569f660c8a..3c365dc5f4c 100644 --- a/jstests/concurrency/fsm_libs/parse_config.js +++ b/jstests/concurrency/fsm_libs/parse_config.js @@ -36,44 +36,40 @@ function parseConfig(config) { assert.eq('object', typeof config.states); assert.gt(Object.keys(config.states).length, 0); - Object.keys(config.states) - .forEach(function(k) { - assert.eq( - 'function', typeof config.states[k], 'config.states.' + k + ' is not a function'); - if (config.passConnectionCache) { - assert.eq(3, - config.states[k].length, - 'if passConnectionCache is true, state functions should ' + - 'accept 3 parameters: db, collName, and connCache'); - } else { - assert.eq(2, - config.states[k].length, - 'if passConnectionCache is false, state functions should ' + - 'accept 2 parameters: db and collName'); - } - }); + Object.keys(config.states).forEach(function(k) { + assert.eq('function', typeof config.states[k], 'config.states.' + k + ' is not a function'); + if (config.passConnectionCache) { + assert.eq(3, + config.states[k].length, + 'if passConnectionCache is true, state functions should ' + + 'accept 3 parameters: db, collName, and connCache'); + } else { + assert.eq(2, + config.states[k].length, + 'if passConnectionCache is false, state functions should ' + + 'accept 2 parameters: db and collName'); + } + }); // assert all states mentioned in config.transitions are present in config.states assert.eq('object', typeof config.transitions); assert.gt(Object.keys(config.transitions).length, 0); - Object.keys(config.transitions) - .forEach(function(fromState) { - assert(config.states.hasOwnProperty(fromState), - 'config.transitions contains a state not in config.states: ' + fromState); + Object.keys(config.transitions).forEach(function(fromState) { + assert(config.states.hasOwnProperty(fromState), + 'config.transitions contains a state not in config.states: ' + fromState); - assert.gt(Object.keys(config.transitions[fromState]).length, 0); - Object.keys(config.transitions[fromState]) - .forEach(function(toState) { - assert(config.states.hasOwnProperty(toState), - 'config.transitions.' + fromState + - ' contains a state not in config.states: ' + toState); - assert.eq('number', - typeof config.transitions[fromState][toState], - 'transitions.' + fromState + '.' + toState + ' should be a number'); - assert(!isNaN(config.transitions[fromState][toState]), - 'transitions.' + fromState + '.' + toState + ' cannot be NaN'); - }); + assert.gt(Object.keys(config.transitions[fromState]).length, 0); + Object.keys(config.transitions[fromState]).forEach(function(toState) { + assert(config.states.hasOwnProperty(toState), + 'config.transitions.' + fromState + ' contains a state not in config.states: ' + + toState); + assert.eq('number', + typeof config.transitions[fromState][toState], + 'transitions.' + fromState + '.' + toState + ' should be a number'); + assert(!isNaN(config.transitions[fromState][toState]), + 'transitions.' + fromState + '.' + toState + ' cannot be NaN'); }); + }); config.setup = config.setup || function() {}; assert.eq('function', typeof config.setup); diff --git a/jstests/concurrency/fsm_libs/runner.js b/jstests/concurrency/fsm_libs/runner.js index 4881676636d..cba8c4efe8a 100644 --- a/jstests/concurrency/fsm_libs/runner.js +++ b/jstests/concurrency/fsm_libs/runner.js @@ -214,9 +214,7 @@ var runner = (function() { myDB[collName].drop(); if (cluster.isSharded()) { - var shardKey = context[workload].config.data.shardKey || { - _id: 'hashed' - }; + var shardKey = context[workload].config.data.shardKey || {_id: 'hashed'}; // TODO: allow workload config data to specify split cluster.shardCollection(myDB[collName], shardKey, false); } @@ -328,11 +326,13 @@ var runner = (function() { numUniqueTraces + ' of which were unique:\n\n'; return summary + - uniqueTraces.map(function(obj) { - var line = pluralize('thread', obj.freq) + ' with tids ' + - JSON.stringify(obj.tids) + ' threw\n'; - return indent(line + obj.value, 8); - }).join('\n\n'); + uniqueTraces + .map(function(obj) { + var line = pluralize('thread', obj.freq) + ' with tids ' + + JSON.stringify(obj.tids) + ' threw\n'; + return indent(line + obj.value, 8); + }) + .join('\n\n'); } if (workerErrs.length > 0) { @@ -401,9 +401,7 @@ var runner = (function() { workloads.forEach(function(workload) { load(workload); // for $config assert.neq('undefined', typeof $config, '$config was not defined by ' + workload); - context[workload] = { - config: parseConfig($config) - }; + context[workload] = {config: parseConfig($config)}; if (applyMultipliers) { context[workload].config.iterations *= executionOptions.iterationMultiplier; context[workload].config.threadCount *= executionOptions.threadMultiplier; @@ -525,7 +523,7 @@ var runner = (function() { } finally { // Threads must be joined before destruction, so do this // even in the presence of exceptions. - errors.push(... threadMgr.joinAll().map( + errors.push(...threadMgr.joinAll().map( e => new WorkloadFailure( e.err, e.stack, e.tid, 'Foreground ' + e.workloads.join(' ')))); } @@ -630,8 +628,8 @@ var runner = (function() { var dbHashBlacklist = ['local']; if (cleanupOptions.dropDatabaseBlacklist) { - dbBlacklist.push(... cleanupOptions.dropDatabaseBlacklist); - dbHashBlacklist.push(... cleanupOptions.dropDatabaseBlacklist); + dbBlacklist.push(...cleanupOptions.dropDatabaseBlacklist); + dbHashBlacklist.push(...cleanupOptions.dropDatabaseBlacklist); } if (!cleanupOptions.keepExistingDatabases) { dropAllDatabases(cluster.getDB('test'), dbBlacklist); @@ -703,7 +701,7 @@ var runner = (function() { } finally { // Set a flag so background threads know to terminate. bgThreadMgr.markAllForTermination(); - errors.push(... bgThreadMgr.joinAll().map( + errors.push(...bgThreadMgr.joinAll().map( e => new WorkloadFailure( e.err, e.stack, e.tid, 'Background ' + e.workloads.join(' ')))); } diff --git a/jstests/concurrency/fsm_libs/thread_mgr.js b/jstests/concurrency/fsm_libs/thread_mgr.js index 145fb57146e..9680e22435b 100644 --- a/jstests/concurrency/fsm_libs/thread_mgr.js +++ b/jstests/concurrency/fsm_libs/thread_mgr.js @@ -211,22 +211,18 @@ workerThread.fsm = function(workloads, args, options) { load('jstests/concurrency/fsm_libs/worker_thread.js'); // for workerThread.main load('jstests/concurrency/fsm_libs/fsm.js'); // for fsm.run - return workerThread.main(workloads, - args, - function(configs) { - var workloads = Object.keys(configs); - assert.eq(1, workloads.length); - fsm.run(configs[workloads[0]]); - }); + return workerThread.main(workloads, args, function(configs) { + var workloads = Object.keys(configs); + assert.eq(1, workloads.length); + fsm.run(configs[workloads[0]]); + }); }; workerThread.composed = function(workloads, args, options) { load('jstests/concurrency/fsm_libs/worker_thread.js'); // for workerThread.main load('jstests/concurrency/fsm_libs/composer.js'); // for composer.run - return workerThread.main(workloads, - args, - function(configs) { - composer.run(workloads, configs, options); - }); + return workerThread.main(workloads, args, function(configs) { + composer.run(workloads, configs, options); + }); }; diff --git a/jstests/concurrency/fsm_libs/worker_thread.js b/jstests/concurrency/fsm_libs/worker_thread.js index 5c6dd771509..7a9bf6b3304 100644 --- a/jstests/concurrency/fsm_libs/worker_thread.js +++ b/jstests/concurrency/fsm_libs/worker_thread.js @@ -62,21 +62,20 @@ var workerThread = (function() { // configurable, enumerable, and writable. To prevent workloads from changing // the iterations and threadCount properties in their state functions, we redefine // them here as non-configurable, non-enumerable, and non-writable. - Object.defineProperties(data, - { - 'iterations': { - configurable: false, - enumerable: false, - writable: false, - value: data.iterations - }, - 'threadCount': { - configurable: false, - enumerable: false, - writable: false, - value: data.threadCount - } - }); + Object.defineProperties(data, { + 'iterations': { + configurable: false, + enumerable: false, + writable: false, + value: data.iterations + }, + 'threadCount': { + configurable: false, + enumerable: false, + writable: false, + value: data.threadCount + } + }); data.tid = args.tid; configs[workload] = { @@ -103,9 +102,7 @@ var workerThread = (function() { Random.setRandomSeed(args.seed); run(configs); - return { - ok: 1 - }; + return {ok: 1}; } catch (e) { args.errorLatch.countDown(); return { @@ -124,8 +121,6 @@ var workerThread = (function() { } } - return { - main: main - }; + return {main: main}; })(); diff --git a/jstests/concurrency/fsm_selftests.js b/jstests/concurrency/fsm_selftests.js index 686a6d286e7..30c614e9148 100644 --- a/jstests/concurrency/fsm_selftests.js +++ b/jstests/concurrency/fsm_selftests.js @@ -9,11 +9,7 @@ load('jstests/concurrency/fsm_libs/fsm.js'); (function() { var getWeightedRandomChoice = fsm._getWeightedRandomChoice; - var doc = { - a: 0.25, - b: 0.5, - c: 0.25 - }; + var doc = {a: 0.25, b: 0.5, c: 0.25}; // NOTE: getWeightedRandomChoice calls assert internally, so it will print stack traces // when assert.throws executes diff --git a/jstests/concurrency/fsm_workload_modifiers/make_capped.js b/jstests/concurrency/fsm_workload_modifiers/make_capped.js index 00f68964531..8bae4b4a9ff 100644 --- a/jstests/concurrency/fsm_workload_modifiers/make_capped.js +++ b/jstests/concurrency/fsm_workload_modifiers/make_capped.js @@ -17,11 +17,10 @@ function makeCapped($config, $super) { $config.setup = function setup(db, collName, cluster) { assertWhenOwnColl(function() { db[collName].drop(); - assertAlways.commandWorked(db.createCollection(collName, - { - capped: true, - size: 16384 // bytes - })); + assertAlways.commandWorked(db.createCollection(collName, { + capped: true, + size: 16384 // bytes + })); }); $super.setup.apply(this, arguments); diff --git a/jstests/concurrency/fsm_workloads/agg_base.js b/jstests/concurrency/fsm_workloads/agg_base.js index 846e6900215..9bc1be04785 100644 --- a/jstests/concurrency/fsm_workloads/agg_base.js +++ b/jstests/concurrency/fsm_workloads/agg_base.js @@ -45,9 +45,7 @@ var $config = (function() { } }; - var transitions = { - query: {query: 1} - }; + var transitions = {query: {query: 1}}; function setup(db, collName, cluster) { // load example data @@ -55,13 +53,12 @@ var $config = (function() { for (var i = 0; i < this.numDocs; ++i) { // note: padDoc caches the large string after allocating it once, so it's ok to call it // in this loop - bulk.insert(padDoc( - { - flag: i % 2 ? true : false, - rand: Random.rand(), - randInt: Random.randInt(this.numDocs) - }, - this.docSize)); + bulk.insert(padDoc({ + flag: i % 2 ? true : false, + rand: Random.rand(), + randInt: Random.randInt(this.numDocs) + }, + this.docSize)); } var res = bulk.execute(); assertWhenOwnColl.writeOK(res); diff --git a/jstests/concurrency/fsm_workloads/agg_graph_lookup.js b/jstests/concurrency/fsm_workloads/agg_graph_lookup.js index 7b675dc1e9c..aacbe632fc2 100644 --- a/jstests/concurrency/fsm_workloads/agg_graph_lookup.js +++ b/jstests/concurrency/fsm_workloads/agg_graph_lookup.js @@ -7,28 +7,28 @@ */ var $config = (function() { - var data = { - numDocs: 1000 - }; + var data = {numDocs: 1000}; var states = { query: function query(db, collName) { var limitAmount = 20; var startingId = Random.randInt(this.numDocs - limitAmount); - var res = db[collName].aggregate([ - {$match: {_id: {$gt: startingId}}}, - { - $graphLookup: { - from: collName, - startWith: "$to", - connectToField: "_id", - connectFromField: "to", - maxDepth: 10, - as: "out", - } - }, - {$limit: limitAmount} - ]).toArray(); + var res = db[collName] + .aggregate([ + {$match: {_id: {$gt: startingId}}}, + { + $graphLookup: { + from: collName, + startWith: "$to", + connectToField: "_id", + connectFromField: "to", + maxDepth: 10, + as: "out", + } + }, + {$limit: limitAmount} + ]) + .toArray(); assertWhenOwnColl.eq(res.length, limitAmount); }, @@ -40,10 +40,7 @@ var $config = (function() { } }; - var transitions = { - query: {query: 0.5, update: 0.5}, - update: {query: 0.5, update: 0.5} - }; + var transitions = {query: {query: 0.5, update: 0.5}, update: {query: 0.5, update: 0.5}}; function setup(db, collName, cluster) { // Load example data. diff --git a/jstests/concurrency/fsm_workloads/agg_group_external.js b/jstests/concurrency/fsm_workloads/agg_group_external.js index 22d71d4564d..e4ca604a99c 100644 --- a/jstests/concurrency/fsm_workloads/agg_group_external.js +++ b/jstests/concurrency/fsm_workloads/agg_group_external.js @@ -12,43 +12,41 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWo load('jstests/concurrency/fsm_workloads/agg_base.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); // for dropCollections -var $config = extendWorkload( - $config, - function($config, $super) { - - // use enough docs to exceed 100MB, the in-memory limit for $sort and $group - $config.data.numDocs = 24 * 1000; - var MB = 1024 * 1024; // bytes - assertAlways.lte(100 * MB, $config.data.numDocs * $config.data.docSize); - - // assume no other workload will manipulate collections with this prefix - $config.data.getOutputCollPrefix = function getOutputCollPrefix(collName) { - return collName + '_out_agg_group_external_'; - }; - - $config.states.query = function query(db, collName) { - var otherCollName = this.getOutputCollPrefix(collName) + this.tid; - var cursor = db[collName].aggregate( - [{$group: {_id: '$randInt', count: {$sum: 1}}}, {$out: otherCollName}], - {allowDiskUse: true}); - assertAlways.eq(0, cursor.itcount()); - assertWhenOwnColl(function() { - // sum the .count fields in the output coll - var sum = db[otherCollName] - .aggregate([{$group: {_id: null, totalCount: {$sum: '$count'}}}]) - .toArray()[0] - .totalCount; - assertWhenOwnColl.eq(this.numDocs, sum); - }.bind(this)); - }; - - $config.teardown = function teardown(db, collName, cluster) { - $super.teardown.apply(this, arguments); - - // drop all collections with this workload's assumed-to-be-unique prefix - // NOTE: assumes the prefix contains no special regex chars - dropCollections(db, new RegExp('^' + this.getOutputCollPrefix(collName))); - }; - - return $config; - }); +var $config = extendWorkload($config, function($config, $super) { + + // use enough docs to exceed 100MB, the in-memory limit for $sort and $group + $config.data.numDocs = 24 * 1000; + var MB = 1024 * 1024; // bytes + assertAlways.lte(100 * MB, $config.data.numDocs * $config.data.docSize); + + // assume no other workload will manipulate collections with this prefix + $config.data.getOutputCollPrefix = function getOutputCollPrefix(collName) { + return collName + '_out_agg_group_external_'; + }; + + $config.states.query = function query(db, collName) { + var otherCollName = this.getOutputCollPrefix(collName) + this.tid; + var cursor = db[collName].aggregate( + [{$group: {_id: '$randInt', count: {$sum: 1}}}, {$out: otherCollName}], + {allowDiskUse: true}); + assertAlways.eq(0, cursor.itcount()); + assertWhenOwnColl(function() { + // sum the .count fields in the output coll + var sum = db[otherCollName] + .aggregate([{$group: {_id: null, totalCount: {$sum: '$count'}}}]) + .toArray()[0] + .totalCount; + assertWhenOwnColl.eq(this.numDocs, sum); + }.bind(this)); + }; + + $config.teardown = function teardown(db, collName, cluster) { + $super.teardown.apply(this, arguments); + + // drop all collections with this workload's assumed-to-be-unique prefix + // NOTE: assumes the prefix contains no special regex chars + dropCollections(db, new RegExp('^' + this.getOutputCollPrefix(collName))); + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/agg_match.js b/jstests/concurrency/fsm_workloads/agg_match.js index a685096155b..ca9682e1a58 100644 --- a/jstests/concurrency/fsm_workloads/agg_match.js +++ b/jstests/concurrency/fsm_workloads/agg_match.js @@ -8,31 +8,29 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/agg_base.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.getOutCollName = function getOutCollName(collName) { - return collName + '_out_agg_match'; - }; + $config.data.getOutCollName = function getOutCollName(collName) { + return collName + '_out_agg_match'; + }; - $config.states.query = function query(db, collName) { - // note that all threads output to the same collection - var otherCollName = this.getOutCollName(collName); - var cursor = db[collName].aggregate([{$match: {flag: true}}, {$out: otherCollName}]); - assertAlways.eq(0, cursor.itcount(), 'cursor returned by $out should always be empty'); - // NOTE: This relies on the fast-path for .count() with no query being isolated. - // NOTE: There's a bug, SERVER-3645, where .count() is wrong on sharded collections, so - // we - // blacklisted this test for sharded clusters. - assertWhenOwnColl.eq(db[collName].count() / 2, db[otherCollName].count()); - }; + $config.states.query = function query(db, collName) { + // note that all threads output to the same collection + var otherCollName = this.getOutCollName(collName); + var cursor = db[collName].aggregate([{$match: {flag: true}}, {$out: otherCollName}]); + assertAlways.eq(0, cursor.itcount(), 'cursor returned by $out should always be empty'); + // NOTE: This relies on the fast-path for .count() with no query being isolated. + // NOTE: There's a bug, SERVER-3645, where .count() is wrong on sharded collections, so + // we + // blacklisted this test for sharded clusters. + assertWhenOwnColl.eq(db[collName].count() / 2, db[otherCollName].count()); + }; - $config.teardown = function teardown(db, collName, cluster) { - $super.teardown.apply(this, arguments); + $config.teardown = function teardown(db, collName, cluster) { + $super.teardown.apply(this, arguments); - assertWhenOwnColl(db[this.getOutCollName(collName)].drop()); - }; + assertWhenOwnColl(db[this.getOutCollName(collName)].drop()); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/agg_sort.js b/jstests/concurrency/fsm_workloads/agg_sort.js index 936ae2cf71b..8ab372d87f0 100644 --- a/jstests/concurrency/fsm_workloads/agg_sort.js +++ b/jstests/concurrency/fsm_workloads/agg_sort.js @@ -10,30 +10,27 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWo load('jstests/concurrency/fsm_workloads/agg_base.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); // for dropCollections -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.getOutputCollPrefix = function getOutputCollPrefix(collName) { - return collName + '_out_agg_sort_'; - }; + $config.data.getOutputCollPrefix = function getOutputCollPrefix(collName) { + return collName + '_out_agg_sort_'; + }; - $config.states.query = function query(db, collName) { - var otherCollName = this.getOutputCollPrefix(collName) + this.tid; - var cursor = db[collName].aggregate( - [{$match: {flag: true}}, {$sort: {rand: 1}}, {$out: otherCollName}]); - assertAlways.eq(0, cursor.itcount()); - assertWhenOwnColl.eq(db[collName].find().itcount() / 2, - db[otherCollName].find().itcount()); - }; + $config.states.query = function query(db, collName) { + var otherCollName = this.getOutputCollPrefix(collName) + this.tid; + var cursor = db[collName].aggregate( + [{$match: {flag: true}}, {$sort: {rand: 1}}, {$out: otherCollName}]); + assertAlways.eq(0, cursor.itcount()); + assertWhenOwnColl.eq(db[collName].find().itcount() / 2, db[otherCollName].find().itcount()); + }; - $config.teardown = function teardown(db, collName, cluster) { - $super.teardown.apply(this, arguments); + $config.teardown = function teardown(db, collName, cluster) { + $super.teardown.apply(this, arguments); - // drop all collections with this workload's assumed-to-be-unique prefix - // NOTE: assumes the prefix contains no special regex chars - dropCollections(db, new RegExp('^' + this.getOutputCollPrefix(collName))); - }; + // drop all collections with this workload's assumed-to-be-unique prefix + // NOTE: assumes the prefix contains no special regex chars + dropCollections(db, new RegExp('^' + this.getOutputCollPrefix(collName))); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/agg_sort_external.js b/jstests/concurrency/fsm_workloads/agg_sort_external.js index 8a7b6b22495..785d1a4d150 100644 --- a/jstests/concurrency/fsm_workloads/agg_sort_external.js +++ b/jstests/concurrency/fsm_workloads/agg_sort_external.js @@ -12,40 +12,36 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWo load('jstests/concurrency/fsm_workloads/agg_base.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); // for dropCollections -var $config = extendWorkload( - $config, - function($config, $super) { - - // use enough docs to exceed 100MB, the in-memory limit for $sort and $group - $config.data.numDocs = 24 * 1000; - var MB = 1024 * 1024; // bytes - // assert that *half* the docs exceed the in-memory limit, because the $match stage will - // only - // pass half the docs in the collection on to the $sort stage. - assertAlways.lte(100 * MB, $config.data.numDocs * $config.data.docSize / 2); - - $config.data.getOutputCollPrefix = function getOutputCollPrefix(collName) { - return collName + '_out_agg_sort_external_'; - }; - - $config.states.query = function query(db, collName) { - var otherCollName = this.getOutputCollPrefix(collName) + this.tid; - var cursor = - db[collName] - .aggregate([{$match: {flag: true}}, {$sort: {rand: 1}}, {$out: otherCollName}], - {allowDiskUse: true}); - assertAlways.eq(0, cursor.itcount()); - assertWhenOwnColl.eq(db[collName].find().itcount() / 2, - db[otherCollName].find().itcount()); - }; - - $config.teardown = function teardown(db, collName, cluster) { - $super.teardown.apply(this, arguments); - - // drop all collections with this workload's assumed-to-be-unique prefix - // NOTE: assumes the prefix contains no special regex chars - dropCollections(db, new RegExp('^' + this.getOutputCollPrefix(collName))); - }; - - return $config; - }); +var $config = extendWorkload($config, function($config, $super) { + + // use enough docs to exceed 100MB, the in-memory limit for $sort and $group + $config.data.numDocs = 24 * 1000; + var MB = 1024 * 1024; // bytes + // assert that *half* the docs exceed the in-memory limit, because the $match stage will + // only + // pass half the docs in the collection on to the $sort stage. + assertAlways.lte(100 * MB, $config.data.numDocs * $config.data.docSize / 2); + + $config.data.getOutputCollPrefix = function getOutputCollPrefix(collName) { + return collName + '_out_agg_sort_external_'; + }; + + $config.states.query = function query(db, collName) { + var otherCollName = this.getOutputCollPrefix(collName) + this.tid; + var cursor = db[collName].aggregate( + [{$match: {flag: true}}, {$sort: {rand: 1}}, {$out: otherCollName}], + {allowDiskUse: true}); + assertAlways.eq(0, cursor.itcount()); + assertWhenOwnColl.eq(db[collName].find().itcount() / 2, db[otherCollName].find().itcount()); + }; + + $config.teardown = function teardown(db, collName, cluster) { + $super.teardown.apply(this, arguments); + + // drop all collections with this workload's assumed-to-be-unique prefix + // NOTE: assumes the prefix contains no special regex chars + dropCollections(db, new RegExp('^' + this.getOutputCollPrefix(collName))); + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/auth_create_role.js b/jstests/concurrency/fsm_workloads/auth_create_role.js index 8b8d3933c2d..6ad5de17d9a 100644 --- a/jstests/concurrency/fsm_workloads/auth_create_role.js +++ b/jstests/concurrency/fsm_workloads/auth_create_role.js @@ -44,17 +44,11 @@ var $config = (function() { } } - return { - init: init, - createRole: createRole - }; + return {init: init, createRole: createRole}; })(); - var transitions = { - init: {createRole: 1}, - createRole: {createRole: 1} - }; + var transitions = {init: {createRole: 1}, createRole: {createRole: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/auth_create_user.js b/jstests/concurrency/fsm_workloads/auth_create_user.js index e49c63bc68e..07fd1135032 100644 --- a/jstests/concurrency/fsm_workloads/auth_create_user.js +++ b/jstests/concurrency/fsm_workloads/auth_create_user.js @@ -39,17 +39,11 @@ var $config = (function() { } } - return { - init: init, - createUser: createUser - }; + return {init: init, createUser: createUser}; })(); - var transitions = { - init: {createUser: 1}, - createUser: {createUser: 1} - }; + var transitions = {init: {createUser: 1}, createUser: {createUser: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/auth_drop_role.js b/jstests/concurrency/fsm_workloads/auth_drop_role.js index d41066dbc63..eba694ccd49 100644 --- a/jstests/concurrency/fsm_workloads/auth_drop_role.js +++ b/jstests/concurrency/fsm_workloads/auth_drop_role.js @@ -44,24 +44,12 @@ var $config = (function() { assertAlways.isnull(db.getRole(roleName), "role '" + roleName + "' should not exist"); } - return { - init: init, - createAndDropRole: createAndDropRole - }; + return {init: init, createAndDropRole: createAndDropRole}; })(); - var transitions = { - init: {createAndDropRole: 1}, - createAndDropRole: {createAndDropRole: 1} - }; + var transitions = {init: {createAndDropRole: 1}, createAndDropRole: {createAndDropRole: 1}}; - return { - threadCount: 10, - iterations: 20, - data: data, - states: states, - transitions: transitions - }; + return {threadCount: 10, iterations: 20, data: data, states: states, transitions: transitions}; })(); diff --git a/jstests/concurrency/fsm_workloads/auth_drop_user.js b/jstests/concurrency/fsm_workloads/auth_drop_user.js index 65cb8e41da2..a47d5566874 100644 --- a/jstests/concurrency/fsm_workloads/auth_drop_user.js +++ b/jstests/concurrency/fsm_workloads/auth_drop_user.js @@ -37,24 +37,12 @@ var $config = (function() { assertAlways.isnull(db.getUser(username), "user '" + username + "' should not exist"); } - return { - init: init, - createAndDropUser: createAndDropUser - }; + return {init: init, createAndDropUser: createAndDropUser}; })(); - var transitions = { - init: {createAndDropUser: 1}, - createAndDropUser: {createAndDropUser: 1} - }; + var transitions = {init: {createAndDropUser: 1}, createAndDropUser: {createAndDropUser: 1}}; - return { - threadCount: 10, - iterations: 20, - data: data, - states: states, - transitions: transitions - }; + return {threadCount: 10, iterations: 20, data: data, states: states, transitions: transitions}; })(); diff --git a/jstests/concurrency/fsm_workloads/collmod.js b/jstests/concurrency/fsm_workloads/collmod.js index 7b803cd3284..adfe98c2ff1 100644 --- a/jstests/concurrency/fsm_workloads/collmod.js +++ b/jstests/concurrency/fsm_workloads/collmod.js @@ -33,15 +33,11 @@ var $config = (function() { } } - return { - collMod: collMod - }; + return {collMod: collMod}; })(); - var transitions = { - collMod: {collMod: 1} - }; + var transitions = {collMod: {collMod: 1}}; function setup(db, collName, cluster) { // other workloads that extend this one might have set 'this.threadCollName' diff --git a/jstests/concurrency/fsm_workloads/collmod_separate_collections.js b/jstests/concurrency/fsm_workloads/collmod_separate_collections.js index 5233733eb2d..a033eb200ee 100644 --- a/jstests/concurrency/fsm_workloads/collmod_separate_collections.js +++ b/jstests/concurrency/fsm_workloads/collmod_separate_collections.js @@ -13,32 +13,28 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWo load('jstests/concurrency/fsm_workloads/collmod.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); // for dropCollections -var $config = extendWorkload($config, - function($config, $super) { - $config.data.prefix = 'collmod_separate_collections'; - $config.data.shardKey = { - createdAt: 1 - }; +var $config = extendWorkload($config, function($config, $super) { + $config.data.prefix = 'collmod_separate_collections'; + $config.data.shardKey = {createdAt: 1}; - $config.states.init = function init(db, collName) { - this.threadCollName = this.prefix + '_' + this.tid; - $super.setup.call(this, db, this.threadCollName); - }; + $config.states.init = function init(db, collName) { + this.threadCollName = this.prefix + '_' + this.tid; + $super.setup.call(this, db, this.threadCollName); + }; - $config.transitions = - Object.extend({init: {collMod: 1}}, $super.transitions); + $config.transitions = Object.extend({init: {collMod: 1}}, $super.transitions); - $config.setup = function setup(db, collName, cluster) { - // no-op: since the init state is used to setup - // the separate collections on a per-thread basis. - }; + $config.setup = function setup(db, collName, cluster) { + // no-op: since the init state is used to setup + // the separate collections on a per-thread basis. + }; - $config.teardown = function teardown(db, collName, cluster) { - var pattern = new RegExp('^' + this.prefix + '_\\d+$'); - dropCollections(db, pattern); - $super.teardown.apply(this, arguments); - }; + $config.teardown = function teardown(db, collName, cluster) { + var pattern = new RegExp('^' + this.prefix + '_\\d+$'); + dropCollections(db, pattern); + $super.teardown.apply(this, arguments); + }; - $config.startState = 'init'; - return $config; - }); + $config.startState = 'init'; + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/compact.js b/jstests/concurrency/fsm_workloads/compact.js index afea3f8a28f..8f91f52bf5e 100644 --- a/jstests/concurrency/fsm_workloads/compact.js +++ b/jstests/concurrency/fsm_workloads/compact.js @@ -72,12 +72,7 @@ var $config = (function() { assertWhenOwnColl.eq(indexesCount, this.nIndexes); } - return { - init: init, - collectionSetup: collectionSetup, - compact: compact, - query: query - }; + return {init: init, collectionSetup: collectionSetup, compact: compact, query: query}; })(); var transitions = { diff --git a/jstests/concurrency/fsm_workloads/compact_simultaneous_padding_bytes.js b/jstests/concurrency/fsm_workloads/compact_simultaneous_padding_bytes.js index 47ad30cedab..b1991cd3b8c 100644 --- a/jstests/concurrency/fsm_workloads/compact_simultaneous_padding_bytes.js +++ b/jstests/concurrency/fsm_workloads/compact_simultaneous_padding_bytes.js @@ -12,26 +12,24 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extend load('jstests/concurrency/fsm_workloads/compact.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/server_types.js'); // for isEphemeral -var $config = extendWorkload( - $config, - function($config, $super) { - $config.states.init = function init(db, collName) { - this.threadCollName = collName; - }; +var $config = extendWorkload($config, function($config, $super) { + $config.states.init = function init(db, collName) { + this.threadCollName = collName; + }; - $config.states.compact = function compact(db, collName) { - var res = - db.runCommand({compact: this.threadCollName, paddingBytes: 1024 * 5, force: true}); - if (!isEphemeral(db)) { - assertAlways.commandWorked(res); - } else { - assertAlways.commandFailedWithCode(res, ErrorCodes.CommandNotSupported); - } - }; + $config.states.compact = function compact(db, collName) { + var res = + db.runCommand({compact: this.threadCollName, paddingBytes: 1024 * 5, force: true}); + if (!isEphemeral(db)) { + assertAlways.commandWorked(res); + } else { + assertAlways.commandFailedWithCode(res, ErrorCodes.CommandNotSupported); + } + }; - // no-op the query state because querying while compacting can result in closed cursors - // as per SERVER-3964, as well as inaccurate counts, leaving nothing to assert. - $config.states.query = function query(db, collName) {}; + // no-op the query state because querying while compacting can result in closed cursors + // as per SERVER-3964, as well as inaccurate counts, leaving nothing to assert. + $config.states.query = function query(db, collName) {}; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/convert_to_capped_collection.js b/jstests/concurrency/fsm_workloads/convert_to_capped_collection.js index 79b9934077b..14cd4e98646 100644 --- a/jstests/concurrency/fsm_workloads/convert_to_capped_collection.js +++ b/jstests/concurrency/fsm_workloads/convert_to_capped_collection.js @@ -13,9 +13,7 @@ load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); var $config = (function() { // TODO: This workload may fail if an iteration multiplier is specified. - var data = { - prefix: 'convert_to_capped_collection' - }; + var data = {prefix: 'convert_to_capped_collection'}; var states = (function() { @@ -62,16 +60,10 @@ var $config = (function() { }); } - return { - init: init, - convertToCapped: convertToCapped - }; + return {init: init, convertToCapped: convertToCapped}; })(); - var transitions = { - init: {convertToCapped: 1}, - convertToCapped: {convertToCapped: 1} - }; + var transitions = {init: {convertToCapped: 1}, convertToCapped: {convertToCapped: 1}}; function setup(db, collName, cluster) { // Initial size should not be a power of 256. diff --git a/jstests/concurrency/fsm_workloads/convert_to_capped_collection_index.js b/jstests/concurrency/fsm_workloads/convert_to_capped_collection_index.js index 01342b9b603..4b410ea7305 100644 --- a/jstests/concurrency/fsm_workloads/convert_to_capped_collection_index.js +++ b/jstests/concurrency/fsm_workloads/convert_to_capped_collection_index.js @@ -16,14 +16,12 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/convert_to_capped_collection.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { - $config.states.convertToCapped = function convertToCapped(db, collName) { - assertWhenOwnDB.commandWorked(db[this.threadCollName].ensureIndex({i: 1, rand: 1})); - assertWhenOwnDB.eq(2, db[this.threadCollName].getIndexes().length); - $super.states.convertToCapped.apply(this, arguments); - }; +var $config = extendWorkload($config, function($config, $super) { + $config.states.convertToCapped = function convertToCapped(db, collName) { + assertWhenOwnDB.commandWorked(db[this.threadCollName].ensureIndex({i: 1, rand: 1})); + assertWhenOwnDB.eq(2, db[this.threadCollName].getIndexes().length); + $super.states.convertToCapped.apply(this, arguments); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/count.js b/jstests/concurrency/fsm_workloads/count.js index 61a4c93d3ab..16221b7ad9d 100644 --- a/jstests/concurrency/fsm_workloads/count.js +++ b/jstests/concurrency/fsm_workloads/count.js @@ -53,24 +53,12 @@ var $config = (function() { assertWhenOwnColl.eq(this.getCount(db, {i: num}), this.countPerNum); } - return { - init: init, - count: count - }; + return {init: init, count: count}; })(); - var transitions = { - init: {count: 1}, - count: {count: 1} - }; + var transitions = {init: {count: 1}, count: {count: 1}}; - return { - data: data, - threadCount: 10, - iterations: 20, - states: states, - transitions: transitions - }; + return {data: data, threadCount: 10, iterations: 20, states: states, transitions: transitions}; })(); diff --git a/jstests/concurrency/fsm_workloads/count_indexed.js b/jstests/concurrency/fsm_workloads/count_indexed.js index b9c09020042..77edf8da6ef 100644 --- a/jstests/concurrency/fsm_workloads/count_indexed.js +++ b/jstests/concurrency/fsm_workloads/count_indexed.js @@ -14,31 +14,26 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWo load('jstests/concurrency/fsm_workloads/count.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); // for dropCollections -var $config = extendWorkload( - $config, - function($config, $super) { - $config.data.prefix = 'count_fsm'; - $config.data.shardKey = { - tid: 1, - i: 1 - }; +var $config = extendWorkload($config, function($config, $super) { + $config.data.prefix = 'count_fsm'; + $config.data.shardKey = {tid: 1, i: 1}; - $config.data.getCount = function getCount(db, predicate) { - var query = Object.extend({tid: this.tid}, predicate); - return db[this.threadCollName].find(query).hint({tid: 1, i: 1}).count(); - }; + $config.data.getCount = function getCount(db, predicate) { + var query = Object.extend({tid: this.tid}, predicate); + return db[this.threadCollName].find(query).hint({tid: 1, i: 1}).count(); + }; - $config.states.init = function init(db, collName) { - this.threadCollName = this.prefix + '_' + this.tid; - $super.states.init.apply(this, arguments); - assertAlways.commandWorked(db[this.threadCollName].ensureIndex({tid: 1, i: 1})); - }; + $config.states.init = function init(db, collName) { + this.threadCollName = this.prefix + '_' + this.tid; + $super.states.init.apply(this, arguments); + assertAlways.commandWorked(db[this.threadCollName].ensureIndex({tid: 1, i: 1})); + }; - $config.teardown = function teardown(db, collName) { - var pattern = new RegExp('^' + this.prefix + '_\\d+$'); - dropCollections(db, pattern); - $super.teardown.apply(this, arguments); - }; + $config.teardown = function teardown(db, collName) { + var pattern = new RegExp('^' + this.prefix + '_\\d+$'); + dropCollections(db, pattern); + $super.teardown.apply(this, arguments); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/count_limit_skip.js b/jstests/concurrency/fsm_workloads/count_limit_skip.js index 59cc5db835f..169094a1c82 100644 --- a/jstests/concurrency/fsm_workloads/count_limit_skip.js +++ b/jstests/concurrency/fsm_workloads/count_limit_skip.js @@ -14,42 +14,36 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWo load('jstests/concurrency/fsm_workloads/count.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); // for dropCollections -var $config = extendWorkload( - $config, - function($config, $super) { - $config.data.prefix = 'count_fsm_q_l_s'; - - $config.data.getCount = function getCount(db, predicate) { - var query = Object.extend({tid: this.tid}, predicate); - return db[this.threadCollName] - .find(query) - .skip(this.countPerNum - 1) - .limit(10) - .count(true); - }; - - $config.states.init = function init(db, collName) { - this.threadCollName = this.prefix + '_' + this.tid; - - $super.states.init.apply(this, arguments); - }; - - $config.states.count = function count(db, collName) { - assertWhenOwnColl.eq(this.getCount(db), - // having done 'skip(this.countPerNum - 1).limit(10)' - 10); - - var num = Random.randInt(this.modulus); - assertWhenOwnColl.eq(this.getCount(db, {i: num}), - // having done 'skip(this.countPerNum - 1).limit(10)' - 1); - }; - - $config.teardown = function teardown(db, collName) { - var pattern = new RegExp('^' + this.prefix + '_\\d+$'); - dropCollections(db, pattern); - $super.teardown.apply(this, arguments); - }; - - return $config; - }); +var $config = extendWorkload($config, function($config, $super) { + $config.data.prefix = 'count_fsm_q_l_s'; + + $config.data.getCount = function getCount(db, predicate) { + var query = Object.extend({tid: this.tid}, predicate); + return db[this.threadCollName].find(query).skip(this.countPerNum - 1).limit(10).count(true); + }; + + $config.states.init = function init(db, collName) { + this.threadCollName = this.prefix + '_' + this.tid; + + $super.states.init.apply(this, arguments); + }; + + $config.states.count = function count(db, collName) { + assertWhenOwnColl.eq(this.getCount(db), + // having done 'skip(this.countPerNum - 1).limit(10)' + 10); + + var num = Random.randInt(this.modulus); + assertWhenOwnColl.eq(this.getCount(db, {i: num}), + // having done 'skip(this.countPerNum - 1).limit(10)' + 1); + }; + + $config.teardown = function teardown(db, collName) { + var pattern = new RegExp('^' + this.prefix + '_\\d+$'); + dropCollections(db, pattern); + $super.teardown.apply(this, arguments); + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/create_capped_collection.js b/jstests/concurrency/fsm_workloads/create_capped_collection.js index 96fdda8ebda..c0ec6c0e071 100644 --- a/jstests/concurrency/fsm_workloads/create_capped_collection.js +++ b/jstests/concurrency/fsm_workloads/create_capped_collection.js @@ -14,10 +14,7 @@ var $config = (function() { // Returns a document of the form { _id: ObjectId(...), field: '...' } // with specified BSON size. function makeDocWithSize(targetSize) { - var doc = { - _id: new ObjectId(), - field: '' - }; + var doc = {_id: new ObjectId(), field: ''}; var size = Object.bsonsize(doc); assertAlways.gte(targetSize, size); @@ -45,11 +42,9 @@ var $config = (function() { // Returns an array containing the _id fields of all the documents // in the collection, sorted according to their insertion order. function getObjectIds(db, collName) { - return db[collName] - .find({}, {_id: 1}) - .map(function(doc) { - return doc._id; - }); + return db[collName].find({}, {_id: 1}).map(function(doc) { + return doc._id; + }); } var data = { @@ -148,17 +143,11 @@ var $config = (function() { this.verifySizeTruncation(db, myCollName, options); } - return { - init: init, - create: create - }; + return {init: init, create: create}; })(); - var transitions = { - init: {create: 1}, - create: {create: 1} - }; + var transitions = {init: {create: 1}, create: {create: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/create_capped_collection_maxdocs.js b/jstests/concurrency/fsm_workloads/create_capped_collection_maxdocs.js index b3a836b8b0b..e29ed65a274 100644 --- a/jstests/concurrency/fsm_workloads/create_capped_collection_maxdocs.js +++ b/jstests/concurrency/fsm_workloads/create_capped_collection_maxdocs.js @@ -10,57 +10,55 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/create_capped_collection.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - // Use the workload name as a prefix for the collection name, - // since the workload name is assumed to be unique. - $config.data.prefix = 'create_capped_collection_maxdocs'; + // Use the workload name as a prefix for the collection name, + // since the workload name is assumed to be unique. + $config.data.prefix = 'create_capped_collection_maxdocs'; - var options = { - capped: true, - size: 8192, // multiple of 256; larger than 4096 default - max: 3 - }; + var options = { + capped: true, + size: 8192, // multiple of 256; larger than 4096 default + max: 3 + }; - function uniqueCollectionName(prefix, tid, num) { - return prefix + tid + '_' + num; - } + function uniqueCollectionName(prefix, tid, num) { + return prefix + tid + '_' + num; + } - // TODO: how to avoid having too many files open? - function create(db, collName) { - var myCollName = uniqueCollectionName(this.prefix, this.tid, this.num++); - assertAlways.commandWorked(db.createCollection(myCollName, options)); + // TODO: how to avoid having too many files open? + function create(db, collName) { + var myCollName = uniqueCollectionName(this.prefix, this.tid, this.num++); + assertAlways.commandWorked(db.createCollection(myCollName, options)); - // Define a small document to be an eighth the size of the capped collection. - var smallDocSize = Math.floor(options.size / 8) - 1; + // Define a small document to be an eighth the size of the capped collection. + var smallDocSize = Math.floor(options.size / 8) - 1; - // Verify size functionality still works as we expect - this.verifySizeTruncation(db, myCollName, options); + // Verify size functionality still works as we expect + this.verifySizeTruncation(db, myCollName, options); - // Insert multiple small documents and verify that at least one truncation has occurred. - // There should never be more than 3 documents in the collection, regardless of the - // storage - // engine. They should always be the most recently inserted documents. + // Insert multiple small documents and verify that at least one truncation has occurred. + // There should never be more than 3 documents in the collection, regardless of the + // storage + // engine. They should always be the most recently inserted documents. - var ids = []; - var count; + var ids = []; + var count; - ids.push(this.insert(db, myCollName, smallDocSize)); - ids.push(this.insert(db, myCollName, smallDocSize)); + ids.push(this.insert(db, myCollName, smallDocSize)); + ids.push(this.insert(db, myCollName, smallDocSize)); - for (var i = 0; i < 50; i++) { - ids.push(this.insert(db, myCollName, smallDocSize)); - count = db[myCollName].find().itcount(); - assertWhenOwnDB.eq(3, count, 'expected truncation to occur due to number of docs'); - assertWhenOwnDB.eq(ids.slice(ids.length - count), - this.getObjectIds(db, myCollName), - 'expected truncation to remove the oldest documents'); - } + for (var i = 0; i < 50; i++) { + ids.push(this.insert(db, myCollName, smallDocSize)); + count = db[myCollName].find().itcount(); + assertWhenOwnDB.eq(3, count, 'expected truncation to occur due to number of docs'); + assertWhenOwnDB.eq(ids.slice(ids.length - count), + this.getObjectIds(db, myCollName), + 'expected truncation to remove the oldest documents'); } + } - $config.states.create = create; + $config.states.create = create; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/create_collection.js b/jstests/concurrency/fsm_workloads/create_collection.js index fdc6d8af9fd..023c6811f1f 100644 --- a/jstests/concurrency/fsm_workloads/create_collection.js +++ b/jstests/concurrency/fsm_workloads/create_collection.js @@ -32,17 +32,11 @@ var $config = (function() { assertAlways.commandWorked(db.createCollection(myCollName)); } - return { - init: init, - create: create - }; + return {init: init, create: create}; })(); - var transitions = { - init: {create: 1}, - create: {create: 1} - }; + var transitions = {init: {create: 1}, create: {create: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/create_index_background.js b/jstests/concurrency/fsm_workloads/create_index_background.js index 046709ebdd3..cfc47156407 100644 --- a/jstests/concurrency/fsm_workloads/create_index_background.js +++ b/jstests/concurrency/fsm_workloads/create_index_background.js @@ -105,8 +105,8 @@ var $config = (function() { for (var i = 0; i < this.nDocumentsToUpdate; ++i) { // Do randomized updates on index x. A document is not guaranteed // to match the randomized 'x' predicate. - res = coll.update({x: Random.randInt(highest), tid: this.tid}, - {$inc: {crud: 1}}); + res = + coll.update({x: Random.randInt(highest), tid: this.tid}, {$inc: {crud: 1}}); assertAlways.writeOK(res); if (db.getMongo().writeMode() === 'commands') { assertWhenOwnColl.contains(res.nModified, [0, 1], tojson(res)); @@ -207,10 +207,8 @@ var $config = (function() { setParameter: 1, internalQueryExecYieldIterations: internalQueryExecYieldIterations })); - assertAlways.commandWorked(db.adminCommand({ - setParameter: 1, - internalQueryExecYieldPeriodMS: internalQueryExecYieldPeriodMS - })); + assertAlways.commandWorked(db.adminCommand( + {setParameter: 1, internalQueryExecYieldPeriodMS: internalQueryExecYieldPeriodMS})); }); } diff --git a/jstests/concurrency/fsm_workloads/distinct.js b/jstests/concurrency/fsm_workloads/distinct.js index c76b5e972f5..c2f519551ce 100644 --- a/jstests/concurrency/fsm_workloads/distinct.js +++ b/jstests/concurrency/fsm_workloads/distinct.js @@ -11,11 +11,7 @@ load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); // for dropColl var $config = (function() { - var data = { - numDocs: 1000, - prefix: 'distinct_fsm', - shardKey: {i: 1} - }; + var data = {numDocs: 1000, prefix: 'distinct_fsm', shardKey: {i: 1}}; var states = (function() { @@ -35,17 +31,11 @@ var $config = (function() { assertWhenOwnColl.eq(this.numDocs, db[this.threadCollName].distinct('i').length); } - return { - init: init, - distinct: distinct - }; + return {init: init, distinct: distinct}; })(); - var transitions = { - init: {distinct: 1}, - distinct: {distinct: 1} - }; + var transitions = {init: {distinct: 1}, distinct: {distinct: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + this.prefix + '_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/distinct_noindex.js b/jstests/concurrency/fsm_workloads/distinct_noindex.js index b55d1e58d3b..3727c968a14 100644 --- a/jstests/concurrency/fsm_workloads/distinct_noindex.js +++ b/jstests/concurrency/fsm_workloads/distinct_noindex.js @@ -35,24 +35,12 @@ var $config = (function() { assertWhenOwnColl.eq(this.modulus, db[collName].distinct('i', {tid: this.tid}).length); } - return { - init: init, - distinct: distinct - }; + return {init: init, distinct: distinct}; })(); - var transitions = { - init: {distinct: 1}, - distinct: {distinct: 1} - }; + var transitions = {init: {distinct: 1}, distinct: {distinct: 1}}; - return { - data: data, - threadCount: 10, - iterations: 20, - states: states, - transitions: transitions - }; + return {data: data, threadCount: 10, iterations: 20, states: states, transitions: transitions}; })(); diff --git a/jstests/concurrency/fsm_workloads/distinct_projection.js b/jstests/concurrency/fsm_workloads/distinct_projection.js index 3f9c4c3192d..cf287cdb210 100644 --- a/jstests/concurrency/fsm_workloads/distinct_projection.js +++ b/jstests/concurrency/fsm_workloads/distinct_projection.js @@ -10,18 +10,13 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/distinct.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { - $config.data.prefix = 'distinct_projection_fsm'; +var $config = extendWorkload($config, function($config, $super) { + $config.data.prefix = 'distinct_projection_fsm'; - $config.states.distinct = function distinct(db, collName) { - var query = { - i: {$lt: this.numDocs / 2} - }; - assertWhenOwnColl.eq( - this.numDocs / 2, - db[this.threadCollName].distinct('i', query).length); - }; + $config.states.distinct = function distinct(db, collName) { + var query = {i: {$lt: this.numDocs / 2}}; + assertWhenOwnColl.eq(this.numDocs / 2, db[this.threadCollName].distinct('i', query).length); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/drop_collection.js b/jstests/concurrency/fsm_workloads/drop_collection.js index 64a60ef8e79..89952c0a48e 100644 --- a/jstests/concurrency/fsm_workloads/drop_collection.js +++ b/jstests/concurrency/fsm_workloads/drop_collection.js @@ -30,24 +30,12 @@ var $config = (function() { assertAlways(db[myCollName].drop()); } - return { - init: init, - createAndDrop: createAndDrop - }; + return {init: init, createAndDrop: createAndDrop}; })(); - var transitions = { - init: {createAndDrop: 1}, - createAndDrop: {createAndDrop: 1} - }; + var transitions = {init: {createAndDrop: 1}, createAndDrop: {createAndDrop: 1}}; - return { - threadCount: 10, - iterations: 10, - data: data, - states: states, - transitions: transitions - }; + return {threadCount: 10, iterations: 10, data: data, states: states, transitions: transitions}; })(); diff --git a/jstests/concurrency/fsm_workloads/drop_database.js b/jstests/concurrency/fsm_workloads/drop_database.js index 9a6b9e0fb80..9d372d354f8 100644 --- a/jstests/concurrency/fsm_workloads/drop_database.js +++ b/jstests/concurrency/fsm_workloads/drop_database.js @@ -24,10 +24,7 @@ var $config = (function() { } }; - var transitions = { - init: {createAndDrop: 1}, - createAndDrop: {createAndDrop: 1} - }; + var transitions = {init: {createAndDrop: 1}, createAndDrop: {createAndDrop: 1}}; return { threadCount: 10, diff --git a/jstests/concurrency/fsm_workloads/explain.js b/jstests/concurrency/fsm_workloads/explain.js index 983218a7fbf..89dfa530d76 100644 --- a/jstests/concurrency/fsm_workloads/explain.js +++ b/jstests/concurrency/fsm_workloads/explain.js @@ -61,11 +61,7 @@ var $config = (function() { } } - return { - insert: insert, - explain: explain, - explainNonExistentNS: explainNonExistentNS - }; + return {insert: insert, explain: explain, explainNonExistentNS: explainNonExistentNS}; })(); diff --git a/jstests/concurrency/fsm_workloads/explain_aggregate.js b/jstests/concurrency/fsm_workloads/explain_aggregate.js index e0bbccb7683..883ab11c06e 100644 --- a/jstests/concurrency/fsm_workloads/explain_aggregate.js +++ b/jstests/concurrency/fsm_workloads/explain_aggregate.js @@ -9,43 +9,37 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/explain.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { - - function assertCursorStages(num, obj) { - assertAlways(obj.stages, tojson(obj)); - assertAlways.eq(num, obj.stages.length, tojson(obj.stages)); - assertAlways(obj.stages[0].$cursor, tojson(obj.stages[0])); - assertAlways(obj.stages[0].$cursor.hasOwnProperty('queryPlanner'), - tojson(obj.stages[0].$cursor)); +var $config = extendWorkload($config, function($config, $super) { + + function assertCursorStages(num, obj) { + assertAlways(obj.stages, tojson(obj)); + assertAlways.eq(num, obj.stages.length, tojson(obj.stages)); + assertAlways(obj.stages[0].$cursor, tojson(obj.stages[0])); + assertAlways(obj.stages[0].$cursor.hasOwnProperty('queryPlanner'), + tojson(obj.stages[0].$cursor)); + } + + $config.states = Object.extend({ + explainMatch: function explainMatch(db, collName) { + var res = db[collName].explain().aggregate([{$match: {i: this.nInserted / 2}}]); + assertAlways.commandWorked(res); + + // stages reported: $cursor + assertCursorStages(1, res); + }, + explainMatchProject: function explainMatchProject(db, collName) { + var res = db[collName].explain().aggregate( + [{$match: {i: this.nInserted / 3}}, {$project: {i: 1}}]); + assertAlways.commandWorked(res); + + // stages reported: $cursor, $project + assertCursorStages(2, res); } + }, + $super.states); - $config.states = Object.extend( - { - explainMatch: function explainMatch(db, collName) { - var res = db[collName].explain().aggregate([{$match: {i: this.nInserted / 2}}]); - assertAlways.commandWorked(res); - - // stages reported: $cursor - assertCursorStages(1, res); - }, - explainMatchProject: function explainMatchProject(db, collName) { - var res = - db[collName] - .explain() - .aggregate([{$match: {i: this.nInserted / 3}}, {$project: {i: 1}}]); - assertAlways.commandWorked(res); - - // stages reported: $cursor, $project - assertCursorStages(2, res); - } - }, - $super.states); - - $config.transitions = - Object.extend({explain: $config.data.assignEqualProbsToTransitions($config.states)}, - $super.transitions); - - return $config; - }); + $config.transitions = Object.extend( + {explain: $config.data.assignEqualProbsToTransitions($config.states)}, $super.transitions); + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/explain_count.js b/jstests/concurrency/fsm_workloads/explain_count.js index b6a9f0fa8b8..948a108ca10 100644 --- a/jstests/concurrency/fsm_workloads/explain_count.js +++ b/jstests/concurrency/fsm_workloads/explain_count.js @@ -10,59 +10,54 @@ load('jstests/concurrency/fsm_workloads/explain.js'); // for $confi load('jstests/concurrency/fsm_workload_helpers/server_types.js'); // for isMongos load('jstests/libs/analyze_plan.js'); // for planHasStage -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - function assertNCounted(num, obj, db) { - var stage = obj.executionStats.executionStages; - // get sharded stage(s) if counting on mongos - if (isMongos(db)) { - stage = stage.shards[0].executionStages; - } - assertWhenOwnColl.eq(num, stage.nCounted); + function assertNCounted(num, obj, db) { + var stage = obj.executionStats.executionStages; + // get sharded stage(s) if counting on mongos + if (isMongos(db)) { + stage = stage.shards[0].executionStages; } + assertWhenOwnColl.eq(num, stage.nCounted); + } - $config.states = Object.extend( - { - explainBasicCount: function explainBasicCount(db, collName) { - var res = db[collName].explain().count(); - assertAlways.commandWorked(res); - assertAlways(planHasStage(res.queryPlanner.winningPlan, 'COUNT')); - }, - explainCountHint: function explainCountHint(db, collName) { - assertWhenOwnColl(function() { - var res = - db[collName].explain().find({i: this.nInserted / 2}).hint({i: 1}).count(); - assertWhenOwnColl.commandWorked(res); - assertWhenOwnColl(planHasStage(res.queryPlanner.winningPlan, 'COUNT')); - assertWhenOwnColl(planHasStage(res.queryPlanner.winningPlan, 'COUNT_SCAN')); - }); - }, - explainCountNoSkipLimit: function explainCountNoSkipLimit(db, collName) { - var res = db[collName] - .explain('executionStats') - .find({i: this.nInserted}) - .skip(1) - .count(false); - assertAlways.commandWorked(res); - assertNCounted(1, res, db); - }, - explainCountSkipLimit: function explainCountSkipLimit(db, collName) { - var res = db[collName] - .explain('executionStats') - .find({i: this.nInserted}) - .skip(1) - .count(true); - assertAlways.commandWorked(res); - assertNCounted(0, res, db); - } - }, - $super.states); + $config.states = Object.extend({ + explainBasicCount: function explainBasicCount(db, collName) { + var res = db[collName].explain().count(); + assertAlways.commandWorked(res); + assertAlways(planHasStage(res.queryPlanner.winningPlan, 'COUNT')); + }, + explainCountHint: function explainCountHint(db, collName) { + assertWhenOwnColl(function() { + var res = db[collName].explain().find({i: this.nInserted / 2}).hint({i: 1}).count(); + assertWhenOwnColl.commandWorked(res); + assertWhenOwnColl(planHasStage(res.queryPlanner.winningPlan, 'COUNT')); + assertWhenOwnColl(planHasStage(res.queryPlanner.winningPlan, 'COUNT_SCAN')); + }); + }, + explainCountNoSkipLimit: function explainCountNoSkipLimit(db, collName) { + var res = db[collName] + .explain('executionStats') + .find({i: this.nInserted}) + .skip(1) + .count(false); + assertAlways.commandWorked(res); + assertNCounted(1, res, db); + }, + explainCountSkipLimit: function explainCountSkipLimit(db, collName) { + var res = db[collName] + .explain('executionStats') + .find({i: this.nInserted}) + .skip(1) + .count(true); + assertAlways.commandWorked(res); + assertNCounted(0, res, db); + } + }, + $super.states); - $config.transitions = - Object.extend({explain: $config.data.assignEqualProbsToTransitions($config.states)}, - $super.transitions); + $config.transitions = Object.extend( + {explain: $config.data.assignEqualProbsToTransitions($config.states)}, $super.transitions); - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/explain_distinct.js b/jstests/concurrency/fsm_workloads/explain_distinct.js index 86c30f3aca9..1c14254daed 100644 --- a/jstests/concurrency/fsm_workloads/explain_distinct.js +++ b/jstests/concurrency/fsm_workloads/explain_distinct.js @@ -9,28 +9,24 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/explain.js'); // for $config load('jstests/libs/analyze_plan.js'); // for planHasStage -var $config = extendWorkload( - $config, - function($config, $super) { - $config.states = Object.extend( - { - explainBasicDistinct: function(db, collName) { - var res = db[collName].explain().distinct('i'); - assertAlways.commandWorked(res); - assertAlways(planHasStage(res.queryPlanner.winningPlan, 'COLLSCAN')); - }, - explainDistinctIndex: function(db, collName) { - var res = db[collName].explain().distinct('_id'); - assertAlways.commandWorked(res); - assertAlways(planHasStage(res.queryPlanner.winningPlan, 'PROJECTION')); - assertAlways(planHasStage(res.queryPlanner.winningPlan, 'DISTINCT_SCAN')); - } - }, - $super.states); +var $config = extendWorkload($config, function($config, $super) { + $config.states = Object.extend({ + explainBasicDistinct: function(db, collName) { + var res = db[collName].explain().distinct('i'); + assertAlways.commandWorked(res); + assertAlways(planHasStage(res.queryPlanner.winningPlan, 'COLLSCAN')); + }, + explainDistinctIndex: function(db, collName) { + var res = db[collName].explain().distinct('_id'); + assertAlways.commandWorked(res); + assertAlways(planHasStage(res.queryPlanner.winningPlan, 'PROJECTION')); + assertAlways(planHasStage(res.queryPlanner.winningPlan, 'DISTINCT_SCAN')); + } + }, + $super.states); - $config.transitions = - Object.extend({explain: $config.data.assignEqualProbsToTransitions($config.states)}, - $super.transitions); + $config.transitions = Object.extend( + {explain: $config.data.assignEqualProbsToTransitions($config.states)}, $super.transitions); - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/explain_find.js b/jstests/concurrency/fsm_workloads/explain_find.js index f0b6f099c63..e338b00e516 100644 --- a/jstests/concurrency/fsm_workloads/explain_find.js +++ b/jstests/concurrency/fsm_workloads/explain_find.js @@ -10,62 +10,57 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/explain.js'); // for $config load('jstests/libs/analyze_plan.js'); // for planHasStage and isIxscan -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.states = Object.extend( - { - explainLimit: function explainLimit(db, collName) { - var res = db[collName].find().limit(3).explain(); - assertAlways.commandWorked(res); - assertAlways(planHasStage(res.queryPlanner.winningPlan, 'LIMIT')); - }, - explainBatchSize: function explainBatchSize(db, collName) { - var res = db[collName].find().batchSize(3).explain(); - assertAlways.commandWorked(res); - }, - explainAddOption: function explainAddOption(db, collName) { - var res = - db[collName].explain().find().addOption(DBQuery.Option.exhaust).finish(); - assertAlways.commandWorked(res); - }, - explainSkip: function explainSkip(db, collName) { - var res = db[collName].explain().find().skip(3).finish(); - assertAlways.commandWorked(res); - assertAlways(planHasStage(res.queryPlanner.winningPlan, 'SKIP')); - }, - explainSort: function explainSort(db, collName) { - var res = db[collName].find().sort({i: -1}).explain(); - assertAlways.commandWorked(res); - assertAlways(planHasStage(res.queryPlanner.winningPlan, 'SORT')); - }, - explainHint: function explainHint(db, collName) { - assertWhenOwnColl(function() { - var res = db[collName].find().hint({j: 1}).explain(); - assertWhenOwnColl.commandWorked(res); - assertWhenOwnColl(isIxscan(res.queryPlanner.winningPlan)); - }); - }, - explainMaxTimeMS: function explainMaxTimeMS(db, collName) { - var res = db[collName].find().maxTimeMS(2000).explain(); - assertAlways.commandWorked(res); - }, - explainSnapshot: function explainSnapshot(db, collName) { - var res = db[collName].find().snapshot().explain(); - assertAlways.commandWorked(res); - assertWhenOwnColl(isIxscan(res.queryPlanner.winningPlan)); - } - }, - $super.states); + $config.states = Object.extend({ + explainLimit: function explainLimit(db, collName) { + var res = db[collName].find().limit(3).explain(); + assertAlways.commandWorked(res); + assertAlways(planHasStage(res.queryPlanner.winningPlan, 'LIMIT')); + }, + explainBatchSize: function explainBatchSize(db, collName) { + var res = db[collName].find().batchSize(3).explain(); + assertAlways.commandWorked(res); + }, + explainAddOption: function explainAddOption(db, collName) { + var res = db[collName].explain().find().addOption(DBQuery.Option.exhaust).finish(); + assertAlways.commandWorked(res); + }, + explainSkip: function explainSkip(db, collName) { + var res = db[collName].explain().find().skip(3).finish(); + assertAlways.commandWorked(res); + assertAlways(planHasStage(res.queryPlanner.winningPlan, 'SKIP')); + }, + explainSort: function explainSort(db, collName) { + var res = db[collName].find().sort({i: -1}).explain(); + assertAlways.commandWorked(res); + assertAlways(planHasStage(res.queryPlanner.winningPlan, 'SORT')); + }, + explainHint: function explainHint(db, collName) { + assertWhenOwnColl(function() { + var res = db[collName].find().hint({j: 1}).explain(); + assertWhenOwnColl.commandWorked(res); + assertWhenOwnColl(isIxscan(res.queryPlanner.winningPlan)); + }); + }, + explainMaxTimeMS: function explainMaxTimeMS(db, collName) { + var res = db[collName].find().maxTimeMS(2000).explain(); + assertAlways.commandWorked(res); + }, + explainSnapshot: function explainSnapshot(db, collName) { + var res = db[collName].find().snapshot().explain(); + assertAlways.commandWorked(res); + assertWhenOwnColl(isIxscan(res.queryPlanner.winningPlan)); + } + }, + $super.states); - $config.transitions = - Object.extend({explain: $config.data.assignEqualProbsToTransitions($config.states)}, - $super.transitions); + $config.transitions = Object.extend( + {explain: $config.data.assignEqualProbsToTransitions($config.states)}, $super.transitions); - // doubling number of iterations so there is a higher chance we will - // transition to each of the 8 new states at least once - $config.iterations = $super.iterations * 2; + // doubling number of iterations so there is a higher chance we will + // transition to each of the 8 new states at least once + $config.iterations = $super.iterations * 2; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/explain_group.js b/jstests/concurrency/fsm_workloads/explain_group.js index f379bf4e608..99e0a0c1266 100644 --- a/jstests/concurrency/fsm_workloads/explain_group.js +++ b/jstests/concurrency/fsm_workloads/explain_group.js @@ -10,23 +10,19 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/explain.js'); // for $config load('jstests/libs/analyze_plan.js'); // for planHasStage -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.states = Object.extend( - { - explainBasicGroup: function explainBasicGroup(db, collName) { - var res = db[collName].explain().group( - {key: {i: 1}, initial: {}, reduce: function() {}}); - assertAlways.commandWorked(res); - } - }, - $super.states); + $config.states = Object.extend({ + explainBasicGroup: function explainBasicGroup(db, collName) { + var res = + db[collName].explain().group({key: {i: 1}, initial: {}, reduce: function() {}}); + assertAlways.commandWorked(res); + } + }, + $super.states); - $config.transitions = Object.extend( - {explain: $config.data.assignEqualProbsToTransitions($config.states)}, - $super.transitions); + $config.transitions = Object.extend( + {explain: $config.data.assignEqualProbsToTransitions($config.states)}, $super.transitions); - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/explain_remove.js b/jstests/concurrency/fsm_workloads/explain_remove.js index c5c05a9af69..173f9b44623 100644 --- a/jstests/concurrency/fsm_workloads/explain_remove.js +++ b/jstests/concurrency/fsm_workloads/explain_remove.js @@ -8,42 +8,37 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/explain.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.states = Object.extend( - { - explainSingleRemove: function explainSingleRemove(db, collName) { - var res = db[collName] - .explain('executionStats') - .remove({i: this.nInserted}, /* justOne */ true); - assertAlways.commandWorked(res); - assertWhenOwnColl(function() { - assertWhenOwnColl.eq(1, res.executionStats.totalDocsExamined); + $config.states = Object.extend({ + explainSingleRemove: function explainSingleRemove(db, collName) { + var res = db[collName] + .explain('executionStats') + .remove({i: this.nInserted}, /* justOne */ true); + assertAlways.commandWorked(res); + assertWhenOwnColl(function() { + assertWhenOwnColl.eq(1, res.executionStats.totalDocsExamined); - // the document should not have been deleted. - assertWhenOwnColl.eq(1, db[collName].find({i: this.nInserted}).itcount()); - }.bind(this)); - }, - explainMultiRemove: function explainMultiRemove(db, collName) { - var res = db[collName] - .explain('executionStats') - .remove({i: {$lte: this.nInserted / 2}}); - assertAlways.commandWorked(res); - assertWhenOwnColl(function() { - assertWhenOwnColl.eq(this.nInserted / 2 + 1, - explain.executionStats.totalDocsExamined); - // no documents should have been deleted - assertWhenOwnColl.eq(this.nInserted, db[collName].itcount()); - }.bind(this)); - } - }, - $super.states); + // the document should not have been deleted. + assertWhenOwnColl.eq(1, db[collName].find({i: this.nInserted}).itcount()); + }.bind(this)); + }, + explainMultiRemove: function explainMultiRemove(db, collName) { + var res = + db[collName].explain('executionStats').remove({i: {$lte: this.nInserted / 2}}); + assertAlways.commandWorked(res); + assertWhenOwnColl(function() { + assertWhenOwnColl.eq(this.nInserted / 2 + 1, + explain.executionStats.totalDocsExamined); + // no documents should have been deleted + assertWhenOwnColl.eq(this.nInserted, db[collName].itcount()); + }.bind(this)); + } + }, + $super.states); - $config.transitions = - Object.extend({explain: $config.data.assignEqualProbsToTransitions($config.states)}, - $super.transitions); + $config.transitions = Object.extend( + {explain: $config.data.assignEqualProbsToTransitions($config.states)}, $super.transitions); - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/explain_update.js b/jstests/concurrency/fsm_workloads/explain_update.js index e63f5948fef..787ccdf7e4b 100644 --- a/jstests/concurrency/fsm_workloads/explain_update.js +++ b/jstests/concurrency/fsm_workloads/explain_update.js @@ -9,69 +9,64 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extend load('jstests/concurrency/fsm_workloads/explain.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/server_types.js'); // for isMongos -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.states = Object.extend( - { - explainBasicUpdate: function explainBasicUpdate(db, collName) { - var res = db[collName] - .explain('executionStats') - .update({i: this.nInserted}, {$set: {j: 49}}); - assertAlways.commandWorked(res); - assertWhenOwnColl(function() { - assertWhenOwnColl.eq(1, explain.executionStats.totalDocsExamined); + $config.states = Object.extend({ + explainBasicUpdate: function explainBasicUpdate(db, collName) { + var res = + db[collName].explain('executionStats').update({i: this.nInserted}, {$set: {j: 49}}); + assertAlways.commandWorked(res); + assertWhenOwnColl(function() { + assertWhenOwnColl.eq(1, explain.executionStats.totalDocsExamined); - // document should not have been updated. - var doc = db[collName].findOne({i: this.nInserted}); - assertWhenOwnColl.eq(2 * this.nInserted, doc.j); - }.bind(this)); - }, - explainUpdateUpsert: function explainUpdateUpsert(db, collName) { - var res = db[collName] - .explain('executionStats') - .update({i: 2 * this.nInserted + 1}, - {$set: {j: 81}}, - /* upsert */ true); - assertAlways.commandWorked(res); - var stage = res.executionStats.executionStages; + // document should not have been updated. + var doc = db[collName].findOne({i: this.nInserted}); + assertWhenOwnColl.eq(2 * this.nInserted, doc.j); + }.bind(this)); + }, + explainUpdateUpsert: function explainUpdateUpsert(db, collName) { + var res = db[collName] + .explain('executionStats') + .update({i: 2 * this.nInserted + 1}, + {$set: {j: 81}}, + /* upsert */ true); + assertAlways.commandWorked(res); + var stage = res.executionStats.executionStages; - // if explaining a write command through mongos - if (isMongos(db)) { - stage = stage.shards[0].executionStages; - } - assertAlways.eq(stage.stage, 'UPDATE'); - assertWhenOwnColl(stage.wouldInsert); + // if explaining a write command through mongos + if (isMongos(db)) { + stage = stage.shards[0].executionStages; + } + assertAlways.eq(stage.stage, 'UPDATE'); + assertWhenOwnColl(stage.wouldInsert); - // make sure that the insert didn't actually happen. - assertWhenOwnColl.eq(this.nInserted, db[collName].find().itcount()); - }, - explainUpdateMulti: function explainUpdateMulti(db, collName) { - var res = db[collName] - .explain('executionStats') - .update({i: {$lte: 2}}, - {$set: {b: 3}}, - /* upsert */ false, - /* multi */ true); - assertAlways.commandWorked(res); - var stage = res.executionStats.executionStages; + // make sure that the insert didn't actually happen. + assertWhenOwnColl.eq(this.nInserted, db[collName].find().itcount()); + }, + explainUpdateMulti: function explainUpdateMulti(db, collName) { + var res = db[collName] + .explain('executionStats') + .update({i: {$lte: 2}}, + {$set: {b: 3}}, + /* upsert */ false, + /* multi */ true); + assertAlways.commandWorked(res); + var stage = res.executionStats.executionStages; - // if explaining a write command through mongos - if (isMongos(db)) { - stage = stage.shards[0].executionStages; - } - assertAlways.eq(stage.stage, 'UPDATE'); - assertWhenOwnColl(!stage.wouldInsert); - assertWhenOwnColl.eq(3, stage.nMatched); - assertWhenOwnColl.eq(3, stage.nWouldModify); - } - }, - $super.states); + // if explaining a write command through mongos + if (isMongos(db)) { + stage = stage.shards[0].executionStages; + } + assertAlways.eq(stage.stage, 'UPDATE'); + assertWhenOwnColl(!stage.wouldInsert); + assertWhenOwnColl.eq(3, stage.nMatched); + assertWhenOwnColl.eq(3, stage.nWouldModify); + } + }, + $super.states); - $config.transitions = - Object.extend({explain: $config.data.assignEqualProbsToTransitions($config.states)}, - $super.transitions); + $config.transitions = Object.extend( + {explain: $config.data.assignEqualProbsToTransitions($config.states)}, $super.transitions); - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/findAndModify_inc.js b/jstests/concurrency/fsm_workloads/findAndModify_inc.js index 5c5d55b55b8..5a8b63392a8 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_inc.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_inc.js @@ -24,9 +24,7 @@ var $config = (function() { }, update: function update(db, collName) { - var updateDoc = { - $inc: {} - }; + var updateDoc = {$inc: {}}; updateDoc.$inc[this.fieldName] = 1; var res = db.runCommand( @@ -64,11 +62,7 @@ var $config = (function() { }; - var transitions = { - init: {update: 1}, - update: {find: 1}, - find: {update: 1} - }; + var transitions = {init: {update: 1}, update: {find: 1}, find: {update: 1}}; function setup(db, collName, cluster) { db[collName].insert({_id: 'findAndModify_inc'}); diff --git a/jstests/concurrency/fsm_workloads/findAndModify_mixed_queue_unindexed.js b/jstests/concurrency/fsm_workloads/findAndModify_mixed_queue_unindexed.js index 11ac81d63fd..19cd191b1aa 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_mixed_queue_unindexed.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_mixed_queue_unindexed.js @@ -21,79 +21,73 @@ load('jstests/concurrency/fsm_workloads/findAndModify_remove_queue.js'); // for // For isMongod and supportsDocumentLevelConcurrency. load('jstests/concurrency/fsm_workload_helpers/server_types.js'); -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - // Use the workload name as the database name, since the workload name is assumed to be - // unique. - $config.data.uniqueDBName = 'findAndModify_mixed_queue_unindexed'; + // Use the workload name as the database name, since the workload name is assumed to be + // unique. + $config.data.uniqueDBName = 'findAndModify_mixed_queue_unindexed'; - $config.data.newDocForInsert = function newDocForInsert(i) { - return { - _id: i, - rand: Random.rand(), - counter: 0 - }; - }; + $config.data.newDocForInsert = function newDocForInsert(i) { + return {_id: i, rand: Random.rand(), counter: 0}; + }; - $config.data.getIndexSpecs = function getIndexSpecs() { - return []; - }; + $config.data.getIndexSpecs = function getIndexSpecs() { + return []; + }; - $config.data.opName = 'modified'; + $config.data.opName = 'modified'; - $config.data.validateResult = function validateResult(db, collName, res) { - assertAlways.commandWorked(res); + $config.data.validateResult = function validateResult(db, collName, res) { + assertAlways.commandWorked(res); - var doc = res.value; - if (isMongod(db) && supportsDocumentLevelConcurrency(db)) { - // Storage engines which do not support document-level concurrency will not - // automatically retry if there was a conflict, so it is expected that it may return - // null in the case of a conflict. All other storage engines should automatically - // retry the operation, and thus should never return null. - assertWhenOwnColl.neq( - doc, null, 'findAndModify should have found a matching document'); - } - if (doc !== null) { - this.saveDocId(db, collName, doc._id); - } - }; + var doc = res.value; + if (isMongod(db) && supportsDocumentLevelConcurrency(db)) { + // Storage engines which do not support document-level concurrency will not + // automatically retry if there was a conflict, so it is expected that it may return + // null in the case of a conflict. All other storage engines should automatically + // retry the operation, and thus should never return null. + assertWhenOwnColl.neq(doc, null, 'findAndModify should have found a matching document'); + } + if (doc !== null) { + this.saveDocId(db, collName, doc._id); + } + }; - $config.states = (function() { - // Avoid removing documents that were already updated. - function remove(db, collName) { - var res = db.runCommand({ - findAndModify: db[collName].getName(), - query: {counter: 0}, - sort: {rand: -1}, - remove: true - }); - this.validateResult(db, collName, res); - } + $config.states = (function() { + // Avoid removing documents that were already updated. + function remove(db, collName) { + var res = db.runCommand({ + findAndModify: db[collName].getName(), + query: {counter: 0}, + sort: {rand: -1}, + remove: true + }); + this.validateResult(db, collName, res); + } - function update(db, collName) { - // Update the counter field to avoid matching the same document again. - var res = db.runCommand({ - findAndModify: db[collName].getName(), - query: {counter: 0}, - sort: {rand: -1}, - update: {$inc: {counter: 1}}, new: false - }); - this.validateResult(db, collName, res); - } + function update(db, collName) { + // Update the counter field to avoid matching the same document again. + var res = db.runCommand({ + findAndModify: db[collName].getName(), + query: {counter: 0}, + sort: {rand: -1}, + update: {$inc: {counter: 1}}, + new: false + }); + this.validateResult(db, collName, res); + } - return { - remove: remove, - update: update, - }; + return { + remove: remove, + update: update, + }; - })(); + })(); - $config.transitions = { - remove: {remove: 0.5, update: 0.5}, - update: {remove: 0.5, update: 0.5}, - }; + $config.transitions = { + remove: {remove: 0.5, update: 0.5}, + update: {remove: 0.5, update: 0.5}, + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/findAndModify_remove.js b/jstests/concurrency/fsm_workloads/findAndModify_remove.js index b33e67b2e01..b4a32a3cc74 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_remove.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_remove.js @@ -8,9 +8,7 @@ */ var $config = (function() { - var data = { - shardKey: {tid: 1} - }; + var data = {shardKey: {tid: 1}}; var states = (function() { @@ -42,24 +40,12 @@ var $config = (function() { this.iter++; } - return { - init: init, - insertAndRemove: insertAndRemove - }; + return {init: init, insertAndRemove: insertAndRemove}; })(); - var transitions = { - init: {insertAndRemove: 1}, - insertAndRemove: {insertAndRemove: 1} - }; + var transitions = {init: {insertAndRemove: 1}, insertAndRemove: {insertAndRemove: 1}}; - return { - threadCount: 20, - iterations: 20, - data: data, - states: states, - transitions: transitions - }; + return {threadCount: 20, iterations: 20, data: data, states: states, transitions: transitions}; })(); diff --git a/jstests/concurrency/fsm_workloads/findAndModify_remove_queue.js b/jstests/concurrency/fsm_workloads/findAndModify_remove_queue.js index 3a330529e0c..9b945468cf5 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_remove_queue.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_remove_queue.js @@ -22,10 +22,7 @@ var $config = (function() { uniqueDBName: 'findAndModify_remove_queue', newDocForInsert: function newDocForInsert(i) { - return { - _id: i, - rand: Random.rand() - }; + return {_id: i, rand: Random.rand()}; }, getIndexSpecs: function getIndexSpecs() { @@ -38,9 +35,7 @@ var $config = (function() { // Use a separate database to avoid conflicts with other FSM workloads. var ownedDB = db.getSiblingDB(db.getName() + this.uniqueDBName); - var updateDoc = { - $push: {} - }; + var updateDoc = {$push: {}}; updateDoc.$push[this.opName] = id; var res = ownedDB[collName].update({_id: this.tid}, updateDoc, {upsert: true}); @@ -64,12 +59,8 @@ var $config = (function() { var states = (function() { function remove(db, collName) { - var res = db.runCommand({ - findAndModify: db[collName].getName(), - query: {}, - sort: {rand: -1}, - remove: true - }); + var res = db.runCommand( + {findAndModify: db[collName].getName(), query: {}, sort: {rand: -1}, remove: true}); assertAlways.commandWorked(res); var doc = res.value; @@ -86,15 +77,11 @@ var $config = (function() { } } - return { - remove: remove - }; + return {remove: remove}; })(); - var transitions = { - remove: {remove: 1} - }; + var transitions = {remove: {remove: 1}}; function setup(db, collName, cluster) { // Each thread should remove exactly one document per iteration. @@ -193,10 +180,7 @@ var $config = (function() { if (!smallestValueIsSet) { return null; } - return { - value: smallestValue, - indices: smallestIndices - }; + return {value: smallestValue, indices: smallestIndices}; } } diff --git a/jstests/concurrency/fsm_workloads/findAndModify_remove_queue_unindexed.js b/jstests/concurrency/fsm_workloads/findAndModify_remove_queue_unindexed.js index 80ce7567a7d..387c5467f04 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_remove_queue_unindexed.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_remove_queue_unindexed.js @@ -16,16 +16,15 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/findAndModify_remove_queue.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - // Use the workload name as the database name, since the workload - // name is assumed to be unique. - $config.data.uniqueDBName = 'findAndModify_remove_queue_unindexed'; + // Use the workload name as the database name, since the workload + // name is assumed to be unique. + $config.data.uniqueDBName = 'findAndModify_remove_queue_unindexed'; - $config.data.getIndexSpecs = function getIndexSpecs() { - return []; - }; + $config.data.getIndexSpecs = function getIndexSpecs() { + return []; + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/findAndModify_update.js b/jstests/concurrency/fsm_workloads/findAndModify_update.js index c794c755ed9..16aa80b8a33 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_update.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_update.js @@ -18,11 +18,7 @@ var $config = (function() { var states = (function() { function makeDoc(tid) { - return { - _id: new ObjectId(), - tid: tid, - value: 0 - }; + return {_id: new ObjectId(), tid: tid, value: 0}; } function init(db, collName) { @@ -40,7 +36,8 @@ var $config = (function() { findandmodify: db[collName].getName(), query: {tid: this.tid}, sort: {value: 1}, - update: {$max: {value: updatedValue}}, new: true + update: {$max: {value: updatedValue}}, + new: true }); assertAlways.commandWorked(res); @@ -60,7 +57,8 @@ var $config = (function() { findandmodify: db[collName].getName(), query: {tid: this.tid}, sort: {value: -1}, - update: {$min: {value: updatedValue}}, new: true + update: {$min: {value: updatedValue}}, + new: true }); assertAlways.commandWorked(res); diff --git a/jstests/concurrency/fsm_workloads/findAndModify_update_collscan.js b/jstests/concurrency/fsm_workloads/findAndModify_update_collscan.js index f9e40b6b467..d1c8134bd39 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_update_collscan.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_update_collscan.js @@ -13,16 +13,15 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/findAndModify_update.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - // Do not create the { tid: 1, value: 1 } index so that a - // collection - // scan is performed for the query and sort operations. - $config.setup = function setup(db, collName, cluster) {}; + // Do not create the { tid: 1, value: 1 } index so that a + // collection + // scan is performed for the query and sort operations. + $config.setup = function setup(db, collName, cluster) {}; - // Remove the shardKey so that a collection scan is performed - delete $config.data.shardKey; + // Remove the shardKey so that a collection scan is performed + delete $config.data.shardKey; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/findAndModify_update_grow.js b/jstests/concurrency/fsm_workloads/findAndModify_update_grow.js index 277b2882700..7c32f6aefec 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_update_grow.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_update_grow.js @@ -30,11 +30,7 @@ var $config = (function() { function makeDoc(tid) { // Use 32-bit integer for representing 'length' property // to ensure $mul does integer multiplication - var doc = { - _id: new ObjectId(), - tid: tid, - length: new NumberInt(1) - }; + var doc = {_id: new ObjectId(), tid: tid, length: new NumberInt(1)}; doc[uniqueFieldName] = makeStringOfLength(doc.length); return doc; } @@ -70,17 +66,15 @@ var $config = (function() { var updatedLength = factor * this.length; var updatedValue = makeStringOfLength(updatedLength); - var update = { - $set: {}, - $mul: {length: factor} - }; + var update = {$set: {}, $mul: {length: factor}}; update.$set[uniqueFieldName] = updatedValue; var res = db.runCommand({ findandmodify: db[collName].getName(), query: {tid: this.tid}, sort: {length: 1}, // fetch document of smallest size - update: update, new: true + update: update, + new: true }); assertAlways.commandWorked(res); @@ -117,10 +111,7 @@ var $config = (function() { })(); - var transitions = { - insert: {findAndModify: 1}, - findAndModify: {findAndModify: 1} - }; + var transitions = {insert: {findAndModify: 1}, findAndModify: {findAndModify: 1}}; return { threadCount: 20, diff --git a/jstests/concurrency/fsm_workloads/findAndModify_update_queue.js b/jstests/concurrency/fsm_workloads/findAndModify_update_queue.js index 104b299b317..1d82f4b7eb2 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_update_queue.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_update_queue.js @@ -17,69 +17,58 @@ load('jstests/concurrency/fsm_workloads/findAndModify_remove_queue.js'); // for // For isMongod and supportsDocumentLevelConcurrency. load('jstests/concurrency/fsm_workload_helpers/server_types.js'); -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - // Use the workload name as the database name, since the workload name is assumed to be - // unique. - $config.data.uniqueDBName = 'findAndModify_update_queue'; + // Use the workload name as the database name, since the workload name is assumed to be + // unique. + $config.data.uniqueDBName = 'findAndModify_update_queue'; - $config.data.newDocForInsert = function newDocForInsert(i) { - return { - _id: i, - rand: Random.rand(), - counter: 0 - }; - }; + $config.data.newDocForInsert = function newDocForInsert(i) { + return {_id: i, rand: Random.rand(), counter: 0}; + }; - $config.data.getIndexSpecs = function getIndexSpecs() { - return [{counter: 1, rand: -1}]; - }; + $config.data.getIndexSpecs = function getIndexSpecs() { + return [{counter: 1, rand: -1}]; + }; - $config.data.opName = 'updated'; + $config.data.opName = 'updated'; - var states = (function() { + var states = (function() { - function update(db, collName) { - // Update the counter field to avoid matching the same document again. - var res = db.runCommand({ - findAndModify: db[collName].getName(), - query: {counter: 0}, - sort: {rand: -1}, - update: {$inc: {counter: 1}}, new: false - }); - assertAlways.commandWorked(res); + function update(db, collName) { + // Update the counter field to avoid matching the same document again. + var res = db.runCommand({ + findAndModify: db[collName].getName(), + query: {counter: 0}, + sort: {rand: -1}, + update: {$inc: {counter: 1}}, + new: false + }); + assertAlways.commandWorked(res); - var doc = res.value; - if (isMongod(db) && supportsDocumentLevelConcurrency(db)) { - // Storage engines which do not support document-level concurrency will not - // automatically retry if there was a conflict, so it is expected that it may - // return null in the case of a conflict. All other storage engines should - // automatically retry the operation, and thus should never return null. - assertWhenOwnColl.neq( - doc, - null, - 'findAndModify should have found and updated a matching document'); - } - if (doc !== null) { - this.saveDocId(db, collName, doc._id); - } + var doc = res.value; + if (isMongod(db) && supportsDocumentLevelConcurrency(db)) { + // Storage engines which do not support document-level concurrency will not + // automatically retry if there was a conflict, so it is expected that it may + // return null in the case of a conflict. All other storage engines should + // automatically retry the operation, and thus should never return null. + assertWhenOwnColl.neq( + doc, null, 'findAndModify should have found and updated a matching document'); } + if (doc !== null) { + this.saveDocId(db, collName, doc._id); + } + } - return { - update: update - }; + return {update: update}; - })(); + })(); - var transitions = { - update: {update: 1} - }; + var transitions = {update: {update: 1}}; - $config.startState = 'update'; - $config.states = states; - $config.transitions = transitions; + $config.startState = 'update'; + $config.states = states; + $config.transitions = transitions; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/findAndModify_update_queue_unindexed.js b/jstests/concurrency/fsm_workloads/findAndModify_update_queue_unindexed.js index c6561829b26..cda9a494a61 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_update_queue_unindexed.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_update_queue_unindexed.js @@ -16,16 +16,15 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/findAndModify_update_queue.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - // Use the workload name as the database name, since the workload - // name is assumed to be unique. - $config.data.uniqueDBName = 'findAndModify_update_queue_unindexed'; + // Use the workload name as the database name, since the workload + // name is assumed to be unique. + $config.data.uniqueDBName = 'findAndModify_update_queue_unindexed'; - $config.data.getIndexSpecs = function getIndexSpecs() { - return []; - }; + $config.data.getIndexSpecs = function getIndexSpecs() { + return []; + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/findAndModify_upsert.js b/jstests/concurrency/fsm_workloads/findAndModify_upsert.js index 499e8324cae..e79b5322bc4 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_upsert.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_upsert.js @@ -10,10 +10,7 @@ */ var $config = (function() { - var data = { - sort: false, - shardKey: {tid: 1} - }; + var data = {sort: false, shardKey: {tid: 1}}; var states = (function() { @@ -41,15 +38,13 @@ var $config = (function() { var updatedValue = this.iter++; // Use a query specification that does not match any existing documents - var query = { - _id: new ObjectId(), - tid: this.tid - }; + var query = {_id: new ObjectId(), tid: this.tid}; var cmdObj = { findandmodify: db[collName].getName(), query: query, - update: {$setOnInsert: {values: [updatedValue]}}, new: true, + update: {$setOnInsert: {values: [updatedValue]}}, + new: true, upsert: true }; @@ -64,11 +59,12 @@ var $config = (function() { assertAlways(doc !== null, 'a document should have been inserted'); assertAlways((function() { - assertAlways.eq(this.tid, doc.tid); - assertAlways(Array.isArray(doc.values), 'expected values to be an array'); - assertAlways.eq(1, doc.values.length); - assertAlways.eq(updatedValue, doc.values[0]); - }).bind(this)); + assertAlways.eq(this.tid, doc.tid); + assertAlways(Array.isArray(doc.values), + 'expected values to be an array'); + assertAlways.eq(1, doc.values.length); + assertAlways.eq(updatedValue, doc.values[0]); + }).bind(this)); } function update(db, collName) { @@ -77,7 +73,8 @@ var $config = (function() { var cmdObj = { findandmodify: db[collName].getName(), query: {tid: this.tid}, - update: {$push: {values: updatedValue}}, new: true, + update: {$push: {values: updatedValue}}, + new: true, upsert: false }; @@ -103,11 +100,7 @@ var $config = (function() { } } - return { - init: init, - upsert: upsert, - update: update - }; + return {init: init, upsert: upsert, update: update}; })(); @@ -117,12 +110,6 @@ var $config = (function() { update: {upsert: 0.1, update: 0.9} }; - return { - threadCount: 20, - iterations: 20, - data: data, - states: states, - transitions: transitions - }; + return {threadCount: 20, iterations: 20, data: data, states: states, transitions: transitions}; })(); diff --git a/jstests/concurrency/fsm_workloads/findAndModify_upsert_collscan.js b/jstests/concurrency/fsm_workloads/findAndModify_upsert_collscan.js index aad1fbc644c..8751e99fd21 100644 --- a/jstests/concurrency/fsm_workloads/findAndModify_upsert_collscan.js +++ b/jstests/concurrency/fsm_workloads/findAndModify_upsert_collscan.js @@ -13,12 +13,9 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/findAndModify_upsert.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.sort = { - $natural: 1 - }; + $config.data.sort = {$natural: 1}; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/group.js b/jstests/concurrency/fsm_workloads/group.js index 3ccc909e0c9..a02d175f202 100644 --- a/jstests/concurrency/fsm_workloads/group.js +++ b/jstests/concurrency/fsm_workloads/group.js @@ -21,9 +21,7 @@ var $config = (function() { initial: {bucketCount: 0, bucketSum: 0}, $keyf: function $keyf(doc) { // place doc.rand into appropriate bucket - return { - bucket: Math.floor(doc.rand * 10) + 1 - }; + return {bucket: Math.floor(doc.rand * 10) + 1}; }, $reduce: function $reduce(curr, result) { result.bucketCount++; @@ -63,15 +61,11 @@ var $config = (function() { }.bind(this)); } - return { - group: group - }; + return {group: group}; })(); - var transitions = { - group: {group: 1} - }; + var transitions = {group: {group: 1}}; function setup(db, collName, cluster) { var bulk = db[collName].initializeUnorderedBulkOp(); diff --git a/jstests/concurrency/fsm_workloads/group_cond.js b/jstests/concurrency/fsm_workloads/group_cond.js index 1ab6aa827c6..03a77993578 100644 --- a/jstests/concurrency/fsm_workloads/group_cond.js +++ b/jstests/concurrency/fsm_workloads/group_cond.js @@ -16,29 +16,25 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/group.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { - $config.setup = function setup(db, collName, cluster) { - $super.setup.apply(this, arguments); - assertAlways.commandWorked(db[collName].ensureIndex({rand: 1})); - }; +var $config = extendWorkload($config, function($config, $super) { + $config.setup = function setup(db, collName, cluster) { + $super.setup.apply(this, arguments); + assertAlways.commandWorked(db[collName].ensureIndex({rand: 1})); + }; - $config.states.group = function group(db, collName) { - var cmdObj = this.generateGroupCmdObj(collName); - cmdObj.group.cond = { - rand: {$gte: 0.5} - }; - var res = db.runCommand(cmdObj); - assertWhenOwnColl.commandWorked(res); + $config.states.group = function group(db, collName) { + var cmdObj = this.generateGroupCmdObj(collName); + cmdObj.group.cond = {rand: {$gte: 0.5}}; + var res = db.runCommand(cmdObj); + assertWhenOwnColl.commandWorked(res); - assertWhenOwnColl.lte(res.count, this.numDocs); - assertWhenOwnColl.lte(res.keys, 5); - assertWhenOwnColl(function() { - assertWhenOwnColl.lte(res.retval.length, 5); - assertWhenOwnColl.eq(this.sumBucketCount(res.retval), res.count); - }.bind(this)); - }; + assertWhenOwnColl.lte(res.count, this.numDocs); + assertWhenOwnColl.lte(res.keys, 5); + assertWhenOwnColl(function() { + assertWhenOwnColl.lte(res.retval.length, 5); + assertWhenOwnColl.eq(this.sumBucketCount(res.retval), res.count); + }.bind(this)); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_1char.js b/jstests/concurrency/fsm_workloads/indexed_insert_1char.js index 5330bd9191e..54fe0662cb4 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_1char.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_1char.js @@ -10,18 +10,17 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_base.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.indexedField = 'indexed_insert_1char'; - $config.data.shardKey = {}; - $config.data.shardKey[$config.data.indexedField] = 1; + $config.data.indexedField = 'indexed_insert_1char'; + $config.data.shardKey = {}; + $config.data.shardKey[$config.data.indexedField] = 1; - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); - this.indexedValue = String.fromCharCode(33 + this.tid); - }; + this.indexedValue = String.fromCharCode(33 + this.tid); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_2d.js b/jstests/concurrency/fsm_workloads/indexed_insert_2d.js index 674f229f53b..a461f9cb310 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_2d.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_2d.js @@ -10,48 +10,46 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_base.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.indexedField = 'indexed_insert_2d'; - // Remove the shard key for 2d indexes, as they are not supported - delete $config.data.shardKey; + $config.data.indexedField = 'indexed_insert_2d'; + // Remove the shard key for 2d indexes, as they are not supported + delete $config.data.shardKey; - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); - assertAlways.lt(this.tid, 1 << 16); // assume tid is a 16 bit nonnegative int - // split the tid into the odd bits and the even bits - // for example: - // tid: 57 = 00111001 - // even: 0 1 0 1 = 5 - // odd: 0 1 1 0 = 6 - // This lets us turn every tid into a unique pair of numbers within the range [0, 255]. - // The pairs are then normalized to have valid longitude and latitude values. - var oddBits = 0; - var evenBits = 0; - for (var i = 0; i < 16; ++i) { - if (this.tid & 1 << i) { - if (i % 2 === 0) { - // i is even - evenBits |= 1 << (i / 2); - } else { - // i is odd - oddBits |= 1 << (i / 2); - } + assertAlways.lt(this.tid, 1 << 16); // assume tid is a 16 bit nonnegative int + // split the tid into the odd bits and the even bits + // for example: + // tid: 57 = 00111001 + // even: 0 1 0 1 = 5 + // odd: 0 1 1 0 = 6 + // This lets us turn every tid into a unique pair of numbers within the range [0, 255]. + // The pairs are then normalized to have valid longitude and latitude values. + var oddBits = 0; + var evenBits = 0; + for (var i = 0; i < 16; ++i) { + if (this.tid & 1 << i) { + if (i % 2 === 0) { + // i is even + evenBits |= 1 << (i / 2); + } else { + // i is odd + oddBits |= 1 << (i / 2); } } - assertAlways.lt(oddBits, 256); - assertAlways.lt(evenBits, 256); - this.indexedValue = [(evenBits - 128) / 2, (oddBits - 128) / 2]; - }; + } + assertAlways.lt(oddBits, 256); + assertAlways.lt(evenBits, 256); + this.indexedValue = [(evenBits - 128) / 2, (oddBits - 128) / 2]; + }; - $config.data.getIndexSpec = function getIndexSpec() { - var ixSpec = {}; - ixSpec[this.indexedField] = '2d'; - return ixSpec; - }; + $config.data.getIndexSpec = function getIndexSpec() { + var ixSpec = {}; + ixSpec[this.indexedField] = '2d'; + return ixSpec; + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_2dsphere.js b/jstests/concurrency/fsm_workloads/indexed_insert_2dsphere.js index a0fb5613ef6..40134e97840 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_2dsphere.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_2dsphere.js @@ -10,16 +10,15 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_2d.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.indexedField = 'indexed_insert_2dsphere'; + $config.data.indexedField = 'indexed_insert_2dsphere'; - $config.data.getIndexSpec = function getIndexSpec() { - var ixSpec = {}; - ixSpec[this.indexedField] = '2dsphere'; - return ixSpec; - }; + $config.data.getIndexSpec = function getIndexSpec() { + var ixSpec = {}; + ixSpec[this.indexedField] = '2dsphere'; + return ixSpec; + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_base.js b/jstests/concurrency/fsm_workloads/indexed_insert_base.js index 59dcab4f0a0..b7a52aae08a 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_base.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_base.js @@ -69,11 +69,7 @@ var $config = (function() { } }; - var transitions = { - init: {insert: 1}, - insert: {find: 1}, - find: {insert: 1} - }; + var transitions = {init: {insert: 1}, insert: {find: 1}, find: {insert: 1}}; function setup(db, collName, cluster) { var res = db[collName].ensureIndex(this.getIndexSpec()); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_compound.js b/jstests/concurrency/fsm_workloads/indexed_insert_compound.js index a32fc084215..c704b6dd0bc 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_compound.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_compound.js @@ -10,31 +10,29 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_base.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); - }; + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); + }; - $config.data.getDoc = function getDoc() { - return { - indexed_insert_compound_x: this.tid & 0x0f, // lowest 4 bits - indexed_insert_compound_y: this.tid >> 4, // high bits - indexed_insert_compound_z: String.fromCharCode(33 + this.tid) - }; - }; + $config.data.getDoc = function getDoc() { + return { + indexed_insert_compound_x: this.tid & 0x0f, // lowest 4 bits + indexed_insert_compound_y: this.tid >> 4, // high bits + indexed_insert_compound_z: String.fromCharCode(33 + this.tid) + }; + }; - $config.data.getIndexSpec = function getIndexSpec() { - return { - indexed_insert_compound_x: 1, - indexed_insert_compound_y: 1, - indexed_insert_compound_z: 1 - }; - }; + $config.data.getIndexSpec = function getIndexSpec() { + return { + indexed_insert_compound_x: 1, + indexed_insert_compound_y: 1, + indexed_insert_compound_z: 1 + }; + }; - $config.data.shardKey = $config.data.getIndexSpec(); + $config.data.shardKey = $config.data.getIndexSpec(); - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_eval.js b/jstests/concurrency/fsm_workloads/indexed_insert_eval.js index ccb3696ffeb..f35d4565e3b 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_eval.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_eval.js @@ -10,26 +10,24 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_base.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.nolock = false; + $config.data.nolock = false; - $config.states.insert = function insert(db, collName) { - var evalResult = db.runCommand({ - eval: function(collName, doc) { - var insertResult = db[collName].insert(doc); - return tojson(insertResult); - }, - args: [collName, this.getDoc()], - nolock: this.nolock - }); - assertAlways.commandWorked(evalResult); - var insertResult = JSON.parse(evalResult.retval); - assertAlways.eq(1, insertResult.nInserted, tojson(insertResult)); - this.nInserted += this.docsPerInsert; - }; + $config.states.insert = function insert(db, collName) { + var evalResult = db.runCommand({ + eval: function(collName, doc) { + var insertResult = db[collName].insert(doc); + return tojson(insertResult); + }, + args: [collName, this.getDoc()], + nolock: this.nolock + }); + assertAlways.commandWorked(evalResult); + var insertResult = JSON.parse(evalResult.retval); + assertAlways.eq(1, insertResult.nInserted, tojson(insertResult)); + this.nInserted += this.docsPerInsert; + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_eval_nolock.js b/jstests/concurrency/fsm_workloads/indexed_insert_eval_nolock.js index 33e8ef41d56..f87ba5da790 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_eval_nolock.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_eval_nolock.js @@ -10,10 +10,9 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_eval.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.nolock = true; + $config.data.nolock = true; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_heterogeneous.js b/jstests/concurrency/fsm_workloads/indexed_insert_heterogeneous.js index ddf2a0c0ead..b486120185d 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_heterogeneous.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_heterogeneous.js @@ -10,48 +10,47 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_base.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { - - $config.data.indexedField = 'indexed_insert_heterogeneous'; - $config.data.shardKey = {}; - $config.data.shardKey[$config.data.indexedField] = 1; - - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); - - // prefix str with zeroes to make it have length len - function pad(len, str) { - var padding = new Array(len + 1).join('0'); - return (padding + str).slice(-len); - } - - function makeOID(tid) { - var str = pad(24, tid.toString(16)); - return new ObjectId(str); - } - - function makeDate(tid) { - var d = new ISODate('2000-01-01T00:00:00.000Z'); - // setSeconds(n) where n >= 60 will just cause the minutes, - // hours, etc to increase, - // so this produces a unique date for each tid - d.setSeconds(tid); - return d; - } - - var choices = [ - this.tid, // int - this.tid.toString(), // string - this.tid * 0.0001, // float - {tid: this.tid}, // subdocument - makeOID(this.tid), // objectid - makeDate(this.tid), // date - new Function('', 'return ' + this.tid + ';') // function - ]; - - this.indexedValue = choices[this.tid % choices.length]; - }; - - return $config; - }); +var $config = extendWorkload($config, function($config, $super) { + + $config.data.indexedField = 'indexed_insert_heterogeneous'; + $config.data.shardKey = {}; + $config.data.shardKey[$config.data.indexedField] = 1; + + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); + + // prefix str with zeroes to make it have length len + function pad(len, str) { + var padding = new Array(len + 1).join('0'); + return (padding + str).slice(-len); + } + + function makeOID(tid) { + var str = pad(24, tid.toString(16)); + return new ObjectId(str); + } + + function makeDate(tid) { + var d = new ISODate('2000-01-01T00:00:00.000Z'); + // setSeconds(n) where n >= 60 will just cause the minutes, + // hours, etc to increase, + // so this produces a unique date for each tid + d.setSeconds(tid); + return d; + } + + var choices = [ + this.tid, // int + this.tid.toString(), // string + this.tid * 0.0001, // float + {tid: this.tid}, // subdocument + makeOID(this.tid), // objectid + makeDate(this.tid), // date + new Function('', 'return ' + this.tid + ';') // function + ]; + + this.indexedValue = choices[this.tid % choices.length]; + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_large.js b/jstests/concurrency/fsm_workloads/indexed_insert_large.js index d7bedb22ade..cb2dbf58b21 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_large.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_large.js @@ -11,38 +11,35 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_base.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.indexedField = 'indexed_insert_large'; + $config.data.indexedField = 'indexed_insert_large'; - // Remove the shard key, since it cannot be greater than 512 bytes - delete $config.data.shardKey; + // Remove the shard key, since it cannot be greater than 512 bytes + delete $config.data.shardKey; - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); - // "The total size of an index entry, which can include structural overhead depending on - // the - // BSON type, must be less than 1024 bytes." - // http://docs.mongodb.org/manual/reference/limits/ - var maxIndexedSize = 1023; + // "The total size of an index entry, which can include structural overhead depending on + // the + // BSON type, must be less than 1024 bytes." + // http://docs.mongodb.org/manual/reference/limits/ + var maxIndexedSize = 1023; - var bsonOverhead = Object.bsonsize({'': ''}); + var bsonOverhead = Object.bsonsize({'': ''}); - var bigstr = new Array(maxIndexedSize + 1).join('x'); + var bigstr = new Array(maxIndexedSize + 1).join('x'); - // prefix the big string with tid to make it unique, - // then trim it down so that it plus bson overhead is maxIndexedSize + // prefix the big string with tid to make it unique, + // then trim it down so that it plus bson overhead is maxIndexedSize - this.indexedValue = (this.tid + bigstr).slice(0, maxIndexedSize - bsonOverhead); + this.indexedValue = (this.tid + bigstr).slice(0, maxIndexedSize - bsonOverhead); - assertAlways.eq( - maxIndexedSize, - Object.bsonsize({'': this.indexedValue}), - 'buggy test: the inserted docs will not have the expected index-key size'); - }; + assertAlways.eq(maxIndexedSize, + Object.bsonsize({'': this.indexedValue}), + 'buggy test: the inserted docs will not have the expected index-key size'); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_long_fieldname.js b/jstests/concurrency/fsm_workloads/indexed_insert_long_fieldname.js index 3c8c2f70223..143f548619a 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_long_fieldname.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_long_fieldname.js @@ -10,16 +10,14 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_base.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - // TODO: make this field name even longer? - var length = 100; - var prefix = 'indexed_insert_long_fieldname_'; - $config.data.indexedField = - prefix + new Array(length - prefix.length + 1).join('x'); - $config.data.shardKey = {}; - $config.data.shardKey[$config.data.indexedField] = 1; + // TODO: make this field name even longer? + var length = 100; + var prefix = 'indexed_insert_long_fieldname_'; + $config.data.indexedField = prefix + new Array(length - prefix.length + 1).join('x'); + $config.data.shardKey = {}; + $config.data.shardKey[$config.data.indexedField] = 1; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_multikey.js b/jstests/concurrency/fsm_workloads/indexed_insert_multikey.js index e49b5356760..34c28db22eb 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_multikey.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_multikey.js @@ -10,21 +10,19 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_base.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.indexedField = 'indexed_insert_multikey'; - // Remove the shard key, since it cannot be a multikey index - delete $config.data.shardKey; + $config.data.indexedField = 'indexed_insert_multikey'; + // Remove the shard key, since it cannot be a multikey index + delete $config.data.shardKey; - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); - this.indexedValue = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function(n) { - return this.tid * 10 + n; - }.bind(this)); - }; + this.indexedValue = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function(n) { + return this.tid * 10 + n; + }.bind(this)); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_ordered_bulk.js b/jstests/concurrency/fsm_workloads/indexed_insert_ordered_bulk.js index eb70c850488..38998cd9f59 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_ordered_bulk.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_ordered_bulk.js @@ -11,30 +11,28 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_base.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.indexedField = 'indexed_insert_ordered_bulk'; - $config.data.shardKey = {}; - $config.data.shardKey[$config.data.indexedField] = 1; + $config.data.indexedField = 'indexed_insert_ordered_bulk'; + $config.data.shardKey = {}; + $config.data.shardKey[$config.data.indexedField] = 1; - $config.states.insert = function insert(db, collName) { - var doc = {}; - doc[this.indexedField] = this.indexedValue; + $config.states.insert = function insert(db, collName) { + var doc = {}; + doc[this.indexedField] = this.indexedValue; - var bulk = db[collName].initializeOrderedBulkOp(); - for (var i = 0; i < this.docsPerInsert; ++i) { - bulk.insert(doc); - } - var res = bulk.execute(); - assertAlways.writeOK(res); - assertAlways.eq(this.docsPerInsert, res.nInserted, tojson(res)); + var bulk = db[collName].initializeOrderedBulkOp(); + for (var i = 0; i < this.docsPerInsert; ++i) { + bulk.insert(doc); + } + var res = bulk.execute(); + assertAlways.writeOK(res); + assertAlways.eq(this.docsPerInsert, res.nInserted, tojson(res)); - this.nInserted += this.docsPerInsert; - }; + this.nInserted += this.docsPerInsert; + }; - $config.data.docsPerInsert = 15; + $config.data.docsPerInsert = 15; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_text.js b/jstests/concurrency/fsm_workloads/indexed_insert_text.js index ab38d07098f..82e0feb09a8 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_text.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_text.js @@ -32,10 +32,7 @@ var $config = (function() { } }; - var transitions = { - init: {insert: 1}, - insert: {insert: 1} - }; + var transitions = {init: {insert: 1}, insert: {insert: 1}}; function setup(db, collName, cluster) { var ixSpec = {}; diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_text_multikey.js b/jstests/concurrency/fsm_workloads/indexed_insert_text_multikey.js index 0cc7b590684..b527ef016f8 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_text_multikey.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_text_multikey.js @@ -8,30 +8,27 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_text.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); - }; + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); + }; - $config.data.getRandomTextSnippet = function getRandomTextSnippet() { - var len = Random.randInt(5) + - 1; // ensure we always add some text, not just empty array - var textArr = []; - for (var i = 0; i < len; ++i) { - textArr.push($super.data.getRandomTextSnippet.call(this, arguments)); - } - return textArr; - }; + $config.data.getRandomTextSnippet = function getRandomTextSnippet() { + var len = Random.randInt(5) + 1; // ensure we always add some text, not just empty array + var textArr = []; + for (var i = 0; i < len; ++i) { + textArr.push($super.data.getRandomTextSnippet.call(this, arguments)); + } + return textArr; + }; - // SERVER-21291: Reduce the thread count to alleviate PV1 failovers on - // Windows DEBUG hosts. - $config.threadCount = 5; + // SERVER-21291: Reduce the thread count to alleviate PV1 failovers on + // Windows DEBUG hosts. + $config.threadCount = 5; - // Remove the shard key, since it cannot be a multikey index - delete $config.data.shardKey; + // Remove the shard key, since it cannot be a multikey index + delete $config.data.shardKey; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_ttl.js b/jstests/concurrency/fsm_workloads/indexed_insert_ttl.js index 90aa6d3baf7..ba95fa6e778 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_ttl.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_ttl.js @@ -24,10 +24,7 @@ var $config = (function() { } }; - var transitions = { - init: {insert: 1}, - insert: {insert: 1} - }; + var transitions = {init: {insert: 1}, insert: {insert: 1}}; function setup(db, collName, cluster) { var res = db[collName].ensureIndex({indexed_insert_ttl: 1}, diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_unordered_bulk.js b/jstests/concurrency/fsm_workloads/indexed_insert_unordered_bulk.js index aa64e8d21e5..3c1ea8f0ea0 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_unordered_bulk.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_unordered_bulk.js @@ -11,30 +11,28 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_base.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.indexedField = 'indexed_insert_unordered_bulk'; - $config.data.shardKey = {}; - $config.data.shardKey[$config.data.indexedField] = 1; + $config.data.indexedField = 'indexed_insert_unordered_bulk'; + $config.data.shardKey = {}; + $config.data.shardKey[$config.data.indexedField] = 1; - $config.states.insert = function insert(db, collName) { - var doc = {}; - doc[this.indexedField] = this.indexedValue; + $config.states.insert = function insert(db, collName) { + var doc = {}; + doc[this.indexedField] = this.indexedValue; - var bulk = db[collName].initializeUnorderedBulkOp(); - for (var i = 0; i < this.docsPerInsert; ++i) { - bulk.insert(doc); - } - var res = bulk.execute(); - assertAlways.writeOK(res); - assertAlways.eq(this.docsPerInsert, res.nInserted, tojson(res)); + var bulk = db[collName].initializeUnorderedBulkOp(); + for (var i = 0; i < this.docsPerInsert; ++i) { + bulk.insert(doc); + } + var res = bulk.execute(); + assertAlways.writeOK(res); + assertAlways.eq(this.docsPerInsert, res.nInserted, tojson(res)); - this.nInserted += this.docsPerInsert; - }; + this.nInserted += this.docsPerInsert; + }; - $config.data.docsPerInsert = 15; + $config.data.docsPerInsert = 15; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_upsert.js b/jstests/concurrency/fsm_workloads/indexed_insert_upsert.js index cc26d364ace..bc1b65e9597 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_upsert.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_upsert.js @@ -13,34 +13,32 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_base.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.indexedField = 'indexed_insert_upsert'; - $config.data.shardKey = {}; - $config.data.shardKey[$config.data.indexedField] = 1; + $config.data.indexedField = 'indexed_insert_upsert'; + $config.data.shardKey = {}; + $config.data.shardKey[$config.data.indexedField] = 1; - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); - this.counter = 0; - }; + this.counter = 0; + }; - $config.states.insert = function insert(db, collName) { - var doc = this.getDoc(); - doc.counter = this.counter++; // ensure doc is unique to guarantee an upsert occurs - doc._id = new ObjectId(); // _id is required for shard targeting + $config.states.insert = function insert(db, collName) { + var doc = this.getDoc(); + doc.counter = this.counter++; // ensure doc is unique to guarantee an upsert occurs + doc._id = new ObjectId(); // _id is required for shard targeting - var res = db[collName].update(doc, {$inc: {unused: 0}}, {upsert: true}); - assertAlways.eq(0, res.nMatched, tojson(res)); - assertAlways.eq(1, res.nUpserted, tojson(res)); - if (db.getMongo().writeMode() === 'commands') { - assertAlways.eq(0, res.nModified, tojson(res)); - } + var res = db[collName].update(doc, {$inc: {unused: 0}}, {upsert: true}); + assertAlways.eq(0, res.nMatched, tojson(res)); + assertAlways.eq(1, res.nUpserted, tojson(res)); + if (db.getMongo().writeMode() === 'commands') { + assertAlways.eq(0, res.nModified, tojson(res)); + } - this.nInserted += this.docsPerInsert; - }; + this.nInserted += this.docsPerInsert; + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/indexed_insert_where.js b/jstests/concurrency/fsm_workloads/indexed_insert_where.js index 14408c26f69..e5d2a98b8c5 100644 --- a/jstests/concurrency/fsm_workloads/indexed_insert_where.js +++ b/jstests/concurrency/fsm_workloads/indexed_insert_where.js @@ -15,9 +15,7 @@ var $config = (function() { documentsToInsert: 100, insertedDocuments: 0, generateDocumentToInsert: function generateDocumentToInsert() { - return { - tid: this.tid - }; + return {tid: this.tid}; }, shardKey: {tid: 1} }; @@ -43,10 +41,7 @@ var $config = (function() { } }; - var transitions = { - insert: {insert: 0.2, query: 0.8}, - query: {insert: 0.8, query: 0.2} - }; + var transitions = {insert: {insert: 0.2, query: 0.8}, query: {insert: 0.8, query: 0.2}}; var setup = function setup(db, collName, cluster) { assertAlways.commandWorked(db[collName].ensureIndex({tid: 1})); diff --git a/jstests/concurrency/fsm_workloads/list_indexes.js b/jstests/concurrency/fsm_workloads/list_indexes.js index 6bcdb8ba96c..e62225eaa51 100644 --- a/jstests/concurrency/fsm_workloads/list_indexes.js +++ b/jstests/concurrency/fsm_workloads/list_indexes.js @@ -26,10 +26,7 @@ var $config = (function() { assertWhenOwnColl.gte(cursor.itcount(), 0); } - return { - modifyIndices: modifyIndices, - listIndices: listIndices - }; + return {modifyIndices: modifyIndices, listIndices: listIndices}; })(); var transitions = { diff --git a/jstests/concurrency/fsm_workloads/map_reduce_drop.js b/jstests/concurrency/fsm_workloads/map_reduce_drop.js index ef03805dffd..48398b4aae2 100644 --- a/jstests/concurrency/fsm_workloads/map_reduce_drop.js +++ b/jstests/concurrency/fsm_workloads/map_reduce_drop.js @@ -80,11 +80,7 @@ var $config = (function() { } } - return { - dropColl: dropColl, - dropDB: dropDB, - mapReduce: mapReduce - }; + return {dropColl: dropColl, dropDB: dropDB, mapReduce: mapReduce}; })(); diff --git a/jstests/concurrency/fsm_workloads/map_reduce_inline.js b/jstests/concurrency/fsm_workloads/map_reduce_inline.js index 1633ce0cc19..ade5a8aa369 100644 --- a/jstests/concurrency/fsm_workloads/map_reduce_inline.js +++ b/jstests/concurrency/fsm_workloads/map_reduce_inline.js @@ -38,12 +38,7 @@ var $config = (function() { return reducedValue; } - var data = { - numDocs: 2000, - mapper: mapper, - reducer: reducer, - finalizer: finalizer - }; + var data = {numDocs: 2000, mapper: mapper, reducer: reducer, finalizer: finalizer}; var states = (function() { @@ -53,26 +48,17 @@ var $config = (function() { } function mapReduce(db, collName) { - var options = { - finalize: this.finalizer, - out: {inline: 1} - }; + var options = {finalize: this.finalizer, out: {inline: 1}}; var res = db[collName].mapReduce(this.mapper, this.reducer, options); assertAlways.commandWorked(res); } - return { - init: init, - mapReduce: mapReduce - }; + return {init: init, mapReduce: mapReduce}; })(); - var transitions = { - init: {mapReduce: 1}, - mapReduce: {mapReduce: 1} - }; + var transitions = {init: {mapReduce: 1}, mapReduce: {mapReduce: 1}}; function makeDoc(keyLimit, valueLimit) { return { diff --git a/jstests/concurrency/fsm_workloads/map_reduce_merge.js b/jstests/concurrency/fsm_workloads/map_reduce_merge.js index 4f96c229eac..f12e7f24144 100644 --- a/jstests/concurrency/fsm_workloads/map_reduce_merge.js +++ b/jstests/concurrency/fsm_workloads/map_reduce_merge.js @@ -16,49 +16,44 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/map_reduce_inline.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - // Use the workload name as the database name, - // since the workload name is assumed to be unique. - var uniqueDBName = 'map_reduce_merge'; + // Use the workload name as the database name, + // since the workload name is assumed to be unique. + var uniqueDBName = 'map_reduce_merge'; - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); - this.outDBName = db.getName() + uniqueDBName; - }; + this.outDBName = db.getName() + uniqueDBName; + }; - $config.states.mapReduce = function mapReduce(db, collName) { - var outDB = db.getSiblingDB(this.outDBName); - var fullName = outDB[collName].getFullName(); - assertAlways(outDB[collName].exists() !== null, - "output collection '" + fullName + "' should exist"); + $config.states.mapReduce = function mapReduce(db, collName) { + var outDB = db.getSiblingDB(this.outDBName); + var fullName = outDB[collName].getFullName(); + assertAlways(outDB[collName].exists() !== null, + "output collection '" + fullName + "' should exist"); - // Have all threads combine their results into the same collection - var options = { - finalize: this.finalizer, - out: {merge: collName, db: this.outDBName} - }; + // Have all threads combine their results into the same collection + var options = {finalize: this.finalizer, out: {merge: collName, db: this.outDBName}}; - var res = db[collName].mapReduce(this.mapper, this.reducer, options); - assertAlways.commandWorked(res); - }; + var res = db[collName].mapReduce(this.mapper, this.reducer, options); + assertAlways.commandWorked(res); + }; - $config.setup = function setup(db, collName, cluster) { - $super.setup.apply(this, arguments); + $config.setup = function setup(db, collName, cluster) { + $super.setup.apply(this, arguments); - var outDB = db.getSiblingDB(db.getName() + uniqueDBName); - assertAlways.commandWorked(outDB.createCollection(collName)); - }; + var outDB = db.getSiblingDB(db.getName() + uniqueDBName); + assertAlways.commandWorked(outDB.createCollection(collName)); + }; - $config.teardown = function teardown(db, collName, cluster) { - var outDB = db.getSiblingDB(db.getName() + uniqueDBName); - var res = outDB.dropDatabase(); - assertAlways.commandWorked(res); - assertAlways.eq(db.getName() + uniqueDBName, res.dropped); - }; + $config.teardown = function teardown(db, collName, cluster) { + var outDB = db.getSiblingDB(db.getName() + uniqueDBName); + var res = outDB.dropDatabase(); + assertAlways.commandWorked(res); + assertAlways.eq(db.getName() + uniqueDBName, res.dropped); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/map_reduce_merge_nonatomic.js b/jstests/concurrency/fsm_workloads/map_reduce_merge_nonatomic.js index 8f0804b365d..9522854d566 100644 --- a/jstests/concurrency/fsm_workloads/map_reduce_merge_nonatomic.js +++ b/jstests/concurrency/fsm_workloads/map_reduce_merge_nonatomic.js @@ -17,45 +17,43 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWo load('jstests/concurrency/fsm_workloads/map_reduce_inline.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); // for dropDatabases -var $config = - extendWorkload($config, - function($config, $super) { - - // Use the workload name as a prefix for the database name, - // since the workload name is assumed to be unique. - var prefix = 'map_reduce_merge_nonatomic'; - - function uniqueDBName(prefix, tid) { - return prefix + tid; - } - - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); - - this.outDBName = db.getName() + uniqueDBName(prefix, this.tid); - var outDB = db.getSiblingDB(this.outDBName); - assertAlways.commandWorked(outDB.createCollection(collName)); - }; - - $config.states.mapReduce = function mapReduce(db, collName) { - var outDB = db.getSiblingDB(this.outDBName); - var fullName = outDB[collName].getFullName(); - assertAlways(outDB[collName].exists() !== null, - "output collection '" + fullName + "' should exist"); - - var options = { - finalize: this.finalizer, - out: {merge: collName, db: this.outDBName, nonAtomic: true} - }; - - var res = db[collName].mapReduce(this.mapper, this.reducer, options); - assertAlways.commandWorked(res); - }; - - $config.teardown = function teardown(db, collName, cluster) { - var pattern = new RegExp('^' + db.getName() + prefix + '\\d+$'); - dropDatabases(db, pattern); - }; - - return $config; - }); +var $config = extendWorkload($config, function($config, $super) { + + // Use the workload name as a prefix for the database name, + // since the workload name is assumed to be unique. + var prefix = 'map_reduce_merge_nonatomic'; + + function uniqueDBName(prefix, tid) { + return prefix + tid; + } + + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); + + this.outDBName = db.getName() + uniqueDBName(prefix, this.tid); + var outDB = db.getSiblingDB(this.outDBName); + assertAlways.commandWorked(outDB.createCollection(collName)); + }; + + $config.states.mapReduce = function mapReduce(db, collName) { + var outDB = db.getSiblingDB(this.outDBName); + var fullName = outDB[collName].getFullName(); + assertAlways(outDB[collName].exists() !== null, + "output collection '" + fullName + "' should exist"); + + var options = { + finalize: this.finalizer, + out: {merge: collName, db: this.outDBName, nonAtomic: true} + }; + + var res = db[collName].mapReduce(this.mapper, this.reducer, options); + assertAlways.commandWorked(res); + }; + + $config.teardown = function teardown(db, collName, cluster) { + var pattern = new RegExp('^' + db.getName() + prefix + '\\d+$'); + dropDatabases(db, pattern); + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/map_reduce_reduce.js b/jstests/concurrency/fsm_workloads/map_reduce_reduce.js index b11ccf3614f..3acd8d3b64c 100644 --- a/jstests/concurrency/fsm_workloads/map_reduce_reduce.js +++ b/jstests/concurrency/fsm_workloads/map_reduce_reduce.js @@ -15,43 +15,38 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWo load('jstests/concurrency/fsm_workloads/map_reduce_inline.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); // for dropCollections -var $config = - extendWorkload($config, - function($config, $super) { - - // Use the workload name as a prefix for the collection name, - // since the workload name is assumed to be unique. - var prefix = 'map_reduce_reduce'; - - function uniqueCollectionName(prefix, tid) { - return prefix + tid; - } - - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); - - this.outCollName = uniqueCollectionName(prefix, this.tid); - assertAlways.commandWorked(db.createCollection(this.outCollName)); - }; - - $config.states.mapReduce = function mapReduce(db, collName) { - var fullName = db[this.outCollName].getFullName(); - assertAlways(db[this.outCollName].exists() !== null, - "output collection '" + fullName + "' should exist"); - - var options = { - finalize: this.finalizer, - out: {reduce: this.outCollName} - }; - - var res = db[collName].mapReduce(this.mapper, this.reducer, options); - assertAlways.commandWorked(res); - }; - - $config.teardown = function teardown(db, collName, cluster) { - var pattern = new RegExp('^' + prefix + '\\d+$'); - dropCollections(db, pattern); - }; - - return $config; - }); +var $config = extendWorkload($config, function($config, $super) { + + // Use the workload name as a prefix for the collection name, + // since the workload name is assumed to be unique. + var prefix = 'map_reduce_reduce'; + + function uniqueCollectionName(prefix, tid) { + return prefix + tid; + } + + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); + + this.outCollName = uniqueCollectionName(prefix, this.tid); + assertAlways.commandWorked(db.createCollection(this.outCollName)); + }; + + $config.states.mapReduce = function mapReduce(db, collName) { + var fullName = db[this.outCollName].getFullName(); + assertAlways(db[this.outCollName].exists() !== null, + "output collection '" + fullName + "' should exist"); + + var options = {finalize: this.finalizer, out: {reduce: this.outCollName}}; + + var res = db[collName].mapReduce(this.mapper, this.reducer, options); + assertAlways.commandWorked(res); + }; + + $config.teardown = function teardown(db, collName, cluster) { + var pattern = new RegExp('^' + prefix + '\\d+$'); + dropCollections(db, pattern); + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/map_reduce_reduce_nonatomic.js b/jstests/concurrency/fsm_workloads/map_reduce_reduce_nonatomic.js index 5953c7c2a07..6ffdf20f85d 100644 --- a/jstests/concurrency/fsm_workloads/map_reduce_reduce_nonatomic.js +++ b/jstests/concurrency/fsm_workloads/map_reduce_reduce_nonatomic.js @@ -17,44 +17,39 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/map_reduce_inline.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - // Use the workload name as the collection name, - // since the workload name is assumed to be unique. - var uniqueCollectionName = 'map_reduce_reduce_nonatomic'; + // Use the workload name as the collection name, + // since the workload name is assumed to be unique. + var uniqueCollectionName = 'map_reduce_reduce_nonatomic'; - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); - this.outCollName = uniqueCollectionName; - }; + this.outCollName = uniqueCollectionName; + }; - $config.states.mapReduce = function mapReduce(db, collName) { - var fullName = db[this.outCollName].getFullName(); - assertAlways(db[this.outCollName].exists() !== null, - "output collection '" + fullName + "' should exist"); + $config.states.mapReduce = function mapReduce(db, collName) { + var fullName = db[this.outCollName].getFullName(); + assertAlways(db[this.outCollName].exists() !== null, + "output collection '" + fullName + "' should exist"); - // Have all threads combine their results into the same collection - var options = { - finalize: this.finalizer, - out: {reduce: this.outCollName, nonAtomic: true} - }; + // Have all threads combine their results into the same collection + var options = {finalize: this.finalizer, out: {reduce: this.outCollName, nonAtomic: true}}; - var res = db[collName].mapReduce(this.mapper, this.reducer, options); - assertAlways.commandWorked(res); - }; + var res = db[collName].mapReduce(this.mapper, this.reducer, options); + assertAlways.commandWorked(res); + }; - $config.setup = function setup(db, collName, cluster) { - $super.setup.apply(this, arguments); + $config.setup = function setup(db, collName, cluster) { + $super.setup.apply(this, arguments); - assertAlways.commandWorked(db.createCollection(uniqueCollectionName)); - }; + assertAlways.commandWorked(db.createCollection(uniqueCollectionName)); + }; - $config.teardown = function teardown(db, collName, cluster) { - assertAlways(db[uniqueCollectionName].drop()); - }; + $config.teardown = function teardown(db, collName, cluster) { + assertAlways(db[uniqueCollectionName].drop()); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/map_reduce_replace.js b/jstests/concurrency/fsm_workloads/map_reduce_replace.js index ce268bf5e20..3db3685a7ad 100644 --- a/jstests/concurrency/fsm_workloads/map_reduce_replace.js +++ b/jstests/concurrency/fsm_workloads/map_reduce_replace.js @@ -15,45 +15,43 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWo load('jstests/concurrency/fsm_workloads/map_reduce_inline.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); // for dropCollections -var $config = - extendWorkload($config, - function($config, $super) { - - // Use the workload name as a prefix for the collection name, - // since the workload name is assumed to be unique. - var prefix = 'map_reduce_replace'; - - function uniqueCollectionName(prefix, tid) { - return prefix + tid; - } - - $config.states.init = function init(db, collName) { - $super.states.init.apply(this, arguments); - - this.outCollName = uniqueCollectionName(prefix, this.tid); - assertAlways.commandWorked(db.createCollection(this.outCollName)); - }; - - $config.states.mapReduce = function mapReduce(db, collName) { - var fullName = db[this.outCollName].getFullName(); - assertAlways(db[this.outCollName].exists() !== null, - "output collection '" + fullName + "' should exist"); - - var options = { - finalize: this.finalizer, - out: {replace: this.outCollName}, - query: {key: {$exists: true}, value: {$exists: true}}, - sort: {_id: -1} // sort key must be an existing index - }; - - var res = db[collName].mapReduce(this.mapper, this.reducer, options); - assertAlways.commandWorked(res); - }; - - $config.teardown = function teardown(db, collName, cluster) { - var pattern = new RegExp('^' + prefix + '\\d+$'); - dropCollections(db, pattern); - }; - - return $config; - }); +var $config = extendWorkload($config, function($config, $super) { + + // Use the workload name as a prefix for the collection name, + // since the workload name is assumed to be unique. + var prefix = 'map_reduce_replace'; + + function uniqueCollectionName(prefix, tid) { + return prefix + tid; + } + + $config.states.init = function init(db, collName) { + $super.states.init.apply(this, arguments); + + this.outCollName = uniqueCollectionName(prefix, this.tid); + assertAlways.commandWorked(db.createCollection(this.outCollName)); + }; + + $config.states.mapReduce = function mapReduce(db, collName) { + var fullName = db[this.outCollName].getFullName(); + assertAlways(db[this.outCollName].exists() !== null, + "output collection '" + fullName + "' should exist"); + + var options = { + finalize: this.finalizer, + out: {replace: this.outCollName}, + query: {key: {$exists: true}, value: {$exists: true}}, + sort: {_id: -1} // sort key must be an existing index + }; + + var res = db[collName].mapReduce(this.mapper, this.reducer, options); + assertAlways.commandWorked(res); + }; + + $config.teardown = function teardown(db, collName, cluster) { + var pattern = new RegExp('^' + prefix + '\\d+$'); + dropCollections(db, pattern); + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/map_reduce_replace_nonexistent.js b/jstests/concurrency/fsm_workloads/map_reduce_replace_nonexistent.js index 3bfdb6086de..cb802da7a90 100644 --- a/jstests/concurrency/fsm_workloads/map_reduce_replace_nonexistent.js +++ b/jstests/concurrency/fsm_workloads/map_reduce_replace_nonexistent.js @@ -14,39 +14,37 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWo load('jstests/concurrency/fsm_workloads/map_reduce_inline.js'); // for $config load('jstests/concurrency/fsm_workload_helpers/drop_utils.js'); // for dropCollections -var $config = extendWorkload( - $config, - function($config, $super) { - - // Use the workload name as a prefix for the collection name, - // since the workload name is assumed to be unique. - var prefix = 'map_reduce_replace_nonexistent'; - - function uniqueCollectionName(prefix, tid) { - return prefix + tid; - } - - $config.states.mapReduce = function mapReduce(db, collName) { - var outCollName = uniqueCollectionName(prefix, this.tid); - var fullName = db[outCollName].getFullName(); - assertAlways.isnull(db[outCollName].exists(), - "output collection '" + fullName + "' should not exist"); - - var options = { - finalize: this.finalizer, - out: {replace: outCollName}, - query: {key: {$exists: true}, value: {$exists: true}} - }; - - var res = db[collName].mapReduce(this.mapper, this.reducer, options); - assertAlways.commandWorked(res); - assertAlways(db[outCollName].drop()); +var $config = extendWorkload($config, function($config, $super) { + + // Use the workload name as a prefix for the collection name, + // since the workload name is assumed to be unique. + var prefix = 'map_reduce_replace_nonexistent'; + + function uniqueCollectionName(prefix, tid) { + return prefix + tid; + } + + $config.states.mapReduce = function mapReduce(db, collName) { + var outCollName = uniqueCollectionName(prefix, this.tid); + var fullName = db[outCollName].getFullName(); + assertAlways.isnull(db[outCollName].exists(), + "output collection '" + fullName + "' should not exist"); + + var options = { + finalize: this.finalizer, + out: {replace: outCollName}, + query: {key: {$exists: true}, value: {$exists: true}} }; - $config.teardown = function teardown(db, collName, cluster) { - var pattern = new RegExp('^' + prefix + '\\d+$'); - dropCollections(db, pattern); - }; + var res = db[collName].mapReduce(this.mapper, this.reducer, options); + assertAlways.commandWorked(res); + assertAlways(db[outCollName].drop()); + }; + + $config.teardown = function teardown(db, collName, cluster) { + var pattern = new RegExp('^' + prefix + '\\d+$'); + dropCollections(db, pattern); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/plan_cache_drop_database.js b/jstests/concurrency/fsm_workloads/plan_cache_drop_database.js index abd1312b7c3..51ec0c3780b 100644 --- a/jstests/concurrency/fsm_workloads/plan_cache_drop_database.js +++ b/jstests/concurrency/fsm_workloads/plan_cache_drop_database.js @@ -40,10 +40,7 @@ var $config = (function() { function count(db, collName) { var coll = db.getSiblingDB(this.dbName)[collName]; - var cmdObj = { - query: {a: 1, b: {$gt: Random.rand()}}, - limit: Random.randInt(10) - }; + var cmdObj = {query: {a: 1, b: {$gt: Random.rand()}}, limit: Random.randInt(10)}; // We can't use assertAlways.commandWorked here because the plan // executor can be killed during the count. @@ -61,17 +58,11 @@ var $config = (function() { populateData(myDB, collName); } - return { - count: count, - dropDB: dropDB - }; + return {count: count, dropDB: dropDB}; })(); - var transitions = { - count: {count: 0.95, dropDB: 0.05}, - dropDB: {count: 0.95, dropDB: 0.05} - }; + var transitions = {count: {count: 0.95, dropDB: 0.05}, dropDB: {count: 0.95, dropDB: 0.05}}; function setup(db, collName, cluster) { var myDB = db.getSiblingDB(this.dbName); diff --git a/jstests/concurrency/fsm_workloads/reindex.js b/jstests/concurrency/fsm_workloads/reindex.js index cec33eddc5f..523e29789e0 100644 --- a/jstests/concurrency/fsm_workloads/reindex.js +++ b/jstests/concurrency/fsm_workloads/reindex.js @@ -62,9 +62,7 @@ var $config = (function() { 'inserted'); var coords = [[[-26, -26], [-26, 26], [26, 26], [26, -26], [-26, -26]]]; - var geoQuery = { - geo: {$geoWithin: {$geometry: {type: 'Polygon', coordinates: coords}}} - }; + var geoQuery = {geo: {$geoWithin: {$geometry: {type: 'Polygon', coordinates: coords}}}}; // We can only perform a geo query when we own the collection and are sure a geo index // is present. The same is true of text queries. @@ -91,12 +89,7 @@ var $config = (function() { assertAlways.commandWorked(res); } - return { - init: init, - createIndexes: createIndexes, - reIndex: reIndex, - query: query - }; + return {init: init, createIndexes: createIndexes, reIndex: reIndex, query: query}; })(); var transitions = { diff --git a/jstests/concurrency/fsm_workloads/reindex_background.js b/jstests/concurrency/fsm_workloads/reindex_background.js index 22db164ae6a..ff5dbc8d4d2 100644 --- a/jstests/concurrency/fsm_workloads/reindex_background.js +++ b/jstests/concurrency/fsm_workloads/reindex_background.js @@ -12,24 +12,22 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/reindex.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { - $config.data.prefix = 'reindex_background'; +var $config = extendWorkload($config, function($config, $super) { + $config.data.prefix = 'reindex_background'; - $config.states.createIndexes = function createIndexes(db, collName) { - var coll = db[this.threadCollName]; + $config.states.createIndexes = function createIndexes(db, collName) { + var coll = db[this.threadCollName]; - // The number of indexes created here is also stored in data.nIndexes - var textResult = coll.ensureIndex({text: 'text'}, {background: true}); - assertAlways.commandWorked(textResult); + // The number of indexes created here is also stored in data.nIndexes + var textResult = coll.ensureIndex({text: 'text'}, {background: true}); + assertAlways.commandWorked(textResult); - var geoResult = coll.ensureIndex({geo: '2dsphere'}, {background: true}); - assertAlways.commandWorked(geoResult); + var geoResult = coll.ensureIndex({geo: '2dsphere'}, {background: true}); + assertAlways.commandWorked(geoResult); - var integerResult = coll.ensureIndex({integer: 1}, {background: true}); - assertAlways.commandWorked(integerResult); - }; + var integerResult = coll.ensureIndex({integer: 1}, {background: true}); + assertAlways.commandWorked(integerResult); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/remove_and_bulk_insert.js b/jstests/concurrency/fsm_workloads/remove_and_bulk_insert.js index a57e61a44b0..63e179a0d2b 100644 --- a/jstests/concurrency/fsm_workloads/remove_and_bulk_insert.js +++ b/jstests/concurrency/fsm_workloads/remove_and_bulk_insert.js @@ -26,10 +26,7 @@ var $config = (function() { } }; - var transitions = { - insert: {insert: 0.5, remove: 0.5}, - remove: {insert: 0.5, remove: 0.5} - }; + var transitions = {insert: {insert: 0.5, remove: 0.5}, remove: {insert: 0.5, remove: 0.5}}; return { threadCount: 5, diff --git a/jstests/concurrency/fsm_workloads/remove_multiple_documents.js b/jstests/concurrency/fsm_workloads/remove_multiple_documents.js index d809b0be8e3..bfd64cd6790 100644 --- a/jstests/concurrency/fsm_workloads/remove_multiple_documents.js +++ b/jstests/concurrency/fsm_workloads/remove_multiple_documents.js @@ -34,17 +34,8 @@ var $config = (function() { } }; - var transitions = { - init: {count: 1}, - count: {remove: 1}, - remove: {remove: 0.825, count: 0.125} - }; + var transitions = {init: {count: 1}, count: {remove: 1}, remove: {remove: 0.825, count: 0.125}}; - return { - threadCount: 10, - iterations: 20, - states: states, - transitions: transitions - }; + return {threadCount: 10, iterations: 20, states: states, transitions: transitions}; })(); diff --git a/jstests/concurrency/fsm_workloads/remove_single_document.js b/jstests/concurrency/fsm_workloads/remove_single_document.js index 5f83e0f57f8..1bfdb2b6897 100644 --- a/jstests/concurrency/fsm_workloads/remove_single_document.js +++ b/jstests/concurrency/fsm_workloads/remove_single_document.js @@ -23,9 +23,7 @@ var $config = (function() { } }; - var transitions = { - remove: {remove: 1} - }; + var transitions = {remove: {remove: 1}}; function setup(db, collName, cluster) { // insert enough documents so that each thread can remove exactly one per iteration diff --git a/jstests/concurrency/fsm_workloads/remove_single_document_eval.js b/jstests/concurrency/fsm_workloads/remove_single_document_eval.js index e90eaa63114..3109c743e29 100644 --- a/jstests/concurrency/fsm_workloads/remove_single_document_eval.js +++ b/jstests/concurrency/fsm_workloads/remove_single_document_eval.js @@ -8,32 +8,30 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/remove_single_document.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.doRemove = function doRemove(db, collName, query, options) { - var evalResult = db.runCommand({ - eval: function(f, collName, query, options) { - return tojson(f(db, collName, query, options)); - }, - args: [$super.data.doRemove, collName, query, options], - nolock: this.nolock - }); - assertAlways.commandWorked(evalResult); - var res = JSON.parse(evalResult.retval); - return res; - }; + $config.data.doRemove = function doRemove(db, collName, query, options) { + var evalResult = db.runCommand({ + eval: function(f, collName, query, options) { + return tojson(f(db, collName, query, options)); + }, + args: [$super.data.doRemove, collName, query, options], + nolock: this.nolock + }); + assertAlways.commandWorked(evalResult); + var res = JSON.parse(evalResult.retval); + return res; + }; - $config.data.assertResult = function assertResult(res) { - assertWhenOwnColl.eq(1, res.nRemoved, tojson(res)); - }; + $config.data.assertResult = function assertResult(res) { + assertWhenOwnColl.eq(1, res.nRemoved, tojson(res)); + }; - $config.data.nolock = false; + $config.data.nolock = false; - // scale down threadCount and iterations because eval takes a global lock - $config.threadCount = 5; - $config.iterations = 10; + // scale down threadCount and iterations because eval takes a global lock + $config.threadCount = 5; + $config.iterations = 10; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/remove_single_document_eval_nolock.js b/jstests/concurrency/fsm_workloads/remove_single_document_eval_nolock.js index e88868c3345..a3f67c26892 100644 --- a/jstests/concurrency/fsm_workloads/remove_single_document_eval_nolock.js +++ b/jstests/concurrency/fsm_workloads/remove_single_document_eval_nolock.js @@ -8,10 +8,9 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/remove_single_document_eval.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.nolock = true; + $config.data.nolock = true; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/remove_where.js b/jstests/concurrency/fsm_workloads/remove_where.js index 36e228ebd9a..f9c0e6a2c03 100644 --- a/jstests/concurrency/fsm_workloads/remove_where.js +++ b/jstests/concurrency/fsm_workloads/remove_where.js @@ -11,37 +11,32 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_where.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { - $config.data.randomBound = 10; - $config.data.generateDocumentToInsert = function generateDocumentToInsert() { - return { - tid: this.tid, - x: Random.randInt(this.randomBound) - }; - }; +var $config = extendWorkload($config, function($config, $super) { + $config.data.randomBound = 10; + $config.data.generateDocumentToInsert = function generateDocumentToInsert() { + return {tid: this.tid, x: Random.randInt(this.randomBound)}; + }; - $config.states.remove = function remove(db, collName) { - var res = db[collName].remove({ - // Server-side JS does not support Random.randInt, so use Math.floor/random instead - $where: 'this.x === Math.floor(Math.random() * ' + this.randomBound + ') ' + - '&& this.tid === ' + this.tid - }); - assertWhenOwnColl.gte(res.nRemoved, 0); - assertWhenOwnColl.lte(res.nRemoved, this.insertedDocuments); - this.insertedDocuments -= res.nRemoved; - }; + $config.states.remove = function remove(db, collName) { + var res = db[collName].remove({ + // Server-side JS does not support Random.randInt, so use Math.floor/random instead + $where: 'this.x === Math.floor(Math.random() * ' + this.randomBound + ') ' + + '&& this.tid === ' + this.tid + }); + assertWhenOwnColl.gte(res.nRemoved, 0); + assertWhenOwnColl.lte(res.nRemoved, this.insertedDocuments); + this.insertedDocuments -= res.nRemoved; + }; - $config.transitions = { - insert: {insert: 0.2, remove: 0.4, query: 0.4}, - remove: {insert: 0.4, remove: 0.2, query: 0.4}, - query: {insert: 0.4, remove: 0.4, query: 0.2} - }; + $config.transitions = { + insert: {insert: 0.2, remove: 0.4, query: 0.4}, + remove: {insert: 0.4, remove: 0.2, query: 0.4}, + query: {insert: 0.4, remove: 0.4, query: 0.2} + }; - $config.setup = function setup(db, collName, cluster) { - /* no-op to prevent index from being created */ - }; + $config.setup = function setup(db, collName, cluster) { + /* no-op to prevent index from being created */ + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/rename_capped_collection_chain.js b/jstests/concurrency/fsm_workloads/rename_capped_collection_chain.js index b02642cb4c2..cc3de60d3c0 100644 --- a/jstests/concurrency/fsm_workloads/rename_capped_collection_chain.js +++ b/jstests/concurrency/fsm_workloads/rename_capped_collection_chain.js @@ -27,10 +27,7 @@ var $config = (function() { this.fromCollName = uniqueCollectionName(this.prefix, this.tid, 0); this.num = 1; - var options = { - capped: true, - size: 4096 - }; + var options = {capped: true, size: 4096}; assertAlways.commandWorked(db.createCollection(this.fromCollName, options)); assertWhenOwnDB(db[this.fromCollName].isCapped()); @@ -44,17 +41,11 @@ var $config = (function() { this.fromCollName = toCollName; } - return { - init: init, - rename: rename - }; + return {init: init, rename: rename}; })(); - var transitions = { - init: {rename: 1}, - rename: {rename: 1} - }; + var transitions = {init: {rename: 1}, rename: {rename: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/rename_capped_collection_dbname_chain.js b/jstests/concurrency/fsm_workloads/rename_capped_collection_dbname_chain.js index d69bb975d62..93d52f8c251 100644 --- a/jstests/concurrency/fsm_workloads/rename_capped_collection_dbname_chain.js +++ b/jstests/concurrency/fsm_workloads/rename_capped_collection_dbname_chain.js @@ -28,10 +28,7 @@ var $config = (function() { this.num = 1; var fromDB = db.getSiblingDB(this.fromDBName); - var options = { - capped: true, - size: 4096 - }; + var options = {capped: true, size: 4096}; assertAlways.commandWorked(fromDB.createCollection(collName, options)); assertAlways(fromDB[collName].isCapped()); @@ -57,17 +54,11 @@ var $config = (function() { this.fromDBName = toDBName; } - return { - init: init, - rename: rename - }; + return {init: init, rename: rename}; })(); - var transitions = { - init: {rename: 1}, - rename: {rename: 1} - }; + var transitions = {init: {rename: 1}, rename: {rename: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + db.getName() + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/rename_capped_collection_dbname_droptarget.js b/jstests/concurrency/fsm_workloads/rename_capped_collection_dbname_droptarget.js index 06930a0457c..b1c4c156c3f 100644 --- a/jstests/concurrency/fsm_workloads/rename_capped_collection_dbname_droptarget.js +++ b/jstests/concurrency/fsm_workloads/rename_capped_collection_dbname_droptarget.js @@ -19,10 +19,7 @@ var $config = (function() { var states = (function() { - var options = { - capped: true, - size: 4096 - }; + var options = {capped: true, size: 4096}; function uniqueDBName(prefix, tid, num) { return prefix + tid + '_' + num; @@ -80,17 +77,11 @@ var $config = (function() { this.toDBName = temp; } - return { - init: init, - rename: rename - }; + return {init: init, rename: rename}; })(); - var transitions = { - init: {rename: 1}, - rename: {rename: 1} - }; + var transitions = {init: {rename: 1}, rename: {rename: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + db.getName() + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/rename_capped_collection_droptarget.js b/jstests/concurrency/fsm_workloads/rename_capped_collection_droptarget.js index 11621a0318b..1d6dfd6faf4 100644 --- a/jstests/concurrency/fsm_workloads/rename_capped_collection_droptarget.js +++ b/jstests/concurrency/fsm_workloads/rename_capped_collection_droptarget.js @@ -19,10 +19,7 @@ var $config = (function() { var states = (function() { - var options = { - capped: true, - size: 4096 - }; + var options = {capped: true, size: 4096}; function uniqueCollectionName(prefix, tid, num) { return prefix + tid + '_' + num; @@ -72,17 +69,11 @@ var $config = (function() { this.toCollName = temp; } - return { - init: init, - rename: rename - }; + return {init: init, rename: rename}; })(); - var transitions = { - init: {rename: 1}, - rename: {rename: 1} - }; + var transitions = {init: {rename: 1}, rename: {rename: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/rename_collection_chain.js b/jstests/concurrency/fsm_workloads/rename_collection_chain.js index 81c0313e217..eb6792f6df8 100644 --- a/jstests/concurrency/fsm_workloads/rename_collection_chain.js +++ b/jstests/concurrency/fsm_workloads/rename_collection_chain.js @@ -36,17 +36,11 @@ var $config = (function() { this.fromCollName = toCollName; } - return { - init: init, - rename: rename - }; + return {init: init, rename: rename}; })(); - var transitions = { - init: {rename: 1}, - rename: {rename: 1} - }; + var transitions = {init: {rename: 1}, rename: {rename: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/rename_collection_dbname_chain.js b/jstests/concurrency/fsm_workloads/rename_collection_dbname_chain.js index d11dfd19d22..bf76caa5014 100644 --- a/jstests/concurrency/fsm_workloads/rename_collection_dbname_chain.js +++ b/jstests/concurrency/fsm_workloads/rename_collection_dbname_chain.js @@ -49,17 +49,11 @@ var $config = (function() { this.fromDBName = toDBName; } - return { - init: init, - rename: rename - }; + return {init: init, rename: rename}; })(); - var transitions = { - init: {rename: 1}, - rename: {rename: 1} - }; + var transitions = {init: {rename: 1}, rename: {rename: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + db.getName() + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/rename_collection_dbname_droptarget.js b/jstests/concurrency/fsm_workloads/rename_collection_dbname_droptarget.js index 453d5a27379..7f23ecbc2d7 100644 --- a/jstests/concurrency/fsm_workloads/rename_collection_dbname_droptarget.js +++ b/jstests/concurrency/fsm_workloads/rename_collection_dbname_droptarget.js @@ -72,17 +72,11 @@ var $config = (function() { this.toDBName = temp; } - return { - init: init, - rename: rename - }; + return {init: init, rename: rename}; })(); - var transitions = { - init: {rename: 1}, - rename: {rename: 1} - }; + var transitions = {init: {rename: 1}, rename: {rename: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + db.getName() + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/rename_collection_droptarget.js b/jstests/concurrency/fsm_workloads/rename_collection_droptarget.js index bb2651258a5..592654ed3b1 100644 --- a/jstests/concurrency/fsm_workloads/rename_collection_droptarget.js +++ b/jstests/concurrency/fsm_workloads/rename_collection_droptarget.js @@ -64,17 +64,11 @@ var $config = (function() { this.toCollName = temp; } - return { - init: init, - rename: rename - }; + return {init: init, rename: rename}; })(); - var transitions = { - init: {rename: 1}, - rename: {rename: 1} - }; + var transitions = {init: {rename: 1}, rename: {rename: 1}}; function teardown(db, collName, cluster) { var pattern = new RegExp('^' + this.prefix + '\\d+_\\d+$'); diff --git a/jstests/concurrency/fsm_workloads/server_status.js b/jstests/concurrency/fsm_workloads/server_status.js index dbde1420b99..fa3c8cbbeef 100644 --- a/jstests/concurrency/fsm_workloads/server_status.js +++ b/jstests/concurrency/fsm_workloads/server_status.js @@ -9,23 +9,15 @@ var $config = (function() { var states = { status: function status(db, collName) { - var opts = { - opcounterRepl: 1, - oplog: 1, - rangeDeleter: 1, - repl: 1, - security: 1, - tcmalloc: 1 - }; + var opts = + {opcounterRepl: 1, oplog: 1, rangeDeleter: 1, repl: 1, security: 1, tcmalloc: 1}; var res = db.serverStatus(); assertAlways.commandWorked(res); assertAlways(res.hasOwnProperty('version')); } }; - var transitions = { - status: {status: 1} - }; + var transitions = {status: {status: 1}}; return { threadCount: 10, diff --git a/jstests/concurrency/fsm_workloads/touch_base.js b/jstests/concurrency/fsm_workloads/touch_base.js index df419e17db7..d69b7c94b2e 100644 --- a/jstests/concurrency/fsm_workloads/touch_base.js +++ b/jstests/concurrency/fsm_workloads/touch_base.js @@ -12,52 +12,42 @@ load('jstests/concurrency/fsm_workloads/indexed_insert_where.js'); // for $conf // For isMongod, isMMAPv1, and isEphemeral. load('jstests/concurrency/fsm_workload_helpers/server_types.js'); -var $config = - extendWorkload($config, - function($config, $super) { - $config.data.generateDocumentToInsert = function generateDocumentToInsert() { - return { - tid: this.tid, - x: Random.randInt(10) - }; - }; - - $config.data.generateTouchCmdObj = function generateTouchCmdObj(collName) { - return { - touch: collName, - data: true, - index: true - }; - }; - - $config.states.touch = function touch(db, collName) { - var res = db.runCommand(this.generateTouchCmdObj(collName)); - if (isMongod(db) && (isMMAPv1(db) || isEphemeral(db))) { - assertAlways.commandWorked(res); - } else { - // SERVER-16850 and SERVER-16797 - assertAlways.commandFailed(res); - } - }; - - $config.states.query = function query(db, collName) { - var count = db[collName].find({tid: this.tid}).itcount(); - assertWhenOwnColl.eq( - count, - this.insertedDocuments, - 'collection scan should return the number of documents this thread' + - ' inserted'); - }; - - $config.transitions = { - insert: {insert: 0.2, touch: 0.4, query: 0.4}, - touch: {insert: 0.4, touch: 0.2, query: 0.4}, - query: {insert: 0.4, touch: 0.4, query: 0.2} - }; - - $config.setup = function setup(db, collName, cluster) { - assertAlways.commandWorked(db[collName].ensureIndex({x: 1})); - }; - - return $config; - }); +var $config = extendWorkload($config, function($config, $super) { + $config.data.generateDocumentToInsert = function generateDocumentToInsert() { + return {tid: this.tid, x: Random.randInt(10)}; + }; + + $config.data.generateTouchCmdObj = function generateTouchCmdObj(collName) { + return {touch: collName, data: true, index: true}; + }; + + $config.states.touch = function touch(db, collName) { + var res = db.runCommand(this.generateTouchCmdObj(collName)); + if (isMongod(db) && (isMMAPv1(db) || isEphemeral(db))) { + assertAlways.commandWorked(res); + } else { + // SERVER-16850 and SERVER-16797 + assertAlways.commandFailed(res); + } + }; + + $config.states.query = function query(db, collName) { + var count = db[collName].find({tid: this.tid}).itcount(); + assertWhenOwnColl.eq(count, + this.insertedDocuments, + 'collection scan should return the number of documents this thread' + + ' inserted'); + }; + + $config.transitions = { + insert: {insert: 0.2, touch: 0.4, query: 0.4}, + touch: {insert: 0.4, touch: 0.2, query: 0.4}, + query: {insert: 0.4, touch: 0.4, query: 0.2} + }; + + $config.setup = function setup(db, collName, cluster) { + assertAlways.commandWorked(db[collName].ensureIndex({x: 1})); + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/touch_data.js b/jstests/concurrency/fsm_workloads/touch_data.js index dc3b7cecef0..11d2e53cdb6 100644 --- a/jstests/concurrency/fsm_workloads/touch_data.js +++ b/jstests/concurrency/fsm_workloads/touch_data.js @@ -10,16 +10,10 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/touch_base.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { - $config.data.generateTouchCmdObj = function generateTouchCmdObj(collName) { - return { - touch: collName, - data: true, - index: false - }; - }; +var $config = extendWorkload($config, function($config, $super) { + $config.data.generateTouchCmdObj = function generateTouchCmdObj(collName) { + return {touch: collName, data: true, index: false}; + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/touch_index.js b/jstests/concurrency/fsm_workloads/touch_index.js index cc0b6fcf48d..b4e47835073 100644 --- a/jstests/concurrency/fsm_workloads/touch_index.js +++ b/jstests/concurrency/fsm_workloads/touch_index.js @@ -10,16 +10,10 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/touch_base.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { - $config.data.generateTouchCmdObj = function generateTouchCmdObj(collName) { - return { - touch: collName, - data: false, - index: true - }; - }; +var $config = extendWorkload($config, function($config, $super) { + $config.data.generateTouchCmdObj = function generateTouchCmdObj(collName) { + return {touch: collName, data: false, index: true}; + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/touch_no_data_no_index.js b/jstests/concurrency/fsm_workloads/touch_no_data_no_index.js index 25ce50fc5ac..14c3e81993d 100644 --- a/jstests/concurrency/fsm_workloads/touch_no_data_no_index.js +++ b/jstests/concurrency/fsm_workloads/touch_no_data_no_index.js @@ -10,22 +10,16 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/touch_base.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { - $config.data.generateTouchCmdObj = function generateTouchCmdObj(collName) { - return { - touch: collName, - data: false, - index: false - }; - }; +var $config = extendWorkload($config, function($config, $super) { + $config.data.generateTouchCmdObj = function generateTouchCmdObj(collName) { + return {touch: collName, data: false, index: false}; + }; - $config.states.touch = function touch(db, collName) { - var res = db.runCommand(this.generateTouchCmdObj(collName)); - // The command always fails because "index" and "data" are both false - assertAlways.commandFailed(res); - }; + $config.states.touch = function touch(db, collName) { + var res = db.runCommand(this.generateTouchCmdObj(collName)); + // The command always fails because "index" and "data" are both false + assertAlways.commandFailed(res); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/update_and_bulk_insert.js b/jstests/concurrency/fsm_workloads/update_and_bulk_insert.js index 5d59ff2b0ef..dde8b4b7093 100644 --- a/jstests/concurrency/fsm_workloads/update_and_bulk_insert.js +++ b/jstests/concurrency/fsm_workloads/update_and_bulk_insert.js @@ -31,10 +31,7 @@ var $config = (function() { } }; - var transitions = { - insert: {insert: 0.2, update: 0.8}, - update: {insert: 0.2, update: 0.8} - }; + var transitions = {insert: {insert: 0.2, update: 0.8}, update: {insert: 0.2, update: 0.8}}; return { threadCount: 5, diff --git a/jstests/concurrency/fsm_workloads/update_array.js b/jstests/concurrency/fsm_workloads/update_array.js index 192626c2430..2020ee3c60a 100644 --- a/jstests/concurrency/fsm_workloads/update_array.js +++ b/jstests/concurrency/fsm_workloads/update_array.js @@ -110,10 +110,7 @@ var $config = (function() { })(); - var transitions = { - push: {push: 0.8, pull: 0.2}, - pull: {push: 0.8, pull: 0.2} - }; + var transitions = {push: {push: 0.8, pull: 0.2}, pull: {push: 0.8, pull: 0.2}}; function setup(db, collName, cluster) { // index on 'arr', the field being updated diff --git a/jstests/concurrency/fsm_workloads/update_check_index.js b/jstests/concurrency/fsm_workloads/update_check_index.js index 3e099d6b2a5..bd82e39c471 100644 --- a/jstests/concurrency/fsm_workloads/update_check_index.js +++ b/jstests/concurrency/fsm_workloads/update_check_index.js @@ -15,14 +15,10 @@ var $config = (function() { db[collName].update({a: 1, b: 1}, {$set: {c: newC}}, {multi: true}); } - return { - multiUpdate: multiUpdate - }; + return {multiUpdate: multiUpdate}; })(); - var transitions = { - multiUpdate: {multiUpdate: 1.0} - }; + var transitions = {multiUpdate: {multiUpdate: 1.0}}; function setup(db, collName, cluster) { assertAlways.commandWorked(db[collName].ensureIndex({a: 1})); diff --git a/jstests/concurrency/fsm_workloads/update_inc.js b/jstests/concurrency/fsm_workloads/update_inc.js index f16d841d3bb..a8328c26703 100644 --- a/jstests/concurrency/fsm_workloads/update_inc.js +++ b/jstests/concurrency/fsm_workloads/update_inc.js @@ -27,9 +27,7 @@ var $config = (function() { }, update: function update(db, collName) { - var updateDoc = { - $inc: {} - }; + var updateDoc = {$inc: {}}; updateDoc.$inc[this.fieldName] = 1; var res = db[collName].update({_id: this.id}, updateDoc); @@ -74,16 +72,10 @@ var $config = (function() { } }; - var transitions = { - init: {update: 1}, - update: {find: 1}, - find: {update: 1} - }; + var transitions = {init: {update: 1}, update: {find: 1}, find: {update: 1}}; function setup(db, collName, cluster) { - var doc = { - _id: this.id - }; + var doc = {_id: this.id}; // Pre-populate the fields we need to avoid size change for capped collections. for (var i = 0; i < this.threadCount; ++i) { diff --git a/jstests/concurrency/fsm_workloads/update_multifield.js b/jstests/concurrency/fsm_workloads/update_multifield.js index 1f62472f754..7428c289c98 100644 --- a/jstests/concurrency/fsm_workloads/update_multifield.js +++ b/jstests/concurrency/fsm_workloads/update_multifield.js @@ -35,15 +35,9 @@ var $config = (function() { var push = Random.rand() > 0.2; var updateDoc = {}; - updateDoc[set ? '$set' : '$unset'] = { - x: x - }; - updateDoc[push ? '$push' : '$pull'] = { - y: y - }; - updateDoc.$inc = { - z: z - }; + updateDoc[set ? '$set' : '$unset'] = {x: x}; + updateDoc[push ? '$push' : '$pull'] = {y: y}; + updateDoc.$inc = {z: z}; return updateDoc; } @@ -61,9 +55,7 @@ var $config = (function() { } }; - var transitions = { - update: {update: 1} - }; + var transitions = {update: {update: 1}}; function setup(db, collName, cluster) { assertAlways.commandWorked(db[collName].ensureIndex({x: 1})); diff --git a/jstests/concurrency/fsm_workloads/update_multifield_isolated_multiupdate.js b/jstests/concurrency/fsm_workloads/update_multifield_isolated_multiupdate.js index 3dd8b584d98..8d95deac710 100644 --- a/jstests/concurrency/fsm_workloads/update_multifield_isolated_multiupdate.js +++ b/jstests/concurrency/fsm_workloads/update_multifield_isolated_multiupdate.js @@ -9,32 +9,30 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/update_multifield.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.multi = true; - $config.data.isolated = true; + $config.data.multi = true; + $config.data.isolated = true; - $config.data.assertResult = function assertResult(res, db, collName, query) { - assertAlways.eq(0, res.nUpserted, tojson(res)); - // documents can't move during an update, because we use $isolated - assertWhenOwnColl.eq(this.numDocs, res.nMatched, tojson(res)); - if (db.getMongo().writeMode() === 'commands') { - assertWhenOwnColl.eq(this.numDocs, res.nModified, tojson(res)); - } + $config.data.assertResult = function assertResult(res, db, collName, query) { + assertAlways.eq(0, res.nUpserted, tojson(res)); + // documents can't move during an update, because we use $isolated + assertWhenOwnColl.eq(this.numDocs, res.nMatched, tojson(res)); + if (db.getMongo().writeMode() === 'commands') { + assertWhenOwnColl.eq(this.numDocs, res.nModified, tojson(res)); + } - // every thread only increments z, and z starts at 0, - // so z should always be strictly greater than 0 after an update, - // even if other threads modify the doc. - var docs = db[collName].find().toArray(); - assertWhenOwnColl(function() { - docs.forEach(function(doc) { - assertWhenOwnColl.eq('number', typeof doc.z); - assertWhenOwnColl.gt(doc.z, 0); - }); - }); - }; + // every thread only increments z, and z starts at 0, + // so z should always be strictly greater than 0 after an update, + // even if other threads modify the doc. + var docs = db[collName].find().toArray(); + assertWhenOwnColl(function() { + docs.forEach(function(doc) { + assertWhenOwnColl.eq('number', typeof doc.z); + assertWhenOwnColl.gt(doc.z, 0); + }); + }); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/update_multifield_multiupdate.js b/jstests/concurrency/fsm_workloads/update_multifield_multiupdate.js index 2cc975085ca..2ca02e2f38e 100644 --- a/jstests/concurrency/fsm_workloads/update_multifield_multiupdate.js +++ b/jstests/concurrency/fsm_workloads/update_multifield_multiupdate.js @@ -12,40 +12,38 @@ load('jstests/concurrency/fsm_workloads/update_multifield.js'); // for $config // For isMongod and recordIdCanChangeOnUpdate. load('jstests/concurrency/fsm_workload_helpers/server_types.js'); -var $config = - extendWorkload($config, - function($config, $super) { - - $config.data.multi = true; - - $config.data.assertResult = function(res, db, collName, query) { - assertAlways.eq(0, res.nUpserted, tojson(res)); - - if (isMongod(db)) { - if (!recordIdCanChangeOnUpdate(db)) { - // If a document's RecordId cannot change, then we should not - // have updated any document more than once, since the update - // stage internally de-duplicates based on RecordId. - assertWhenOwnColl.lte(this.numDocs, res.nMatched, tojson(res)); - } else { - // If RecordIds can change, then there are no guarantees on how - // many documents were updated. - assertAlways.gte(res.nMatched, 0, tojson(res)); - } - } else { // mongos - assertAlways.gte(res.nMatched, 0, tojson(res)); - } - - if (db.getMongo().writeMode() === 'commands') { - assertWhenOwnColl.eq(res.nMatched, res.nModified, tojson(res)); - } - - var docs = db[collName].find().toArray(); - docs.forEach(function(doc) { - assertWhenOwnColl.eq('number', typeof doc.z); - assertWhenOwnColl.gt(doc.z, 0); - }); - }; - - return $config; - }); +var $config = extendWorkload($config, function($config, $super) { + + $config.data.multi = true; + + $config.data.assertResult = function(res, db, collName, query) { + assertAlways.eq(0, res.nUpserted, tojson(res)); + + if (isMongod(db)) { + if (!recordIdCanChangeOnUpdate(db)) { + // If a document's RecordId cannot change, then we should not + // have updated any document more than once, since the update + // stage internally de-duplicates based on RecordId. + assertWhenOwnColl.lte(this.numDocs, res.nMatched, tojson(res)); + } else { + // If RecordIds can change, then there are no guarantees on how + // many documents were updated. + assertAlways.gte(res.nMatched, 0, tojson(res)); + } + } else { // mongos + assertAlways.gte(res.nMatched, 0, tojson(res)); + } + + if (db.getMongo().writeMode() === 'commands') { + assertWhenOwnColl.eq(res.nMatched, res.nModified, tojson(res)); + } + + var docs = db[collName].find().toArray(); + docs.forEach(function(doc) { + assertWhenOwnColl.eq('number', typeof doc.z); + assertWhenOwnColl.gt(doc.z, 0); + }); + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/update_ordered_bulk_inc.js b/jstests/concurrency/fsm_workloads/update_ordered_bulk_inc.js index 0d6b4651a5d..45a079091e0 100644 --- a/jstests/concurrency/fsm_workloads/update_ordered_bulk_inc.js +++ b/jstests/concurrency/fsm_workloads/update_ordered_bulk_inc.js @@ -22,9 +22,7 @@ var $config = (function() { }, update: function update(db, collName) { - var updateDoc = { - $inc: {} - }; + var updateDoc = {$inc: {}}; updateDoc.$inc[this.fieldName] = 1; var bulk = db[collName].initializeOrderedBulkOp(); @@ -74,11 +72,7 @@ var $config = (function() { } }; - var transitions = { - init: {update: 1}, - update: {find: 1}, - find: {update: 1} - }; + var transitions = {init: {update: 1}, update: {find: 1}, find: {update: 1}}; function setup(db, collName, cluster) { this.count = 0; diff --git a/jstests/concurrency/fsm_workloads/update_rename.js b/jstests/concurrency/fsm_workloads/update_rename.js index b163b44f690..ca74ac5287d 100644 --- a/jstests/concurrency/fsm_workloads/update_rename.js +++ b/jstests/concurrency/fsm_workloads/update_rename.js @@ -20,15 +20,11 @@ var $config = (function() { var to = choose(fieldNames.filter(function(n) { return n !== from; })); - var updater = { - $rename: {} - }; + var updater = {$rename: {}}; updater.$rename[from] = to; var query = {}; - query[from] = { - $exists: 1 - }; + query[from] = {$exists: 1}; var res = db[collName].update(query, updater); @@ -40,9 +36,7 @@ var $config = (function() { } }; - var transitions = { - update: {update: 1} - }; + var transitions = {update: {update: 1}}; function setup(db, collName, cluster) { // Create an index on all but one fieldName key to make it possible to test renames diff --git a/jstests/concurrency/fsm_workloads/update_replace.js b/jstests/concurrency/fsm_workloads/update_replace.js index f7edb05126d..2d04f38294c 100644 --- a/jstests/concurrency/fsm_workloads/update_replace.js +++ b/jstests/concurrency/fsm_workloads/update_replace.js @@ -56,9 +56,7 @@ var $config = (function() { } }; - var transitions = { - update: {update: 1} - }; + var transitions = {update: {update: 1}}; function setup(db, collName, cluster) { assertAlways.commandWorked(db[collName].ensureIndex({a: 1})); diff --git a/jstests/concurrency/fsm_workloads/update_simple.js b/jstests/concurrency/fsm_workloads/update_simple.js index 85f877e6090..cb4adf926c9 100644 --- a/jstests/concurrency/fsm_workloads/update_simple.js +++ b/jstests/concurrency/fsm_workloads/update_simple.js @@ -24,10 +24,7 @@ var $config = (function() { } }; - var transitions = { - set: {set: 0.5, unset: 0.5}, - unset: {set: 0.5, unset: 0.5} - }; + var transitions = {set: {set: 0.5, unset: 0.5}, unset: {set: 0.5, unset: 0.5}}; function setup(db, collName, cluster) { // index on 'value', the field being updated @@ -83,13 +80,9 @@ var $config = (function() { var value = Random.randInt(5); var updater = {}; - updater[set ? '$set' : '$unset'] = { - value: value - }; + updater[set ? '$set' : '$unset'] = {value: value}; - var query = { - _id: docIndex - }; + var query = {_id: docIndex}; var res = this.doUpdate(db, collName, query, updater); this.assertResult(db, res); }, diff --git a/jstests/concurrency/fsm_workloads/update_simple_eval.js b/jstests/concurrency/fsm_workloads/update_simple_eval.js index 988c2e44ab3..f8b9115e455 100644 --- a/jstests/concurrency/fsm_workloads/update_simple_eval.js +++ b/jstests/concurrency/fsm_workloads/update_simple_eval.js @@ -12,24 +12,22 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/update_simple.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.doUpdate = function doUpdate(db, collName, query, updater) { - var evalResult = db.runCommand({ - eval: function(f, collName, query, updater) { - return tojson(f(db, collName, query, updater)); - }, - args: [$super.data.doUpdate, collName, query, updater], - nolock: this.nolock - }); - assertAlways.commandWorked(evalResult); - var res = JSON.parse(evalResult.retval); - return res; - }; + $config.data.doUpdate = function doUpdate(db, collName, query, updater) { + var evalResult = db.runCommand({ + eval: function(f, collName, query, updater) { + return tojson(f(db, collName, query, updater)); + }, + args: [$super.data.doUpdate, collName, query, updater], + nolock: this.nolock + }); + assertAlways.commandWorked(evalResult); + var res = JSON.parse(evalResult.retval); + return res; + }; - $config.data.nolock = false; + $config.data.nolock = false; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/update_simple_eval_nolock.js b/jstests/concurrency/fsm_workloads/update_simple_eval_nolock.js index 282e98a461d..c5f081088cd 100644 --- a/jstests/concurrency/fsm_workloads/update_simple_eval_nolock.js +++ b/jstests/concurrency/fsm_workloads/update_simple_eval_nolock.js @@ -8,10 +8,9 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/update_simple_eval.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.data.nolock = true; + $config.data.nolock = true; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/update_upsert_multi.js b/jstests/concurrency/fsm_workloads/update_upsert_multi.js index 96d83cb5115..61e7f84f2e9 100644 --- a/jstests/concurrency/fsm_workloads/update_upsert_multi.js +++ b/jstests/concurrency/fsm_workloads/update_upsert_multi.js @@ -51,13 +51,10 @@ var $config = (function() { // because docs with lower i are newer, so they have had fewer // opportunities to have n incremented.) var prevN = Infinity; - db[collName] - .find({tid: this.tid}) - .sort({i: 1}) - .forEach(function(doc) { - assertWhenOwnColl.gte(prevN, doc.n); - prevN = doc.n; - }); + db[collName].find({tid: this.tid}).sort({i: 1}).forEach(function(doc) { + assertWhenOwnColl.gte(prevN, doc.n); + prevN = doc.n; + }); } }; diff --git a/jstests/concurrency/fsm_workloads/update_where.js b/jstests/concurrency/fsm_workloads/update_where.js index d7ef045131f..614cbc86093 100644 --- a/jstests/concurrency/fsm_workloads/update_where.js +++ b/jstests/concurrency/fsm_workloads/update_where.js @@ -10,43 +10,38 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_where.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { - $config.data.randomBound = 10; - $config.data.generateDocumentToInsert = function generateDocumentToInsert() { - return { - tid: this.tid, - x: Random.randInt(this.randomBound) - }; - }; - - $config.states.update = function update(db, collName) { - var res = db[collName].update( - // Server-side JS does not support Random.randInt, so use Math.floor/random instead - { - $where: 'this.x === Math.floor(Math.random() * ' + this.randomBound + ') ' + - '&& this.tid === ' + this.tid - }, - {$set: {x: Random.randInt(this.randomBound)}}, - {multi: true}); - assertAlways.writeOK(res); - - if (db.getMongo().writeMode() === 'commands') { - assertWhenOwnColl.gte(res.nModified, 0); - assertWhenOwnColl.lte(res.nModified, this.insertedDocuments); - } - }; - - $config.transitions = { - insert: {insert: 0.2, update: 0.4, query: 0.4}, - update: {insert: 0.4, update: 0.2, query: 0.4}, - query: {insert: 0.4, update: 0.4, query: 0.2} - }; - - $config.setup = function setup(db, collName, cluster) { - /* no-op to prevent index from being created */ - }; - - return $config; - }); +var $config = extendWorkload($config, function($config, $super) { + $config.data.randomBound = 10; + $config.data.generateDocumentToInsert = function generateDocumentToInsert() { + return {tid: this.tid, x: Random.randInt(this.randomBound)}; + }; + + $config.states.update = function update(db, collName) { + var res = db[collName].update( + // Server-side JS does not support Random.randInt, so use Math.floor/random instead + { + $where: 'this.x === Math.floor(Math.random() * ' + this.randomBound + ') ' + + '&& this.tid === ' + this.tid + }, + {$set: {x: Random.randInt(this.randomBound)}}, + {multi: true}); + assertAlways.writeOK(res); + + if (db.getMongo().writeMode() === 'commands') { + assertWhenOwnColl.gte(res.nModified, 0); + assertWhenOwnColl.lte(res.nModified, this.insertedDocuments); + } + }; + + $config.transitions = { + insert: {insert: 0.2, update: 0.4, query: 0.4}, + update: {insert: 0.4, update: 0.2, query: 0.4}, + query: {insert: 0.4, update: 0.4, query: 0.2} + }; + + $config.setup = function setup(db, collName, cluster) { + /* no-op to prevent index from being created */ + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/upsert_where.js b/jstests/concurrency/fsm_workloads/upsert_where.js index 72ff542c572..7fa00727725 100644 --- a/jstests/concurrency/fsm_workloads/upsert_where.js +++ b/jstests/concurrency/fsm_workloads/upsert_where.js @@ -9,39 +9,34 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/indexed_insert_where.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { - $config.data.randomBound = 10; - $config.data.generateDocumentToInsert = function generateDocumentToInsert() { - return { - tid: this.tid, - x: Random.randInt(this.randomBound) - }; - }; +var $config = extendWorkload($config, function($config, $super) { + $config.data.randomBound = 10; + $config.data.generateDocumentToInsert = function generateDocumentToInsert() { + return {tid: this.tid, x: Random.randInt(this.randomBound)}; + }; - $config.states.upsert = function upsert(db, collName) { - var res = db[collName].update( - {$where: 'this.x === ' + this.randomBound + ' && this.tid === ' + this.tid}, - {$set: {x: Random.randInt(this.randomBound), tid: this.tid}}, - {upsert: true}); - assertWhenOwnColl.eq(res.nUpserted, 1); - var upsertedDocument = db[collName].findOne({_id: res.getUpsertedId()._id}); - assertWhenOwnColl(function() { - assertWhenOwnColl.eq(upsertedDocument.tid, this.tid); - }.bind(this)); - this.insertedDocuments += res.nUpserted; - }; + $config.states.upsert = function upsert(db, collName) { + var res = db[collName].update( + {$where: 'this.x === ' + this.randomBound + ' && this.tid === ' + this.tid}, + {$set: {x: Random.randInt(this.randomBound), tid: this.tid}}, + {upsert: true}); + assertWhenOwnColl.eq(res.nUpserted, 1); + var upsertedDocument = db[collName].findOne({_id: res.getUpsertedId()._id}); + assertWhenOwnColl(function() { + assertWhenOwnColl.eq(upsertedDocument.tid, this.tid); + }.bind(this)); + this.insertedDocuments += res.nUpserted; + }; - $config.transitions = { - insert: {insert: 0.2, upsert: 0.4, query: 0.4}, - upsert: {insert: 0.4, upsert: 0.2, query: 0.4}, - query: {insert: 0.4, upsert: 0.4, query: 0.2} - }; + $config.transitions = { + insert: {insert: 0.2, upsert: 0.4, query: 0.4}, + upsert: {insert: 0.4, upsert: 0.2, query: 0.4}, + query: {insert: 0.4, upsert: 0.4, query: 0.2} + }; - $config.setup = function setup(db, collName, cluster) { - /* no-op to prevent index from being created */ - }; + $config.setup = function setup(db, collName, cluster) { + /* no-op to prevent index from being created */ + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/yield.js b/jstests/concurrency/fsm_workloads/yield.js index 0ef6aa9b1a0..adbe1076ee6 100644 --- a/jstests/concurrency/fsm_workloads/yield.js +++ b/jstests/concurrency/fsm_workloads/yield.js @@ -44,9 +44,7 @@ var $config = (function() { */ genUpdateDoc: function genUpdateDoc() { var newVal = Random.randInt(this.nDocs); - return { - $set: {a: newVal} - }; + return {$set: {a: newVal}}; } }; diff --git a/jstests/concurrency/fsm_workloads/yield_and_hashed.js b/jstests/concurrency/fsm_workloads/yield_and_hashed.js index 48a14d706e2..f9267b9c020 100644 --- a/jstests/concurrency/fsm_workloads/yield_and_hashed.js +++ b/jstests/concurrency/fsm_workloads/yield_and_hashed.js @@ -9,67 +9,63 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/yield_rooted_or.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - /* - * Issue a query that will use the AND_HASH stage. This is a little tricky, so use - * stagedebug to force it to happen. Unfortunately this means it can't be batched. - */ - $config.states.query = function andHash(db, collName) { - var nMatches = 100; - assertAlways.lte(nMatches, this.nDocs); - // Construct the query plan: two ixscans under an andHashed. - // Scan c <= nMatches - var ixscan1 = { - ixscan: { - args: { - name: 'stages_and_hashed', - keyPattern: {c: 1}, - startKey: {'': nMatches}, - endKey: {}, - endKeyInclusive: true, - direction: -1 - } + /* + * Issue a query that will use the AND_HASH stage. This is a little tricky, so use + * stagedebug to force it to happen. Unfortunately this means it can't be batched. + */ + $config.states.query = function andHash(db, collName) { + var nMatches = 100; + assertAlways.lte(nMatches, this.nDocs); + // Construct the query plan: two ixscans under an andHashed. + // Scan c <= nMatches + var ixscan1 = { + ixscan: { + args: { + name: 'stages_and_hashed', + keyPattern: {c: 1}, + startKey: {'': nMatches}, + endKey: {}, + endKeyInclusive: true, + direction: -1 } - }; + } + }; - // Scan d >= this.nDocs - nMatches - var ixscan2 = { - ixscan: { - args: { - name: 'stages_and_hashed', - keyPattern: {d: 1}, - startKey: {'': this.nDocs - nMatches}, - endKey: {}, - endKeyInclusive: true, - direction: 1 - } + // Scan d >= this.nDocs - nMatches + var ixscan2 = { + ixscan: { + args: { + name: 'stages_and_hashed', + keyPattern: {d: 1}, + startKey: {'': this.nDocs - nMatches}, + endKey: {}, + endKeyInclusive: true, + direction: 1 } - }; - - var andix1ix2 = { - andHash: {args: {nodes: [ixscan1, ixscan2]}} - }; + } + }; - // On non-MMAP storage engines, index intersection plans will always re-filter - // the docs to make sure we don't get any spurious matches. - var fetch = { - fetch: { - filter: {c: {$lte: nMatches}, d: {$gte: (this.nDocs - nMatches)}}, - args: {node: andix1ix2} - } - }; + var andix1ix2 = {andHash: {args: {nodes: [ixscan1, ixscan2]}}}; - var res = db.runCommand({stageDebug: {plan: fetch, collection: collName}}); - assertAlways.commandWorked(res); - for (var i = 0; i < res.results.length; i++) { - var result = res.results[i]; - assertAlways.lte(result.c, nMatches); - assertAlways.gte(result.d, this.nDocs - nMatches); + // On non-MMAP storage engines, index intersection plans will always re-filter + // the docs to make sure we don't get any spurious matches. + var fetch = { + fetch: { + filter: {c: {$lte: nMatches}, d: {$gte: (this.nDocs - nMatches)}}, + args: {node: andix1ix2} } }; - return $config; - }); + var res = db.runCommand({stageDebug: {plan: fetch, collection: collName}}); + assertAlways.commandWorked(res); + for (var i = 0; i < res.results.length; i++) { + var result = res.results[i]; + assertAlways.lte(result.c, nMatches); + assertAlways.gte(result.d, this.nDocs - nMatches); + } + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/yield_and_sorted.js b/jstests/concurrency/fsm_workloads/yield_and_sorted.js index 2bea4226ba0..aed15988b10 100644 --- a/jstests/concurrency/fsm_workloads/yield_and_sorted.js +++ b/jstests/concurrency/fsm_workloads/yield_and_sorted.js @@ -9,62 +9,58 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/yield_rooted_or.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - /* - * Issue a query that will use the AND_SORTED stage. This is a little tricky, so use - * stagedebug to force it to happen. Unfortunately this means it can't be batched. - */ - $config.states.query = function andSorted(db, collName) { - // Not very many docs returned in this, so loop to increase chances of yielding in the - // middle. - for (var i = 0; i < 100; i++) { - // Construct the query plan: two ixscans under an andSorted. - // Scan a == 0 - var ixscan1 = { - ixscan: { - args: { - name: 'stages_and_sorted', - keyPattern: {c: 1}, - startKey: {'': 0}, - endKey: {'': 0}, - endKeyInclusive: false, - direction: 1 - } + /* + * Issue a query that will use the AND_SORTED stage. This is a little tricky, so use + * stagedebug to force it to happen. Unfortunately this means it can't be batched. + */ + $config.states.query = function andSorted(db, collName) { + // Not very many docs returned in this, so loop to increase chances of yielding in the + // middle. + for (var i = 0; i < 100; i++) { + // Construct the query plan: two ixscans under an andSorted. + // Scan a == 0 + var ixscan1 = { + ixscan: { + args: { + name: 'stages_and_sorted', + keyPattern: {c: 1}, + startKey: {'': 0}, + endKey: {'': 0}, + endKeyInclusive: false, + direction: 1 } - }; - // Scan b == this.nDocs - var ixscan2 = { - ixscan: { - args: { - name: 'stages_and_sorted', - keyPattern: {d: 1}, - startKey: {'': this.nDocs}, - endKey: {'': this.nDocs}, - endKeyInclusive: false, - direction: -1 - } + } + }; + // Scan b == this.nDocs + var ixscan2 = { + ixscan: { + args: { + name: 'stages_and_sorted', + keyPattern: {d: 1}, + startKey: {'': this.nDocs}, + endKey: {'': this.nDocs}, + endKeyInclusive: false, + direction: -1 } - }; - - // Intersect the two - var andix1ix2 = { - andSorted: {args: {nodes: [ixscan1, ixscan2]}} - }; - var res = db.runCommand({stageDebug: {collection: collName, plan: andix1ix2}}); - assertAlways.commandWorked(res); - for (var j = 0; j < res.results.length; j++) { - var result = res.results[j]; - // These should always be true, since they're just verifying that the results - // match - // the query predicate. - assertAlways.eq(result.c, 0); - assertAlways.eq(result.d, this.nDocs); } + }; + + // Intersect the two + var andix1ix2 = {andSorted: {args: {nodes: [ixscan1, ixscan2]}}}; + var res = db.runCommand({stageDebug: {collection: collName, plan: andix1ix2}}); + assertAlways.commandWorked(res); + for (var j = 0; j < res.results.length; j++) { + var result = res.results[j]; + // These should always be true, since they're just verifying that the results + // match + // the query predicate. + assertAlways.eq(result.c, 0); + assertAlways.eq(result.d, this.nDocs); } - }; + } + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/yield_fetch.js b/jstests/concurrency/fsm_workloads/yield_fetch.js index b3f47a5fe5d..e802635af73 100644 --- a/jstests/concurrency/fsm_workloads/yield_fetch.js +++ b/jstests/concurrency/fsm_workloads/yield_fetch.js @@ -9,24 +9,22 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/yield_rooted_or.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - /* - * Issue a query that will use the FETCH stage. - */ - $config.states.query = function fetch(db, collName) { - var nMatches = 100; + /* + * Issue a query that will use the FETCH stage. + */ + $config.states.query = function fetch(db, collName) { + var nMatches = 100; - var cursor = db[collName].find({c: {$lt: nMatches}}).batchSize(this.batchSize); + var cursor = db[collName].find({c: {$lt: nMatches}}).batchSize(this.batchSize); - var verifier = function fetchVerifier(doc, prevDoc) { - return doc.c < nMatches; - }; - - this.advanceCursor(cursor, verifier); + var verifier = function fetchVerifier(doc, prevDoc) { + return doc.c < nMatches; }; - return $config; - }); + this.advanceCursor(cursor, verifier); + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/yield_geo_near.js b/jstests/concurrency/fsm_workloads/yield_geo_near.js index fd13bd31014..3ed79835906 100644 --- a/jstests/concurrency/fsm_workloads/yield_geo_near.js +++ b/jstests/concurrency/fsm_workloads/yield_geo_near.js @@ -8,80 +8,69 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/yield.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - /* - * Use geo $near query to find points near the origin. Note this should be done using the - * geoNear command, rather than a $near query, as the $near query doesn't work in a sharded - * environment. Unfortunately this means we cannot batch the request. - */ - $config.states.query = function geoNear(db, collName) { - // This distance gets about 80 docs around the origin. There is one doc inserted - // every 1m^2 and the area scanned by a 5m radius is PI*(5m)^2 ~ 79. - var maxDistance = 5; + /* + * Use geo $near query to find points near the origin. Note this should be done using the + * geoNear command, rather than a $near query, as the $near query doesn't work in a sharded + * environment. Unfortunately this means we cannot batch the request. + */ + $config.states.query = function geoNear(db, collName) { + // This distance gets about 80 docs around the origin. There is one doc inserted + // every 1m^2 and the area scanned by a 5m radius is PI*(5m)^2 ~ 79. + var maxDistance = 5; - var res = db.runCommand({geoNear: collName, near: [0, 0], maxDistance: maxDistance}); - assertWhenOwnColl.commandWorked(res); // Could fail if more than 1 2d index. - assertWhenOwnColl(function verifyResults() { - var results = res.results; - var prevDoc = { - dis: 0 - }; // distance should never be less than 0 - for (var i = 0; i < results.length; i++) { - var doc = results[i]; - assertAlways.lte(NumberInt(doc.dis), maxDistance); // satisfies query - assertAlways.lte(prevDoc.dis, doc.dis); // returned in the correct order - prevDoc = doc; - } - }); - }; + var res = db.runCommand({geoNear: collName, near: [0, 0], maxDistance: maxDistance}); + assertWhenOwnColl.commandWorked(res); // Could fail if more than 1 2d index. + assertWhenOwnColl(function verifyResults() { + var results = res.results; + var prevDoc = {dis: 0}; // distance should never be less than 0 + for (var i = 0; i < results.length; i++) { + var doc = results[i]; + assertAlways.lte(NumberInt(doc.dis), maxDistance); // satisfies query + assertAlways.lte(prevDoc.dis, doc.dis); // returned in the correct order + prevDoc = doc; + } + }); + }; - $config.data.genUpdateDoc = function genUpdateDoc() { - var P = Math.floor(Math.sqrt(this.nDocs)); + $config.data.genUpdateDoc = function genUpdateDoc() { + var P = Math.floor(Math.sqrt(this.nDocs)); - // Move the point to another location within the PxP grid. - var newX = Random.randInt(P) - P / 2; - var newY = Random.randInt(P) - P / 2; - return { - $set: {geo: [newX, newY]} - }; - }; + // Move the point to another location within the PxP grid. + var newX = Random.randInt(P) - P / 2; + var newY = Random.randInt(P) - P / 2; + return {$set: {geo: [newX, newY]}}; + }; - $config.data.getIndexSpec = function getIndexSpec() { - return { - geo: '2d' - }; - }; + $config.data.getIndexSpec = function getIndexSpec() { + return {geo: '2d'}; + }; - $config.data.getReplaceSpec = function getReplaceSpec(i, coords) { - return { - _id: i, - geo: coords - }; - }; + $config.data.getReplaceSpec = function getReplaceSpec(i, coords) { + return {_id: i, geo: coords}; + }; - /* - * Insert some docs in geo form and make a 2d index. - */ - $config.setup = function setup(db, collName, cluster) { - $super.setup.apply(this, arguments); + /* + * Insert some docs in geo form and make a 2d index. + */ + $config.setup = function setup(db, collName, cluster) { + $super.setup.apply(this, arguments); - var P = Math.floor(Math.sqrt(this.nDocs)); - var i = 0; - // Set up some points to query (in a PxP grid around 0,0). - var bulk = db[collName].initializeUnorderedBulkOp(); - for (var x = 0; x < P; x++) { - for (var y = 0; y < P; y++) { - var coords = [x - P / 2, y - P / 2]; - bulk.find({_id: i}).upsert().replaceOne(this.getReplaceSpec(i, coords)); - i++; - } + var P = Math.floor(Math.sqrt(this.nDocs)); + var i = 0; + // Set up some points to query (in a PxP grid around 0,0). + var bulk = db[collName].initializeUnorderedBulkOp(); + for (var x = 0; x < P; x++) { + for (var y = 0; y < P; y++) { + var coords = [x - P / 2, y - P / 2]; + bulk.find({_id: i}).upsert().replaceOne(this.getReplaceSpec(i, coords)); + i++; } - assertAlways.writeOK(bulk.execute()); - assertAlways.commandWorked(db[collName].ensureIndex(this.getIndexSpec())); - }; + } + assertAlways.writeOK(bulk.execute()); + assertAlways.commandWorked(db[collName].ensureIndex(this.getIndexSpec())); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/yield_geo_near_dedup.js b/jstests/concurrency/fsm_workloads/yield_geo_near_dedup.js index 5efd9cf7242..9f3476873f7 100644 --- a/jstests/concurrency/fsm_workloads/yield_geo_near_dedup.js +++ b/jstests/concurrency/fsm_workloads/yield_geo_near_dedup.js @@ -8,92 +8,78 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/yield_geo_near.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - $config.states.remove = function remove(db, collName) { - var id = Random.randInt(this.nDocs); - var doc = db[collName].findOne({_id: id}); - if (doc !== null) { - var res = db[collName].remove({_id: id}); - assertAlways.writeOK(res); - if (res.nRemoved > 0) { - // Re-insert the document with the same '_id', but an incremented - // 'timesInserted' to - // distinguish it from the deleted document. - doc.timesInserted++; - assertAlways.writeOK(db[collName].insert(doc)); - } + $config.states.remove = function remove(db, collName) { + var id = Random.randInt(this.nDocs); + var doc = db[collName].findOne({_id: id}); + if (doc !== null) { + var res = db[collName].remove({_id: id}); + assertAlways.writeOK(res); + if (res.nRemoved > 0) { + // Re-insert the document with the same '_id', but an incremented + // 'timesInserted' to + // distinguish it from the deleted document. + doc.timesInserted++; + assertAlways.writeOK(db[collName].insert(doc)); } - }; + } + }; - /* - * Use geo $nearSphere query to find points near the origin. Note this should be done using - *the - * geoNear command, rather than a $nearSphere query, as the $nearSphere query doesn't work - *in a - * sharded environment. Unfortunately this means we cannot batch the request. - * - * Only points are covered in this test as there is no guarantee that geometries indexed in - * multiple cells will be deduplicated correctly with interspersed updates. If multiple - *index - * cells for the same geometry occur in the same search interval, an update may cause - *geoNear - * to return the same document multiple times. - */ - $config.states.query = function geoNear(db, collName) { - // This distance gets about 80 docs around the origin. There is one doc inserted - // every 1m^2 and the area scanned by a 5m radius is PI*(5m)^2 ~ 79. - var maxDistance = 5; + /* + * Use geo $nearSphere query to find points near the origin. Note this should be done using + *the + * geoNear command, rather than a $nearSphere query, as the $nearSphere query doesn't work + *in a + * sharded environment. Unfortunately this means we cannot batch the request. + * + * Only points are covered in this test as there is no guarantee that geometries indexed in + * multiple cells will be deduplicated correctly with interspersed updates. If multiple + *index + * cells for the same geometry occur in the same search interval, an update may cause + *geoNear + * to return the same document multiple times. + */ + $config.states.query = function geoNear(db, collName) { + // This distance gets about 80 docs around the origin. There is one doc inserted + // every 1m^2 and the area scanned by a 5m radius is PI*(5m)^2 ~ 79. + var maxDistance = 5; - var res = db.runCommand( - {geoNear: collName, near: [0, 0], maxDistance: maxDistance, spherical: true}); - assertWhenOwnColl.commandWorked(res); - assertWhenOwnColl(function verifyResults() { - var results = res.results; - var seenObjs = []; - for (var i = 0; i < results.length; i++) { - var doc = results[i].obj; + var res = db.runCommand( + {geoNear: collName, near: [0, 0], maxDistance: maxDistance, spherical: true}); + assertWhenOwnColl.commandWorked(res); + assertWhenOwnColl(function verifyResults() { + var results = res.results; + var seenObjs = []; + for (var i = 0; i < results.length; i++) { + var doc = results[i].obj; - // The pair (_id, timesInserted) is the smallest set of attributes that uniquely - // identifies a document. - var objToSearchFor = { - _id: doc._id, - timesInserted: doc.timesInserted - }; - var found = seenObjs.some(function(obj) { - return bsonWoCompare(obj, objToSearchFor) === 0; - }); - assertWhenOwnColl(!found, - 'geoNear command returned the document ' + tojson(doc) + - ' multiple times: ' + tojson(seenObjs)); - seenObjs.push(objToSearchFor); - } - }); - }; + // The pair (_id, timesInserted) is the smallest set of attributes that uniquely + // identifies a document. + var objToSearchFor = {_id: doc._id, timesInserted: doc.timesInserted}; + var found = seenObjs.some(function(obj) { + return bsonWoCompare(obj, objToSearchFor) === 0; + }); + assertWhenOwnColl(!found, + 'geoNear command returned the document ' + tojson(doc) + + ' multiple times: ' + tojson(seenObjs)); + seenObjs.push(objToSearchFor); + } + }); + }; - $config.data.genUpdateDoc = function genUpdateDoc() { - // Attempts to perform an in-place update to trigger an invalidation on MMAP v1. - return { - $inc: {timesUpdated: 1} - }; - }; + $config.data.genUpdateDoc = function genUpdateDoc() { + // Attempts to perform an in-place update to trigger an invalidation on MMAP v1. + return {$inc: {timesUpdated: 1}}; + }; - $config.data.getIndexSpec = function getIndexSpec() { - return { - geo: '2dsphere' - }; - }; + $config.data.getIndexSpec = function getIndexSpec() { + return {geo: '2dsphere'}; + }; - $config.data.getReplaceSpec = function getReplaceSpec(i, coords) { - return { - _id: i, - geo: coords, - timesUpdated: 0, - timesInserted: 0 - }; - }; + $config.data.getReplaceSpec = function getReplaceSpec(i, coords) { + return {_id: i, geo: coords, timesUpdated: 0, timesInserted: 0}; + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/yield_id_hack.js b/jstests/concurrency/fsm_workloads/yield_id_hack.js index 0d50eb7d350..eddb653c1d8 100644 --- a/jstests/concurrency/fsm_workloads/yield_id_hack.js +++ b/jstests/concurrency/fsm_workloads/yield_id_hack.js @@ -9,26 +9,25 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/yield.js'); // for $config -var $config = extendWorkload($config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - /* - * Issue a query that will use the ID_HACK stage. This cannot be - * batched, so issue a - * number of them to increase the chances of yielding between - * getting the key and looking - * up its value. - */ - $config.states.query = function idHack(db, collName) { - var nQueries = 100; - for (var i = 0; i < nQueries; i++) { - assertAlways.lte(db[collName].find({_id: i}).itcount(), 1); - var res = db[collName].findOne({_id: i}); - if (res !== null) { - assertAlways.eq(i, res._id); - } - } - }; + /* + * Issue a query that will use the ID_HACK stage. This cannot be + * batched, so issue a + * number of them to increase the chances of yielding between + * getting the key and looking + * up its value. + */ + $config.states.query = function idHack(db, collName) { + var nQueries = 100; + for (var i = 0; i < nQueries; i++) { + assertAlways.lte(db[collName].find({_id: i}).itcount(), 1); + var res = db[collName].findOne({_id: i}); + if (res !== null) { + assertAlways.eq(i, res._id); + } + } + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/yield_rooted_or.js b/jstests/concurrency/fsm_workloads/yield_rooted_or.js index f7dd0dcffdf..2d21427b42b 100644 --- a/jstests/concurrency/fsm_workloads/yield_rooted_or.js +++ b/jstests/concurrency/fsm_workloads/yield_rooted_or.js @@ -10,41 +10,37 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/yield.js'); // for $config -var $config = - extendWorkload($config, - function($config, $super) { - - /* - * Issue a query with an or stage as the root. - */ - $config.states.query = function rootedOr(db, collName) { - var nMatches = 100; - - var cursor = db[collName].find({ - $or: [{c: {$lte: nMatches / 2}}, {d: {$lte: nMatches / 2}}] - }).batchSize(this.batchSize); - - var verifier = function rootedOrVerifier(doc, prevDoc) { - return (doc.c <= nMatches / 2 || doc.d <= nMatches / 2); - }; - - this.advanceCursor(cursor, verifier); - }; - - $config.data.genUpdateDoc = function genUpdateDoc() { - var newC = Random.randInt(this.nDocs); - var newD = Random.randInt(this.nDocs); - return { - $set: {c: newC, d: newD} - }; - }; - - $config.setup = function setup(db, collName, cluster) { - $super.setup.apply(this, arguments); - - assertAlways.commandWorked(db[collName].ensureIndex({c: 1})); - assertAlways.commandWorked(db[collName].ensureIndex({d: 1})); - }; - - return $config; - }); +var $config = extendWorkload($config, function($config, $super) { + + /* + * Issue a query with an or stage as the root. + */ + $config.states.query = function rootedOr(db, collName) { + var nMatches = 100; + + var cursor = db[collName] + .find({$or: [{c: {$lte: nMatches / 2}}, {d: {$lte: nMatches / 2}}]}) + .batchSize(this.batchSize); + + var verifier = function rootedOrVerifier(doc, prevDoc) { + return (doc.c <= nMatches / 2 || doc.d <= nMatches / 2); + }; + + this.advanceCursor(cursor, verifier); + }; + + $config.data.genUpdateDoc = function genUpdateDoc() { + var newC = Random.randInt(this.nDocs); + var newD = Random.randInt(this.nDocs); + return {$set: {c: newC, d: newD}}; + }; + + $config.setup = function setup(db, collName, cluster) { + $super.setup.apply(this, arguments); + + assertAlways.commandWorked(db[collName].ensureIndex({c: 1})); + assertAlways.commandWorked(db[collName].ensureIndex({d: 1})); + }; + + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/yield_sort.js b/jstests/concurrency/fsm_workloads/yield_sort.js index d0d905177f8..1c535ae6415 100644 --- a/jstests/concurrency/fsm_workloads/yield_sort.js +++ b/jstests/concurrency/fsm_workloads/yield_sort.js @@ -9,37 +9,33 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/yield_sort_merge.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { +var $config = extendWorkload($config, function($config, $super) { - /* - * Execute a query that will use the SORT stage. - */ - $config.states.query = function sort(db, collName) { - var nMatches = 100; - // Sort on c, since it's not an indexed field. - var cursor = - db[collName].find({a: {$lt: nMatches}}).sort({c: -1}).batchSize(this.batchSize); + /* + * Execute a query that will use the SORT stage. + */ + $config.states.query = function sort(db, collName) { + var nMatches = 100; + // Sort on c, since it's not an indexed field. + var cursor = + db[collName].find({a: {$lt: nMatches}}).sort({c: -1}).batchSize(this.batchSize); - var verifier = function sortVerifier(doc, prevDoc) { - var correctOrder = true; - if (prevDoc !== null) { - correctOrder = (doc.c <= prevDoc.c); - } - return doc.a < nMatches && correctOrder; - }; - - this.advanceCursor(cursor, verifier); + var verifier = function sortVerifier(doc, prevDoc) { + var correctOrder = true; + if (prevDoc !== null) { + correctOrder = (doc.c <= prevDoc.c); + } + return doc.a < nMatches && correctOrder; }; - $config.data.genUpdateDoc = function genUpdateDoc() { - var newA = Random.randInt(this.nDocs); - var newC = Random.randInt(this.nDocs); - return { - $set: {a: newA, c: newC} - }; - }; + this.advanceCursor(cursor, verifier); + }; + + $config.data.genUpdateDoc = function genUpdateDoc() { + var newA = Random.randInt(this.nDocs); + var newC = Random.randInt(this.nDocs); + return {$set: {a: newA, c: newC}}; + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/yield_sort_merge.js b/jstests/concurrency/fsm_workloads/yield_sort_merge.js index c46163df492..d715a813701 100644 --- a/jstests/concurrency/fsm_workloads/yield_sort_merge.js +++ b/jstests/concurrency/fsm_workloads/yield_sort_merge.js @@ -10,49 +10,44 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/yield.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { - - /* - * Execute a query that will use the SORT_MERGE stage. - */ - $config.states.query = function sortMerge(db, collName) { - var nMatches = 50; // Don't push this too high, or SORT_MERGE stage won't be selected. - - // Build an array [0, nMatches). - var matches = []; - for (var i = 0; i < nMatches; i++) { - matches.push(i); +var $config = extendWorkload($config, function($config, $super) { + + /* + * Execute a query that will use the SORT_MERGE stage. + */ + $config.states.query = function sortMerge(db, collName) { + var nMatches = 50; // Don't push this too high, or SORT_MERGE stage won't be selected. + + // Build an array [0, nMatches). + var matches = []; + for (var i = 0; i < nMatches; i++) { + matches.push(i); + } + + var cursor = db[collName].find({a: {$in: matches}}).sort({b: -1}).batchSize(this.batchSize); + + var verifier = function sortMergeVerifier(doc, prevDoc) { + var correctOrder = true; + if (prevDoc !== null) { + correctOrder = (doc.b <= prevDoc.b); } - - var cursor = - db[collName].find({a: {$in: matches}}).sort({b: -1}).batchSize(this.batchSize); - - var verifier = function sortMergeVerifier(doc, prevDoc) { - var correctOrder = true; - if (prevDoc !== null) { - correctOrder = (doc.b <= prevDoc.b); - } - return doc.a < nMatches && correctOrder; - }; - - this.advanceCursor(cursor, verifier); + return doc.a < nMatches && correctOrder; }; - $config.data.genUpdateDoc = function genUpdateDoc() { - var newA = Random.randInt(this.nDocs); - var newB = Random.randInt(this.nDocs); - return { - $set: {a: newA, b: newB} - }; - }; + this.advanceCursor(cursor, verifier); + }; - $config.setup = function setup(db, collName, cluster) { - $super.setup.apply(this, arguments); + $config.data.genUpdateDoc = function genUpdateDoc() { + var newA = Random.randInt(this.nDocs); + var newB = Random.randInt(this.nDocs); + return {$set: {a: newA, b: newB}}; + }; - assertAlways.commandWorked(db[collName].ensureIndex({a: 1, b: 1})); - }; + $config.setup = function setup(db, collName, cluster) { + $super.setup.apply(this, arguments); + + assertAlways.commandWorked(db[collName].ensureIndex({a: 1, b: 1})); + }; - return $config; - }); + return $config; +}); diff --git a/jstests/concurrency/fsm_workloads/yield_text.js b/jstests/concurrency/fsm_workloads/yield_text.js index 9291c25e527..0ccf5b8a7d4 100644 --- a/jstests/concurrency/fsm_workloads/yield_text.js +++ b/jstests/concurrency/fsm_workloads/yield_text.js @@ -9,47 +9,42 @@ load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload load('jstests/concurrency/fsm_workloads/yield.js'); // for $config -var $config = extendWorkload( - $config, - function($config, $super) { - - /* - * Pick a random word and search for it using full text search. - */ - $config.states.query = function text(db, collName) { - var word = this.words[Random.randInt(this.words.length)]; - - var cursor = db[collName].find({ - $text: {$search: word}, - yield_text: {$exists: true} - }).batchSize(this.batchSize); - - var verifier = function textVerifier(doc, prevDoc) { - return doc.yield_text.indexOf(word) !== -1; - }; - - // If we don't have the right text index, or someone drops our text index, this - // assertion - // is either pointless or won't work. So only verify the results when we know no one - // else - // is messing with our indices. - assertWhenOwnColl(function verifyTextResults() { - this.advanceCursor(cursor, verifier); - }.bind(this)); - }; +var $config = extendWorkload($config, function($config, $super) { - $config.data.genUpdateDoc = function genUpdateDoc() { - var newWord = this.words[Random.randInt(this.words.length)]; - return { - $set: {yield_text: newWord} - }; - }; + /* + * Pick a random word and search for it using full text search. + */ + $config.states.query = function text(db, collName) { + var word = this.words[Random.randInt(this.words.length)]; - $config.setup = function setup(db, collName, cluster) { - $super.setup.apply(this, arguments); + var cursor = db[collName] + .find({$text: {$search: word}, yield_text: {$exists: true}}) + .batchSize(this.batchSize); - assertWhenOwnColl.commandWorked(db[collName].ensureIndex({yield_text: 'text'})); + var verifier = function textVerifier(doc, prevDoc) { + return doc.yield_text.indexOf(word) !== -1; }; - return $config; - }); + // If we don't have the right text index, or someone drops our text index, this + // assertion + // is either pointless or won't work. So only verify the results when we know no one + // else + // is messing with our indices. + assertWhenOwnColl(function verifyTextResults() { + this.advanceCursor(cursor, verifier); + }.bind(this)); + }; + + $config.data.genUpdateDoc = function genUpdateDoc() { + var newWord = this.words[Random.randInt(this.words.length)]; + return {$set: {yield_text: newWord}}; + }; + + $config.setup = function setup(db, collName, cluster) { + $super.setup.apply(this, arguments); + + assertWhenOwnColl.commandWorked(db[collName].ensureIndex({yield_text: 'text'})); + }; + + return $config; +}); diff --git a/jstests/core/apitest_db.js b/jstests/core/apitest_db.js index 2713a6cfd24..be90b9eb877 100644 --- a/jstests/core/apitest_db.js +++ b/jstests/core/apitest_db.js @@ -73,9 +73,9 @@ assert.docEq(validStorageEngineOptions, // The indexOptionDefaults must be a document that contains only a storageEngine field. db.idxOptions.drop(); assert.commandFailed(db.createCollection('idxOptions', {indexOptionDefaults: 'not a document'})); -assert.commandFailed(db.createCollection('idxOptions', - {indexOptionDefaults: {unknownOption: true}}), - 'created a collection with an unknown option to indexOptionDefaults'); +assert.commandFailed( + db.createCollection('idxOptions', {indexOptionDefaults: {unknownOption: true}}), + 'created a collection with an unknown option to indexOptionDefaults'); assert.commandWorked(db.createCollection('idxOptions', {indexOptionDefaults: {}}), 'should have been able to specify an empty object for indexOptionDefaults'); assert(db.idxOptions.drop()); @@ -99,9 +99,7 @@ assert.commandFailed( var alternateStorageEngine = db.serverBuildInfo().storageEngines.find(engine => engine !== storageEngineName); if (alternateStorageEngine) { - var indexOptions = { - storageEngine: {[alternateStorageEngine]: {}} - }; + var indexOptions = {storageEngine: {[alternateStorageEngine]: {}}}; assert.commandWorked(db.createCollection('idxOptions', {indexOptionDefaults: indexOptions}), 'should have been able to configure a non-active storage engine'); assert(db.idxOptions.drop()); diff --git a/jstests/core/apitest_dbcollection.js b/jstests/core/apitest_dbcollection.js index 8f0129319f7..ac30128b90e 100644 --- a/jstests/core/apitest_dbcollection.js +++ b/jstests/core/apitest_dbcollection.js @@ -214,9 +214,7 @@ assert.eq(0, db.getCollection("test_db").getIndexes().length, "24"); } // indexDetailsKey - show indexDetails results for this index key only. - var indexKey = { - a: 1 - }; + var indexKey = {a: 1}; var indexName = getIndexName(indexKey); checkIndexDetails({indexDetails: true, indexDetailsKey: indexKey}, indexName); diff --git a/jstests/core/apply_ops1.js b/jstests/core/apply_ops1.js index 8a19caa9f23..96840f125e9 100644 --- a/jstests/core/apply_ops1.js +++ b/jstests/core/apply_ops1.js @@ -156,10 +156,7 @@ assert.eq(1, t.find().count(), "Duplicate insert failed"); assert.eq(true, a.results[0], "Bad result value for duplicate insert"); - var o = { - _id: 5, - x: 17 - }; + var o = {_id: 5, x: 17}; assert.eq(o, t.findOne(), "Mismatching document inserted."); var res = db.runCommand({ @@ -243,8 +240,9 @@ res = t.getIndexes(); assert.eq(1, res.filter(function(element, index, array) { - return element.name == 'a_1'; - }).length, + return element.name == 'a_1'; + }) + .length, 'Foreground index not found in listIndexes result: ' + tojson(res)); // Background indexes are created in the foreground when processed by applyOps. @@ -265,7 +263,8 @@ res = t.getIndexes(); assert.eq(1, res.filter(function(element, index, array) { - return element.name == 'b_1'; - }).length, + return element.name == 'b_1'; + }) + .length, 'Background index not found in listIndexes result: ' + tojson(res)); })(); diff --git a/jstests/core/array4.js b/jstests/core/array4.js index c6fe1599880..fe131a04ca9 100644 --- a/jstests/core/array4.js +++ b/jstests/core/array4.js @@ -5,9 +5,7 @@ t.drop(); t.insert({"a": ["1", "2", "3"]}); t.insert({"a": ["2", "1"]}); -var x = { - 'a.0': /1/ -}; +var x = {'a.0': /1/}; assert.eq(t.count(x), 1); diff --git a/jstests/core/array_match4.js b/jstests/core/array_match4.js index 4956fc1d8b2..b4cdec5143a 100644 --- a/jstests/core/array_match4.js +++ b/jstests/core/array_match4.js @@ -3,9 +3,7 @@ var t = db.array_match4; t.drop(); t.save({a: [1, 2]}); -var query_gte = { - a: {$gte: [1, 2]} -}; +var query_gte = {a: {$gte: [1, 2]}}; // // without index diff --git a/jstests/core/arrayfind7.js b/jstests/core/arrayfind7.js index f0dc2e2caa8..699f8c9586d 100644 --- a/jstests/core/arrayfind7.js +++ b/jstests/core/arrayfind7.js @@ -36,10 +36,9 @@ checkElemMatch({'a.b.c': 1}, {a: {$elemMatch: {b: {$elemMatch: {c: {$gte: 1, $in: [2]}}}}}}); // Two nested $elemMatch expressions. -checkElemMatch( - {'a.d.e': 1, 'a.b.c': 1}, - {a: [{b: [{c: 1}], d: [{e: 1}]}]}, - {a: {$elemMatch: {d: {$elemMatch: {e: {$lte: 1}}}, b: {$elemMatch: {c: {$gte: 1}}}}}}); +checkElemMatch({'a.d.e': 1, 'a.b.c': 1}, {a: [{b: [{c: 1}], d: [{e: 1}]}]}, { + a: {$elemMatch: {d: {$elemMatch: {e: {$lte: 1}}}, b: {$elemMatch: {c: {$gte: 1}}}}} +}); // A non $elemMatch expression and a nested $elemMatch expression. checkElemMatch({'a.x': 1, 'a.b.c': 1}, diff --git a/jstests/core/arrayfind8.js b/jstests/core/arrayfind8.js index d322229a298..a687351b554 100644 --- a/jstests/core/arrayfind8.js +++ b/jstests/core/arrayfind8.js @@ -77,20 +77,14 @@ function checkQuery(subQuery, bothMatch, elemMatch, nonElemMatch, additionalCons // Construct standard and elemMatch queries from subQuery. firstSubQueryKey = Object.keySet(subQuery)[0]; if (firstSubQueryKey[0] == '$') { - standardQuery = { - $and: [{a: subQuery}, additionalConstraints] - }; + standardQuery = {$and: [{a: subQuery}, additionalConstraints]}; } else { // If the subQuery contains a field rather than operators, append to the 'a' field. modifiedSubQuery = {}; modifiedSubQuery['a.' + firstSubQueryKey] = subQuery[firstSubQueryKey]; - standardQuery = { - $and: [modifiedSubQuery, additionalConstraints] - }; + standardQuery = {$and: [modifiedSubQuery, additionalConstraints]}; } - elemMatchQuery = { - $and: [{a: {$elemMatch: subQuery}}, additionalConstraints] - }; + elemMatchQuery = {$and: [{a: {$elemMatch: subQuery}}, additionalConstraints]}; debug(elemMatchQuery); function maySave(aValue) { diff --git a/jstests/core/basic3.js b/jstests/core/basic3.js index ec0b48ec0cf..2fa26627bf9 100644 --- a/jstests/core/basic3.js +++ b/jstests/core/basic3.js @@ -35,7 +35,6 @@ t.update({"a": 0}, {$set: {"c.c": 1}}); t.update({"a": 0}, {$inc: {"c.c": 1}}); // edge cases -assert.throws(doBadUpdate, - [{a: 0}, {"": {"b.b": 1}}], - "must deny '' embedded '.' in key of update"); +assert.throws( + doBadUpdate, [{a: 0}, {"": {"b.b": 1}}], "must deny '' embedded '.' in key of update"); t.update({"a": 0}, {}); diff --git a/jstests/core/basic9.js b/jstests/core/basic9.js index bebaeb54740..6d368f46e3b 100644 --- a/jstests/core/basic9.js +++ b/jstests/core/basic9.js @@ -14,6 +14,5 @@ t.save({foo$foo: 5}); t.save({foo$: 5}); assert.throws(doBadSave, [{$foo: 5}], "key names aren't allowed to start with $ doesn't work"); -assert.throws(doBadSave, - [{x: {$foo: 5}}], - "embedded key names aren't allowed to start with $ doesn't work"); +assert.throws( + doBadSave, [{x: {$foo: 5}}], "embedded key names aren't allowed to start with $ doesn't work"); diff --git a/jstests/core/batch_size.js b/jstests/core/batch_size.js index eca41e412ba..3dfbe0face6 100644 --- a/jstests/core/batch_size.js +++ b/jstests/core/batch_size.js @@ -95,12 +95,7 @@ while (bigStr.length < 1000000) { // Insert enough documents to exceed the 32 MB in-memory sort limit. for (var i = 0; i < 40; i++) { - var doc = { - x: 1, - y: 1, - z: i, - big: bigStr - }; + var doc = {x: 1, y: 1, z: i, big: bigStr}; t.insert(doc); } diff --git a/jstests/core/big_object1.js b/jstests/core/big_object1.js index 017fcdc9756..8029cbb868f 100644 --- a/jstests/core/big_object1.js +++ b/jstests/core/big_object1.js @@ -11,10 +11,7 @@ if (db.adminCommand("buildinfo").bits == 64) { x = 0; while (true) { var result; - n = { - _id: x, - a: [] - }; + n = {_id: x, a: []}; for (i = 0; i < 14 + x; i++) n.a.push(s); try { diff --git a/jstests/core/bittest.js b/jstests/core/bittest.js index 45559d8f505..0a54215ee60 100644 --- a/jstests/core/bittest.js +++ b/jstests/core/bittest.js @@ -144,14 +144,13 @@ assertQueryCorrect({a: {$bitsAnyClear: BinData(0, "////////////////////////////")}}, 3); // Tests with multiple predicates. - assertQueryCorrect( - { - a: { - $bitsAllSet: BinData(0, "AANgAAAAAAAAAAAAAAAAAAAAAAAA"), - $bitsAllClear: BinData(0, "//yf////////////////////////") - } - }, - 1); + assertQueryCorrect({ + a: { + $bitsAllSet: BinData(0, "AANgAAAAAAAAAAAAAAAAAAAAAAAA"), + $bitsAllClear: BinData(0, "//yf////////////////////////") + } + }, + 1); coll.drop(); })();
\ No newline at end of file diff --git a/jstests/core/capped6.js b/jstests/core/capped6.js index d7b8a60985a..e94e7ea44e8 100644 --- a/jstests/core/capped6.js +++ b/jstests/core/capped6.js @@ -38,9 +38,7 @@ var c = ""; for (i = 0; i < maxDocuments; ++i, c += "-") { // The a values are strings of increasing length. - valueArray[i] = { - a: c - }; + valueArray[i] = {a: c}; } if (shouldReverse) { valueArray.reverse(); diff --git a/jstests/core/collation_shell_helpers.js b/jstests/core/collation_shell_helpers.js index 99dda6047b1..e9308960164 100644 --- a/jstests/core/collation_shell_helpers.js +++ b/jstests/core/collation_shell_helpers.js @@ -47,49 +47,46 @@ db.createCollection("collation_shell_helpers", {collation: {locale: "fr_CA"}})); var collectionInfos = db.getCollectionInfos({name: "collation_shell_helpers"}); assert.eq(collectionInfos.length, 1); - assert.eq(collectionInfos[0].options.collation, - { - locale: "fr_CA", - caseLevel: false, - caseFirst: "off", - strength: 3, - numericOrdering: false, - alternate: "non-ignorable", - maxVariable: "punct", - normalization: false, - backwards: true - }); + assert.eq(collectionInfos[0].options.collation, { + locale: "fr_CA", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: true + }); // Ensure that an index with no collation inherits the collection-default collation. assert.commandWorked(coll.ensureIndex({a: 1})); - assertIndexHasCollation({a: 1}, - { - locale: "fr_CA", - caseLevel: false, - caseFirst: "off", - strength: 3, - numericOrdering: false, - alternate: "non-ignorable", - maxVariable: "punct", - normalization: false, - backwards: true - }); + assertIndexHasCollation({a: 1}, { + locale: "fr_CA", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: true + }); // Ensure that an index which specifies an overriding collation does not use the collection // default. assert.commandWorked(coll.ensureIndex({b: 1}, {collation: {locale: "en_US"}})); - assertIndexHasCollation({b: 1}, - { - locale: "en_US", - caseLevel: false, - caseFirst: "off", - strength: 3, - numericOrdering: false, - alternate: "non-ignorable", - maxVariable: "punct", - normalization: false, - backwards: false - }); + assertIndexHasCollation({b: 1}, { + locale: "en_US", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: false + }); coll.drop(); @@ -106,58 +103,54 @@ assert.commandFailed(coll.ensureIndex({a: 1}, {collation: {locale: "en", strength: 99}})); assert.commandWorked(coll.ensureIndex({a: 1}, {collation: {locale: "en_US"}})); - assertIndexHasCollation({a: 1}, - { - locale: "en_US", - caseLevel: false, - caseFirst: "off", - strength: 3, - numericOrdering: false, - alternate: "non-ignorable", - maxVariable: "punct", - normalization: false, - backwards: false - }); + assertIndexHasCollation({a: 1}, { + locale: "en_US", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: false + }); assert.commandWorked(coll.createIndex({b: 1}, {collation: {locale: "en_US"}})); - assertIndexHasCollation({b: 1}, - { - locale: "en_US", - caseLevel: false, - caseFirst: "off", - strength: 3, - numericOrdering: false, - alternate: "non-ignorable", - maxVariable: "punct", - normalization: false, - backwards: false - }); + assertIndexHasCollation({b: 1}, { + locale: "en_US", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: false + }); assert.commandWorked(coll.createIndexes([{c: 1}, {d: 1}], {collation: {locale: "fr_CA"}})); - assertIndexHasCollation({c: 1}, - { - locale: "fr_CA", - caseLevel: false, - caseFirst: "off", - strength: 3, - numericOrdering: false, - alternate: "non-ignorable", - maxVariable: "punct", - normalization: false, - backwards: true - }); - assertIndexHasCollation({d: 1}, - { - locale: "fr_CA", - caseLevel: false, - caseFirst: "off", - strength: 3, - numericOrdering: false, - alternate: "non-ignorable", - maxVariable: "punct", - normalization: false, - backwards: true - }); + assertIndexHasCollation({c: 1}, { + locale: "fr_CA", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: true + }); + assertIndexHasCollation({d: 1}, { + locale: "fr_CA", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: true + }); // TODO SERVER-23791: Test that queries with matching collations can use these indices, and that // the indices contain collator-generated comparison keys rather than the verbatim indexed @@ -172,21 +165,8 @@ assert.writeOK(coll.insert({_id: 2, str: "bar"})); // Aggregation. - assert.eq(2, - coll.aggregate([], - { - collation : { - locale: - "fr" - } - }).itcount()); - assert.commandWorked(coll.explain().aggregate([], - { - collation : { - locale: - "fr" - } - })); + assert.eq(2, coll.aggregate([], {collation: {locale: "fr"}}).itcount()); + assert.commandWorked(coll.explain().aggregate([], {collation: {locale: "fr"}})); // Count command. assert.eq(0, coll.find({str: "FOO"}).count()); @@ -236,28 +216,24 @@ assert.commandWorked(coll.find().collation({locale: "fr"}).explain()); // findAndModify. - assert.eq({_id: 2, str: "baz"}, - coll.findAndModify({ - query: {str: "bar"}, - update: {$set: {str: "baz"}}, new: true, - collation: {locale: "fr"} - })); - assert.commandWorked(coll.explain().findAndModify({ + assert.eq({_id: 2, str: "baz"}, coll.findAndModify({ query: {str: "bar"}, - update: {$set: {str: "baz"}}, new: true, + update: {$set: {str: "baz"}}, + new: true, collation: {locale: "fr"} })); + assert.commandWorked(coll.explain().findAndModify( + {query: {str: "bar"}, update: {$set: {str: "baz"}}, new: true, collation: {locale: "fr"}})); // Group. - assert.eq([{str: "foo", count: 1}, {str: "baz", count: 1}], - coll.group({ - key: {str: 1}, - initial: {count: 0}, - reduce: function(curr, result) { - result.count += 1; - }, - collation: {locale: "fr"} - })); + assert.eq([{str: "foo", count: 1}, {str: "baz", count: 1}], coll.group({ + key: {str: 1}, + initial: {count: 0}, + reduce: function(curr, result) { + result.count += 1; + }, + collation: {locale: "fr"} + })); assert.commandWorked(coll.explain().group({ key: {str: 1}, initial: {count: 0}, @@ -323,79 +299,95 @@ // String field not indexed. assert.commandWorked(coll.ensureIndex({geo: "2dsphere"})); assert.eq(0, - assert.commandWorked(db.runCommand({ - geoNear: coll.getName(), - near: {type: "Point", coordinates: [0, 0]}, - spherical: true, - query: {str: "ABC"} - })).results.length); + assert + .commandWorked(db.runCommand({ + geoNear: coll.getName(), + near: {type: "Point", coordinates: [0, 0]}, + spherical: true, + query: {str: "ABC"} + })) + .results.length); assert.eq(1, - assert.commandWorked(db.runCommand({ - geoNear: coll.getName(), - near: {type: "Point", coordinates: [0, 0]}, - spherical: true, - query: {str: "ABC"}, - collation: {locale: "en_US", strength: 2} - })).results.length); + assert + .commandWorked(db.runCommand({ + geoNear: coll.getName(), + near: {type: "Point", coordinates: [0, 0]}, + spherical: true, + query: {str: "ABC"}, + collation: {locale: "en_US", strength: 2} + })) + .results.length); // String field indexed without collation. assert.commandWorked(coll.dropIndexes()); assert.commandWorked(coll.ensureIndex({geo: "2dsphere", str: 1})); assert.eq(0, - assert.commandWorked(db.runCommand({ - geoNear: coll.getName(), - near: {type: "Point", coordinates: [0, 0]}, - spherical: true, - query: {str: "ABC"} - })).results.length); + assert + .commandWorked(db.runCommand({ + geoNear: coll.getName(), + near: {type: "Point", coordinates: [0, 0]}, + spherical: true, + query: {str: "ABC"} + })) + .results.length); assert.eq(1, - assert.commandWorked(db.runCommand({ - geoNear: coll.getName(), - near: {type: "Point", coordinates: [0, 0]}, - spherical: true, - query: {str: "ABC"}, - collation: {locale: "en_US", strength: 2} - })).results.length); + assert + .commandWorked(db.runCommand({ + geoNear: coll.getName(), + near: {type: "Point", coordinates: [0, 0]}, + spherical: true, + query: {str: "ABC"}, + collation: {locale: "en_US", strength: 2} + })) + .results.length); // String field indexed with non-matching collation. assert.commandWorked(coll.dropIndexes()); assert.commandWorked( coll.ensureIndex({geo: "2dsphere", str: 1}, {collation: {locale: "en_US", strength: 3}})); assert.eq(0, - assert.commandWorked(db.runCommand({ - geoNear: coll.getName(), - near: {type: "Point", coordinates: [0, 0]}, - spherical: true, - query: {str: "ABC"} - })).results.length); + assert + .commandWorked(db.runCommand({ + geoNear: coll.getName(), + near: {type: "Point", coordinates: [0, 0]}, + spherical: true, + query: {str: "ABC"} + })) + .results.length); assert.eq(1, - assert.commandWorked(db.runCommand({ - geoNear: coll.getName(), - near: {type: "Point", coordinates: [0, 0]}, - spherical: true, - query: {str: "ABC"}, - collation: {locale: "en_US", strength: 2} - })).results.length); + assert + .commandWorked(db.runCommand({ + geoNear: coll.getName(), + near: {type: "Point", coordinates: [0, 0]}, + spherical: true, + query: {str: "ABC"}, + collation: {locale: "en_US", strength: 2} + })) + .results.length); // String field indexed with matching collation. assert.commandWorked(coll.dropIndexes()); assert.commandWorked( coll.ensureIndex({geo: "2dsphere", str: 1}, {collation: {locale: "en_US", strength: 2}})); assert.eq(0, - assert.commandWorked(db.runCommand({ - geoNear: coll.getName(), - near: {type: "Point", coordinates: [0, 0]}, - spherical: true, - query: {str: "ABC"} - })).results.length); + assert + .commandWorked(db.runCommand({ + geoNear: coll.getName(), + near: {type: "Point", coordinates: [0, 0]}, + spherical: true, + query: {str: "ABC"} + })) + .results.length); assert.eq(1, - assert.commandWorked(db.runCommand({ - geoNear: coll.getName(), - near: {type: "Point", coordinates: [0, 0]}, - spherical: true, - query: {str: "ABC"}, - collation: {locale: "en_US", strength: 2} - })).results.length); + assert + .commandWorked(db.runCommand({ + geoNear: coll.getName(), + near: {type: "Point", coordinates: [0, 0]}, + spherical: true, + query: {str: "ABC"}, + collation: {locale: "en_US", strength: 2} + })) + .results.length); coll.drop(); @@ -407,14 +399,15 @@ assert.commandWorked(coll.ensureIndex({geo: "2dsphere"})); assert.eq(0, coll.find({ - str: "ABC", - geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} - }).itcount()); + str: "ABC", + geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} + }) + .itcount()); assert.eq(1, coll.find({ - str: "ABC", - geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} - }) + str: "ABC", + geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} + }) .collation({locale: "en_US", strength: 2}) .itcount()); @@ -423,14 +416,15 @@ assert.commandWorked(coll.ensureIndex({geo: "2dsphere", str: 1})); assert.eq(0, coll.find({ - str: "ABC", - geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} - }).itcount()); + str: "ABC", + geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} + }) + .itcount()); assert.eq(1, coll.find({ - str: "ABC", - geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} - }) + str: "ABC", + geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} + }) .collation({locale: "en_US", strength: 2}) .itcount()); @@ -440,14 +434,15 @@ {collation: {locale: "en_US", strength: 3}})); assert.eq(0, coll.find({ - str: "ABC", - geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} - }).itcount()); + str: "ABC", + geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} + }) + .itcount()); assert.eq(1, coll.find({ - str: "ABC", - geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} - }) + str: "ABC", + geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} + }) .collation({locale: "en_US", strength: 2}) .itcount()); @@ -457,14 +452,15 @@ {collation: {locale: "en_US", strength: 2}})); assert.eq(0, coll.find({ - str: "ABC", - geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} - }).itcount()); + str: "ABC", + geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} + }) + .itcount()); assert.eq(1, coll.find({ - str: "ABC", - geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} - }) + str: "ABC", + geo: {$nearSphere: {$geometry: {type: "Point", coordinates: [0, 0]}}} + }) .collation({locale: "en_US", strength: 2}) .itcount()); @@ -684,11 +680,8 @@ } else { assert.throws(function() { coll.bulkWrite([{ - replaceOne: { - filter: {str: "foo"}, - replacement: {str: "bar"}, - collation: {locale: "fr"} - } + replaceOne: + {filter: {str: "foo"}, replacement: {str: "bar"}, collation: {locale: "fr"}} }]); }); } diff --git a/jstests/core/commands_that_do_not_write_do_not_accept_wc.js b/jstests/core/commands_that_do_not_write_do_not_accept_wc.js index 3faab189bcb..ef5f8762a42 100644 --- a/jstests/core/commands_that_do_not_write_do_not_accept_wc.js +++ b/jstests/core/commands_that_do_not_write_do_not_accept_wc.js @@ -22,9 +22,7 @@ }); }, reduce: function(key, values) { - return { - count: values.length - }; + return {count: values.length}; }, out: {inline: 1} }); diff --git a/jstests/core/connection_status.js b/jstests/core/connection_status.js index 728e3d8a131..47aab3f0f43 100644 --- a/jstests/core/connection_status.js +++ b/jstests/core/connection_status.js @@ -70,14 +70,8 @@ } function test(userName) { - var user = { - user: userName, - db: dbName - }; - var role = { - role: "root", - db: "admin" - }; + var user = {user: userName, db: dbName}; + var role = {role: "root", db: "admin"}; myDB.createUser({user: userName, pwd: "weak password", roles: [role]}); myDB.auth(userName, "weak password"); diff --git a/jstests/core/constructors.js b/jstests/core/constructors.js index 814766ee2c3..34e6cbed9a6 100644 --- a/jstests/core/constructors.js +++ b/jstests/core/constructors.js @@ -12,10 +12,7 @@ function addConstructorsWithNew(constructorList) { // We use slice(0) here to make a copy of our lists var validWithNew = valid.concat(valid.slice(0).map(prependNew)); var invalidWithNew = invalid.concat(invalid.slice(0).map(prependNew)); - return { - "valid": validWithNew, - "invalid": invalidWithNew - }; + return {"valid": validWithNew, "invalid": invalidWithNew}; } function clientEvalConstructorTest(constructorList) { @@ -142,12 +139,22 @@ var dbpointerConstructors = { }; var objectidConstructors = { - "valid": ['ObjectId()', 'ObjectId("FFFFFFFFFFFFFFFFFFFFFFFF")', ], - "invalid": ['ObjectId(5)', 'ObjectId("FFFFFFFFFFFFFFFFFFFFFFFQ")', ] + "valid": [ + 'ObjectId()', + 'ObjectId("FFFFFFFFFFFFFFFFFFFFFFFF")', + ], + "invalid": [ + 'ObjectId(5)', + 'ObjectId("FFFFFFFFFFFFFFFFFFFFFFFQ")', + ] }; var timestampConstructors = { - "valid": ['Timestamp()', 'Timestamp(0,0)', 'Timestamp(1.0,1.0)', ], + "valid": [ + 'Timestamp()', + 'Timestamp(0,0)', + 'Timestamp(1.0,1.0)', + ], "invalid": [ 'Timestamp(0)', 'Timestamp(0,0,0)', @@ -161,7 +168,9 @@ var timestampConstructors = { }; var bindataConstructors = { - "valid": ['BinData(0,"test")', ], + "valid": [ + 'BinData(0,"test")', + ], "invalid": [ 'BinData(0,"test", "test")', 'BinData()', @@ -178,7 +187,9 @@ var bindataConstructors = { }; var uuidConstructors = { - "valid": ['UUID("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")', ], + "valid": [ + 'UUID("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")', + ], "invalid": [ 'UUID("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0)', 'UUID()', @@ -195,7 +206,9 @@ var uuidConstructors = { }; var md5Constructors = { - "valid": ['MD5("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")', ], + "valid": [ + 'MD5("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")', + ], "invalid": [ 'MD5("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0)', 'MD5()', @@ -238,7 +251,13 @@ var hexdataConstructors = { }; var dateConstructors = { - "valid": ['Date()', 'Date(0)', 'Date(0,0)', 'Date(0,0,0)', 'Date("foo")', ], + "valid": [ + 'Date()', + 'Date(0)', + 'Date(0,0)', + 'Date(0,0,0)', + 'Date("foo")', + ], "invalid": [] }; diff --git a/jstests/core/convert_to_capped_nonexistant.js b/jstests/core/convert_to_capped_nonexistant.js index a09ce553788..08996087da7 100644 --- a/jstests/core/convert_to_capped_nonexistant.js +++ b/jstests/core/convert_to_capped_nonexistant.js @@ -7,9 +7,8 @@ testDb.dropDatabase(); // Database does not exist here var result = testDb.runCommand({convertToCapped: 'foo', size: 1024}); assert.eq(result.ok, 0, "converting a nonexistent to capped worked and should not have"); -assert.eq(result.code, - 26, - "converting a nonexistent database to capped failed, but code has changed"); +assert.eq( + result.code, 26, "converting a nonexistent database to capped failed, but code has changed"); assert.eq(result.errmsg, "database convert_to_capped_nonexistent not found", "converting a nonexistent to capped failed, but message has changed"); @@ -19,9 +18,8 @@ testDb.coll.insert({}); var result = testDb.runCommand({convertToCapped: 'foo', size: 1024}); assert.eq(result.ok, 0, "converting a nonexistent to capped worked and should not have"); -assert.eq(result.code, - 26, - "converting a nonexistent collection to capped failed, but code has changed"); +assert.eq( + result.code, 26, "converting a nonexistent collection to capped failed, but code has changed"); assert.eq(result.errmsg, "source collection convert_to_capped_nonexistent.foo does not exist", "converting a nonexistent to capped failed, but message has changed"); diff --git a/jstests/core/count11.js b/jstests/core/count11.js index 4ce218bfc43..aeda1e4b1cf 100644 --- a/jstests/core/count11.js +++ b/jstests/core/count11.js @@ -5,12 +5,8 @@ var t = db.count11; t.drop(); -var validQuery = { - a: 1 -}; -var invalidQuery = { - a: {$invalid: 1} -}; +var validQuery = {a: 1}; +var invalidQuery = {a: {$invalid: 1}}; // Query non-existing collection with empty query. assert.eq(0, t.find().count()); diff --git a/jstests/core/create_indexes.js b/jstests/core/create_indexes.js index 3e069d7478e..a6cdb99ea89 100644 --- a/jstests/core/create_indexes.js +++ b/jstests/core/create_indexes.js @@ -114,9 +114,11 @@ res = t.runCommand("createIndexes", {indexes: [{key: {"c": 1}, sparse: true, name: "c_1"}]}); assert.eq(6, t.getIndexes().length); assert.eq(1, - t.getIndexes().filter(function(z) { - return z.sparse; - }).length); + t.getIndexes() + .filter(function(z) { + return z.sparse; + }) + .length); res = t.runCommand("createIndexes", {indexes: [{key: {"x": "foo"}, name: "x_1"}]}); assert(!res.ok); diff --git a/jstests/core/crud_api.js b/jstests/core/crud_api.js index f6cc77025c3..c9dbfb40c85 100644 --- a/jstests/core/crud_api.js +++ b/jstests/core/crud_api.js @@ -32,9 +32,7 @@ if (db.getMongo().writeMode() === 'commands') { assert.docEq(first, second); } else { - var overrideModifiedCount = { - modifiedCount: undefined - }; + var overrideModifiedCount = {modifiedCount: undefined}; assert.docEq(Object.merge(first, overrideModifiedCount), Object.merge(second, overrideModifiedCount)); } diff --git a/jstests/core/currentop_predicate.js b/jstests/core/currentop_predicate.js index 98df3c9756e..73b8a006588 100644 --- a/jstests/core/currentop_predicate.js +++ b/jstests/core/currentop_predicate.js @@ -1,22 +1,20 @@ // Tests the use of a match predicate with the currentOp command. (function() { // Test a $where predicate that matches the currentOp operation we are running. - var res = db.adminCommand("currentOp", - { - $where: function() { - return true; - } - }); + var res = db.adminCommand("currentOp", { + $where: function() { + return true; + } + }); assert.commandWorked(res); assert.gt(res.inprog.length, 0, tojson(res)); // Test a $where predicate that matches no operations. - res = db.adminCommand("currentOp", - { - $where: function() { - return false; - } - }); + res = db.adminCommand("currentOp", { + $where: function() { + return false; + } + }); assert.commandWorked(res); assert.eq(res.inprog.length, 0, tojson(res)); })(); diff --git a/jstests/core/cursor5.js b/jstests/core/cursor5.js index 64158eaccec..0232b92e4cc 100644 --- a/jstests/core/cursor5.js +++ b/jstests/core/cursor5.js @@ -24,16 +24,8 @@ function testBoundsWithSubobjectIndexes(db) { ]; for (i = 0; i < z.length; ++i) r.save(z[i]); - idx = { - "a.d": 1, - a: 1, - e: -1 - }; - rIdx = { - "a.d": -1, - a: -1, - e: 1 - }; + idx = {"a.d": 1, a: 1, e: -1}; + rIdx = {"a.d": -1, a: -1, e: 1}; r.ensureIndex(idx); checkResults([z[0], z[4], z[2]], r.find({e: 4}).sort(idx).hint(idx)); diff --git a/jstests/core/cursor6.js b/jstests/core/cursor6.js index f793d37bfe5..d373e952b2d 100644 --- a/jstests/core/cursor6.js +++ b/jstests/core/cursor6.js @@ -8,14 +8,9 @@ function eq(one, two) { function check(indexed) { var hint; if (indexed) { - hint = { - a: 1, - b: -1 - }; + hint = {a: 1, b: -1}; } else { - hint = { - $natural: 1 - }; + hint = {$natural: 1}; } f = r.find().sort({a: 1, b: 1}).hint(hint); diff --git a/jstests/core/cursor7.js b/jstests/core/cursor7.js index 6e77a144ba3..7807dbe22f5 100644 --- a/jstests/core/cursor7.js +++ b/jstests/core/cursor7.js @@ -15,14 +15,8 @@ function testMultipleInequalities(db) { z = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}]; for (i = 0; i < z.length; ++i) r.save(z[i]); - idx = { - a: 1, - b: 1 - }; - rIdx = { - a: -1, - b: -1 - }; + idx = {a: 1, b: 1}; + rIdx = {a: -1, b: -1}; r.ensureIndex(idx); checkResults([z[2], z[3]], r.find({a: {$gt: 3}}).sort(idx).hint(idx)); @@ -33,35 +27,27 @@ function testMultipleInequalities(db) { checkResults([z[2]], r.find({a: {$gt: 3, $lt: 7}}).sort(rIdx).hint(idx)); checkResults([z[2]], r.find({a: {$gt: 3, $lt: 7, $lte: 5}}).sort(rIdx).hint(idx)); - checkResults([z[1], z[2]], - r.find({ - a: {$gt: 1, $lt: 7, $gte: 3, $lte: 5}, - b: {$gt: 2, $lt: 8, $gte: 4, $lte: 6} - }) - .sort(idx) - .hint(idx)); - checkResults([z[2], z[1]], - r.find({ - a: {$gt: 1, $lt: 7, $gte: 3, $lte: 5}, - b: {$gt: 2, $lt: 8, $gte: 4, $lte: 6} - }) - .sort(rIdx) - .hint(idx)); - - checkResults([z[1], z[2]], - r.find({ - a: {$gte: 1, $lte: 7, $gt: 2, $lt: 6}, - b: {$gte: 2, $lte: 8, $gt: 3, $lt: 7} - }) - .sort(idx) - .hint(idx)); - checkResults([z[2], z[1]], - r.find({ - a: {$gte: 1, $lte: 7, $gt: 2, $lt: 6}, - b: {$gte: 2, $lte: 8, $gt: 3, $lt: 7} - }) - .sort(rIdx) - .hint(idx)); + checkResults( + [z[1], z[2]], + r.find({a: {$gt: 1, $lt: 7, $gte: 3, $lte: 5}, b: {$gt: 2, $lt: 8, $gte: 4, $lte: 6}}) + .sort(idx) + .hint(idx)); + checkResults( + [z[2], z[1]], + r.find({a: {$gt: 1, $lt: 7, $gte: 3, $lte: 5}, b: {$gt: 2, $lt: 8, $gte: 4, $lte: 6}}) + .sort(rIdx) + .hint(idx)); + + checkResults( + [z[1], z[2]], + r.find({a: {$gte: 1, $lte: 7, $gt: 2, $lt: 6}, b: {$gte: 2, $lte: 8, $gt: 3, $lt: 7}}) + .sort(idx) + .hint(idx)); + checkResults( + [z[2], z[1]], + r.find({a: {$gte: 1, $lte: 7, $gt: 2, $lt: 6}, b: {$gte: 2, $lte: 8, $gt: 3, $lt: 7}}) + .sort(rIdx) + .hint(idx)); } testMultipleInequalities(db); diff --git a/jstests/core/cursora.js b/jstests/core/cursora.js index dfd9e28f281..1ee0a6d3e69 100644 --- a/jstests/core/cursora.js +++ b/jstests/core/cursora.js @@ -24,11 +24,11 @@ function run(n, atomic) { try { start = new Date(); num = t.find(function() { - num = 2; - for (var x = 0; x < 1000; x++) - num += 2; - return num > 0; - }) + num = 2; + for (var x = 0; x < 1000; x++) + num += 2; + return num > 0; + }) .sort({_id: -1}) .itcount(); end = new Date(); diff --git a/jstests/core/datasize2.js b/jstests/core/datasize2.js index 6cb5b9b10d9..eb79b12a6c4 100644 --- a/jstests/core/datasize2.js +++ b/jstests/core/datasize2.js @@ -15,12 +15,8 @@ coll.insert({_id: i, s: "asdasdasdasdasdasdasd"}); } - var dataSizeCommand = { - "dataSize": "test.foo", - "keyPattern": {"_id": 1}, - "min": {"_id": 0}, - "max": {"_id": N} - }; + var dataSizeCommand = + {"dataSize": "test.foo", "keyPattern": {"_id": 1}, "min": {"_id": 0}, "max": {"_id": N}}; assert.eq(N, db.runCommand(dataSizeCommand).numObjects, diff --git a/jstests/core/date2.js b/jstests/core/date2.js index 2980f10bf7a..15993815b14 100644 --- a/jstests/core/date2.js +++ b/jstests/core/date2.js @@ -5,9 +5,7 @@ t.drop(); t.ensureIndex({a: 1}); -var obj = { - a: new Timestamp(0, 1) -}; // in old versions this was == to new Date(1) +var obj = {a: new Timestamp(0, 1)}; // in old versions this was == to new Date(1) t.save(obj); assert.eq(0, t.find({a: {$gt: new Date(1)}}).itcount()); assert.eq(1, t.find(obj).itcount()); diff --git a/jstests/core/depth_limit.js b/jstests/core/depth_limit.js index ddb648b4586..4e40c114369 100644 --- a/jstests/core/depth_limit.js +++ b/jstests/core/depth_limit.js @@ -17,9 +17,7 @@ function test() { function objWithDepth(depth) { var out = 1; while (depth--) { - out = { - o: out - }; + out = {o: out}; } return out; } diff --git a/jstests/core/distinct_index1.js b/jstests/core/distinct_index1.js index 31faecd376e..026fdca4e0a 100644 --- a/jstests/core/distinct_index1.js +++ b/jstests/core/distinct_index1.js @@ -11,10 +11,7 @@ function d(k, q) { } for (i = 0; i < 1000; i++) { - o = { - a: r(i * 5), - b: r(i) - }; + o = {a: r(i * 5), b: r(i)}; t.insert(o); } diff --git a/jstests/core/doc_validation_invalid_validators.js b/jstests/core/doc_validation_invalid_validators.js index aeebae42820..b78b31c0977 100644 --- a/jstests/core/doc_validation_invalid_validators.js +++ b/jstests/core/doc_validation_invalid_validators.js @@ -23,8 +23,8 @@ assert.commandFailed( db.getSiblingDB("admin").createCollection(collName, {validator: {a: {$exists: true}}})); if (!db.runCommand("isdbgrid").isdbgrid) { - assert.commandFailed(db.getSiblingDB("local") - .createCollection(collName, {validator: {a: {$exists: true}}})); + assert.commandFailed( + db.getSiblingDB("local").createCollection(collName, {validator: {a: {$exists: true}}})); } assert.commandFailed( db.getSiblingDB("config").createCollection(collName, {validator: {a: {$exists: true}}})); diff --git a/jstests/core/dropdb_race.js b/jstests/core/dropdb_race.js index b4666ecc3ad..bd5e7e5ddba 100644 --- a/jstests/core/dropdb_race.js +++ b/jstests/core/dropdb_race.js @@ -14,7 +14,7 @@ var start = new Date(); for (var pass = 0; pass < 100; pass++) { if (pass % 2 == 0) { // sometimes wait for create db first, to vary the timing of things - var options = ( pass % 4 == 0 )? { writeConcern: { fsync: true }} : undefined; + var options = (pass % 4 == 0) ? {writeConcern: {fsync: true}} : undefined; t.insert({}, options); } t.insert({x: 1}); diff --git a/jstests/core/elemMatchProjection.js b/jstests/core/elemMatchProjection.js index 97d1be0f081..e7aa5194607 100644 --- a/jstests/core/elemMatchProjection.js +++ b/jstests/core/elemMatchProjection.js @@ -47,9 +47,8 @@ assert.eq(1, t.find({group: 3, 'x.a': 2}, {'x.$': 1}).toArray()[0].x.length, "single object match (array length match)"); -assert.eq(2, - t.find({group: 3, 'x.a': 1}, {'x.$': 1}).toArray()[0].x[0].b, - "single object match first"); +assert.eq( + 2, t.find({group: 3, 'x.a': 1}, {'x.$': 1}).toArray()[0].x[0].b, "single object match first"); assert.eq(undefined, t.find({group: 3, 'x.a': 2}, {_id: 0, 'x.$': 1}).toArray()[0]._id, @@ -149,9 +148,8 @@ if (false) { // // SERVER-2238: $elemMatch projections // -assert.eq(-6, - t.find({group: 4}, {x: {$elemMatch: {a: -6}}}).toArray()[0].x[0].a, - "single object match"); +assert.eq( + -6, t.find({group: 4}, {x: {$elemMatch: {a: -6}}}).toArray()[0].x[0].a, "single object match"); assert.eq(1, t.find({group: 4}, {x: {$elemMatch: {a: -6}}}).toArray()[0].x.length, @@ -184,9 +182,8 @@ assert.eq([1], // but this may become a user assertion, since a single element of an array can't match more than // one value -assert.eq([1], - t.find({group: 1}, {x: {$elemMatch: {$all: [1]}}}).toArray()[0].x, - "$in number match"); +assert.eq( + [1], t.find({group: 1}, {x: {$elemMatch: {$all: [1]}}}).toArray()[0].x, "$in number match"); assert.eq([{a: 'string', b: date1}], t.find({group: 6}, {x: {$elemMatch: {a: 'string'}}}).toArray()[0].x, @@ -212,10 +209,10 @@ assert.eq([{a: 2, c: 3}], t.find({group: 3}, {x: {$elemMatch: {a: {$mod: [2, 0]}}}}).toArray()[0].x, "mixed object match on mod"); -assert.eq({"x": [{"a": 1, "b": 2}], "y": [{"c": 3, "d": 4}]}, - t.find({group: 10}, {_id: 0, x: {$elemMatch: {a: 1}}, y: {$elemMatch: {c: 3}}}) - .toArray()[0], - "multiple $elemMatch on unique fields 1"); +assert.eq( + {"x": [{"a": 1, "b": 2}], "y": [{"c": 3, "d": 4}]}, + t.find({group: 10}, {_id: 0, x: {$elemMatch: {a: 1}}, y: {$elemMatch: {c: 3}}}).toArray()[0], + "multiple $elemMatch on unique fields 1"); assert.eq({"x": [{"y": [{"a": 1, "b": 2}, {"a": 3, "b": 4}]}]}, t.find({group: 8}, {_id: 0, x: {$elemMatch: {y: {$elemMatch: {a: 3}}}}}).toArray()[0], diff --git a/jstests/core/eval0.js b/jstests/core/eval0.js index a0c93da2cab..57a60e77244 100644 --- a/jstests/core/eval0.js +++ b/jstests/core/eval0.js @@ -4,13 +4,9 @@ assert.eq(17, return 11 + 6; }), "A"); -assert.eq(17, - db.eval( - function(x) { - return 10 + x; - }, - 7), - "B"); +assert.eq(17, db.eval(function(x) { + return 10 + x; +}, 7), "B"); // check that functions in system.js work db.system.js.insert({ diff --git a/jstests/core/eval_mr.js b/jstests/core/eval_mr.js index 84036b1e0d5..4a3dc8dad6c 100644 --- a/jstests/core/eval_mr.js +++ b/jstests/core/eval_mr.js @@ -6,16 +6,15 @@ assert.writeOK(db.eval_mr.insert({val: 1})); assert.writeOK(db.eval_mr.insert({val: 2})); var runBasicMapReduce = function() { - return db.eval_mr.runCommand("mapReduce", - { - map: function() { - emit(0, this.val); - }, - reduce: function(id, values) { - return Array.sum(values); - }, - out: {replace: "eval_mr_out"} - }); + return db.eval_mr.runCommand("mapReduce", { + map: function() { + emit(0, this.val); + }, + reduce: function(id, values) { + return Array.sum(values); + }, + out: {replace: "eval_mr_out"} + }); }; assert.commandWorked(runBasicMapReduce()); assert.eq(3, db.eval_mr_out.findOne().value); diff --git a/jstests/core/evalg.js b/jstests/core/evalg.js index 570464cbce2..18503659217 100644 --- a/jstests/core/evalg.js +++ b/jstests/core/evalg.js @@ -3,10 +3,9 @@ db.evalg.drop(); for (var i = 0; i < 102; ++i) { db.evalg.insert({}); } -assert.eq(102, - db.eval(function() { - var cursor = db.evalg.aggregate(); - assert(cursor.hasNext()); - assert.eq(101, cursor.objsLeftInBatch()); - return cursor.itcount(); - })); +assert.eq(102, db.eval(function() { + var cursor = db.evalg.aggregate(); + assert(cursor.hasNext()); + assert.eq(101, cursor.objsLeftInBatch()); + return cursor.itcount(); +})); diff --git a/jstests/core/exists4.js b/jstests/core/exists4.js index 097a3462da9..2979a60f276 100644 --- a/jstests/core/exists4.js +++ b/jstests/core/exists4.js @@ -34,12 +34,10 @@ assert.eq( 3, t.find({date: new Date("08/27/2010"), country_code: {$exists: true}, user_id: {$exists: true}}) .count()); -assert.eq(2, - t.find({ - date: new Date("08/27/2010"), - country_code: {$exists: true}, - user_id: {$exists: false} - }).count()); -assert.eq(2, - t.find({date: new Date("08/27/2010"), country_code: {$exists: true}, user_id: null}) - .count()); +assert.eq( + 2, + t.find({date: new Date("08/27/2010"), country_code: {$exists: true}, user_id: {$exists: false}}) + .count()); +assert.eq( + 2, + t.find({date: new Date("08/27/2010"), country_code: {$exists: true}, user_id: null}).count()); diff --git a/jstests/core/existsa.js b/jstests/core/existsa.js index 45adb5d3172..e9430b489a3 100644 --- a/jstests/core/existsa.js +++ b/jstests/core/existsa.js @@ -38,9 +38,7 @@ function assertExists(query, expectedExists) { // An $exists:true predicate generates no index filters. Add another predicate on the index key // to trigger use of the index. andClause = {}; - andClause[indexKeyField] = { - $ne: null - }; + andClause[indexKeyField] = {$ne: null}; Object.extend(query, {$and: [andClause]}); assert.eq(expectedExists, t.count(query)); assert.eq(expectedExists, hintedCount(query)); @@ -52,9 +50,7 @@ function assertExistsUnindexed(query, expectedExists) { assert.eq(expectedExists, t.count(query)); // Even with another predicate on the index key, the sparse index is disallowed. andClause = {}; - andClause[indexKeyField] = { - $ne: null - }; + andClause[indexKeyField] = {$ne: null}; Object.extend(query, {$and: [andClause]}); assert.eq(expectedExists, t.count(query)); assert.eq(expectedExists, hintedCount(query)); diff --git a/jstests/core/explain_distinct.js b/jstests/core/explain_distinct.js index bc5b3635c95..57e5f55e065 100644 --- a/jstests/core/explain_distinct.js +++ b/jstests/core/explain_distinct.js @@ -10,10 +10,7 @@ var coll = db[collName]; function runDistinctExplain(collection, keyString, query) { - var distinctCmd = { - distinct: collection.getName(), - key: keyString - }; + var distinctCmd = {distinct: collection.getName(), key: keyString}; if (typeof query !== 'undefined') { distinctCmd.query = query; diff --git a/jstests/core/explain_find.js b/jstests/core/explain_find.js index 820e6dffbcd..87174e99a62 100644 --- a/jstests/core/explain_find.js +++ b/jstests/core/explain_find.js @@ -10,8 +10,8 @@ for (var i = 0; i < 10; i++) { t.insert({_id: i, a: i}); } -var explain = db.runCommand( - {explain: {find: collName, filter: {a: {$lte: 2}}}, verbosity: "executionStats"}); +var explain = + db.runCommand({explain: {find: collName, filter: {a: {$lte: 2}}}, verbosity: "executionStats"}); printjson(explain); assert.commandWorked(explain); assert.eq(3, explain.executionStats.nReturned); diff --git a/jstests/core/explain_find_and_modify.js b/jstests/core/explain_find_and_modify.js index 346e7029cd1..1d30486ecb4 100644 --- a/jstests/core/explain_find_and_modify.js +++ b/jstests/core/explain_find_and_modify.js @@ -13,12 +13,8 @@ var t = db.getCollection(cName); // Different types of findAndModify explain requests. - var explainRemove = { - explain: {findAndModify: cName, remove: true, query: {_id: 0}} - }; - var explainUpdate = { - explain: {findAndModify: cName, update: {$inc: {i: 1}}, query: {_id: 0}} - }; + var explainRemove = {explain: {findAndModify: cName, remove: true, query: {_id: 0}}}; + var explainUpdate = {explain: {findAndModify: cName, update: {$inc: {i: 1}}, query: {_id: 0}}}; var explainUpsert = { explain: {findAndModify: cName, update: {$inc: {i: 1}}, query: {_id: 0}, upsert: true} }; @@ -60,39 +56,24 @@ assert.commandFailed(db.runCommand({remove: true, new: true})); // 4. Explaining findAndModify should not modify any contents of the collection. - var onlyDoc = { - _id: 0, - i: 1 - }; + var onlyDoc = {_id: 0, i: 1}; assert.writeOK(t.insert(onlyDoc)); // Explaining a delete should not delete anything. - var matchingRemoveCmd = { - findAndModify: cName, - remove: true, - query: {_id: onlyDoc._id} - }; + var matchingRemoveCmd = {findAndModify: cName, remove: true, query: {_id: onlyDoc._id}}; var res = db.runCommand({explain: matchingRemoveCmd}); assert.commandWorked(res); assert.eq(t.find().itcount(), 1, "Explaining a remove should not remove any documents."); // Explaining an update should not update anything. - var matchingUpdateCmd = { - findAndModify: cName, - update: {x: "x"}, - query: {_id: onlyDoc._id} - }; + var matchingUpdateCmd = {findAndModify: cName, update: {x: "x"}, query: {_id: onlyDoc._id}}; var res = db.runCommand({explain: matchingUpdateCmd}); assert.commandWorked(res); assert.eq(t.findOne(), onlyDoc, "Explaining an update should not update any documents."); // Explaining an upsert should not insert anything. - var matchingUpsertCmd = { - findAndModify: cName, - update: {x: "x"}, - query: {_id: "non-match"}, - upsert: true - }; + var matchingUpsertCmd = + {findAndModify: cName, update: {x: "x"}, query: {_id: "non-match"}, upsert: true}; var res = db.runCommand({explain: matchingUpsertCmd}); assert.commandWorked(res); assert.eq(t.find().itcount(), 1, "Explaining an upsert should not insert any documents."); @@ -273,23 +254,21 @@ function assertExplainResultsMatch(explainOut, expectedMatches, preMsg, currentPath) { // This is only used recursively, to keep track of where we are in the document. var isRootLevel = typeof currentPath === "undefined"; - Object.keys(expectedMatches) - .forEach(function(key) { - var totalFieldName = isRootLevel ? key : currentPath + "." + key; - assert(explainOut.hasOwnProperty(key), - preMsg + "Explain's output does not have a value for " + key); - if (typeof expectedMatches[key] === "object") { - // Sub-doc, recurse to match on it's fields - assertExplainResultsMatch( - explainOut[key], expectedMatches[key], preMsg, totalFieldName); - } else { - assert.eq(explainOut[key], - expectedMatches[key], - preMsg + "Explain's " + totalFieldName + " (" + explainOut[key] + - ")" + " does not match expected value (" + expectedMatches[key] + - ")."); - } - }); + Object.keys(expectedMatches).forEach(function(key) { + var totalFieldName = isRootLevel ? key : currentPath + "." + key; + assert(explainOut.hasOwnProperty(key), + preMsg + "Explain's output does not have a value for " + key); + if (typeof expectedMatches[key] === "object") { + // Sub-doc, recurse to match on it's fields + assertExplainResultsMatch( + explainOut[key], expectedMatches[key], preMsg, totalFieldName); + } else { + assert.eq(explainOut[key], + expectedMatches[key], + preMsg + "Explain's " + totalFieldName + " (" + explainOut[key] + ")" + + " does not match expected value (" + expectedMatches[key] + ")."); + } + }); } /** diff --git a/jstests/core/explain_multi_plan.js b/jstests/core/explain_multi_plan.js index f74078c717d..693237d9edc 100644 --- a/jstests/core/explain_multi_plan.js +++ b/jstests/core/explain_multi_plan.js @@ -49,13 +49,12 @@ }); assert.doesNotThrow(function() { - coll.explain("allPlansExecution") - .group({ - key: {a: 1}, - cond: {a: {$gte: 1}}, - reduce: function(curr, result) {}, - initial: {} - }); + coll.explain("allPlansExecution").group({ + key: {a: 1}, + cond: {a: {$gte: 1}}, + reduce: function(curr, result) {}, + initial: {} + }); }); // SERVER-21376: Make sure the 'rejectedPlans' field is filled in appropriately. diff --git a/jstests/core/find4.js b/jstests/core/find4.js index 7a5ebf79578..204e7c511e2 100644 --- a/jstests/core/find4.js +++ b/jstests/core/find4.js @@ -23,9 +23,11 @@ t.drop(); t.save({a: 1, b: 1}); t.save({a: 2, b: 2}); assert.eq("1-1,2-2", - t.find().map(function(z) { - return z.a + "-" + z.b; - }).toString()); + t.find() + .map(function(z) { + return z.a + "-" + z.b; + }) + .toString()); assert.eq("1-undefined,2-undefined", t.find({}, {a: 1}) .map(function(z) { diff --git a/jstests/core/find_and_modify.js b/jstests/core/find_and_modify.js index cf2f8804d9e..394b618f109 100644 --- a/jstests/core/find_and_modify.js +++ b/jstests/core/find_and_modify.js @@ -69,7 +69,8 @@ var cmdRes = db.runCommand({ query: {_id: "miss"}, update: {$inc: {y: 1}}, fields: {foo: {$pop: ["bar"]}}, - upsert: true, new: true + upsert: true, + new: true }); assert.commandFailed(cmdRes); @@ -81,7 +82,8 @@ cmdRes = db.runCommand({ query: {_id: "found"}, update: {$inc: {y: 1}}, fields: {foo: {$pop: ["bar"]}}, - upsert: true, new: true + upsert: true, + new: true }); assert.commandFailed(cmdRes); @@ -90,7 +92,8 @@ cmdRes = db.runCommand({ findAndModify: t.getName(), query: {_id: "found"}, update: {$inc: {y: 1}}, - fields: {foo: {$pop: ["bar"]}}, new: true + fields: {foo: {$pop: ["bar"]}}, + new: true }); assert.commandFailed(cmdRes); @@ -128,7 +131,8 @@ cmdRes = db.runCommand({ findAndModify: t.getName(), query: {_id: "missagain"}, update: {$inc: {y: 1}}, - upsert: true, new: true + upsert: true, + new: true }); assert.commandWorked(cmdRes); assert("value" in cmdRes); diff --git a/jstests/core/find_and_modify_server6865.js b/jstests/core/find_and_modify_server6865.js index b38c0b1bee4..3583da42412 100644 --- a/jstests/core/find_and_modify_server6865.js +++ b/jstests/core/find_and_modify_server6865.js @@ -69,66 +69,60 @@ {_id: 42, c: 4}); // Simple query that uses $elemMatch in the projection. - testFAMWorked( - { - _id: 42, - b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] - }, - {query: {_id: 42}, fields: {b: {$elemMatch: {value: 2}}}, remove: true}, - {_id: 42, b: [{name: 'second', value: 2}]}); + testFAMWorked({ + _id: 42, + b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] + }, + {query: {_id: 42}, fields: {b: {$elemMatch: {value: 2}}}, remove: true}, + {_id: 42, b: [{name: 'second', value: 2}]}); // Query on an array of values while using a positional projection. - testFAMWorked({_id: 42, a: [1, 2]}, - {query: {a: 2}, fields: {'a.$': 1}, remove: true}, - {_id: 42, a: [2]}); + testFAMWorked( + {_id: 42, a: [1, 2]}, {query: {a: 2}, fields: {'a.$': 1}, remove: true}, {_id: 42, a: [2]}); // Query on an array of objects while using a positional projection. - testFAMWorked( - { - _id: 42, - b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] - }, - {query: {_id: 42, 'b.name': 'third'}, fields: {'b.$': 1}, remove: true}, - {_id: 42, b: [{name: 'third', value: 3}]}); + testFAMWorked({ + _id: 42, + b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] + }, + {query: {_id: 42, 'b.name': 'third'}, fields: {'b.$': 1}, remove: true}, + {_id: 42, b: [{name: 'third', value: 3}]}); // Query on an array of objects while using a position projection. // Verifies that the projection {'b.$.value': 1} is treated the // same as {'b.$': 1}. - testFAMWorked( - { - _id: 42, - b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] - }, - {query: {_id: 42, 'b.name': 'third'}, fields: {'b.$.value': 1}, remove: true}, - {_id: 42, b: [{name: 'third', value: 3}]}); + testFAMWorked({ + _id: 42, + b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] + }, + {query: {_id: 42, 'b.name': 'third'}, fields: {'b.$.value': 1}, remove: true}, + {_id: 42, b: [{name: 'third', value: 3}]}); // Query on an array of objects using $elemMatch while using an inclusion projection. - testFAMWorked( - { - _id: 42, - a: 5, - b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] - }, - { - query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, - fields: {_id: 0, a: 5}, - remove: true - }, - {a: 5}); + testFAMWorked({ + _id: 42, + a: 5, + b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] + }, + { + query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, + fields: {_id: 0, a: 5}, + remove: true + }, + {a: 5}); // Query on an array of objects using $elemMatch while using the positional // operator in the projection. - testFAMWorked( - { - _id: 42, - b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] - }, - { - query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, - fields: {_id: 0, 'b.$': 1}, - remove: true - }, - {b: [{name: 'john', value: 1}]}); + testFAMWorked({ + _id: 42, + b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] + }, + { + query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, + fields: {_id: 0, 'b.$': 1}, + remove: true + }, + {b: [{name: 'john', value: 1}]}); // // Update operations with new=false @@ -145,17 +139,17 @@ {_id: 42, c: 4}); // Simple query that uses $elemMatch in the projection. - testFAMWorked( - { - _id: 42, - b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] - }, - { - query: {_id: 42}, - fields: {b: {$elemMatch: {value: 2}}}, - update: {$set: {name: '2nd'}}, new: false - }, - {_id: 42, b: [{name: 'second', value: 2}]}); + testFAMWorked({ + _id: 42, + b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] + }, + { + query: {_id: 42}, + fields: {b: {$elemMatch: {value: 2}}}, + update: {$set: {name: '2nd'}}, + new: false + }, + {_id: 42, b: [{name: 'second', value: 2}]}); // Query on an array of values while using a positional projection. testFAMWorked( @@ -164,17 +158,17 @@ {_id: 42, a: [2]}); // Query on an array of objects while using a positional projection. - testFAMWorked( - { - _id: 42, - b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] - }, - { - query: {_id: 42, 'b.name': 'third'}, - fields: {'b.$': 1}, - update: {$set: {'b.$.kind': 'xyz'}}, new: false - }, - {_id: 42, b: [{name: 'third', value: 3}]}); + testFAMWorked({ + _id: 42, + b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] + }, + { + query: {_id: 42, 'b.name': 'third'}, + fields: {'b.$': 1}, + update: {$set: {'b.$.kind': 'xyz'}}, + new: false + }, + {_id: 42, b: [{name: 'third', value: 3}]}); // Query on an array of objects while using $elemMatch in the projection, // where the matched array element is modified. @@ -184,32 +178,32 @@ {_id: 1, a: [{x: 1, y: 1}]}); // Query on an array of objects using $elemMatch while using an inclusion projection. - testFAMWorked( - { - _id: 42, - a: 5, - b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] - }, - { - query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, - fields: {_id: 0, a: 5}, - update: {$inc: {a: 6}}, new: false - }, - {a: 5}); + testFAMWorked({ + _id: 42, + a: 5, + b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] + }, + { + query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, + fields: {_id: 0, a: 5}, + update: {$inc: {a: 6}}, + new: false + }, + {a: 5}); // Query on an array of objects using $elemMatch while using the positional // operator in the projection. - testFAMWorked( - { - _id: 42, - b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] - }, - { - query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, - fields: {_id: 0, 'b.$': 1}, - update: {$set: {name: 'james'}}, new: false - }, - {b: [{name: 'john', value: 1}]}); + testFAMWorked({ + _id: 42, + b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] + }, + { + query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, + fields: {_id: 0, 'b.$': 1}, + update: {$set: {name: 'james'}}, + new: false + }, + {b: [{name: 'john', value: 1}]}); // // Update operations with new=true @@ -226,17 +220,17 @@ {_id: 42, c: 5}); // Simple query that uses $elemMatch in the projection. - testFAMWorked( - { - _id: 42, - b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] - }, - { - query: {_id: 42}, - fields: {b: {$elemMatch: {value: 2}}}, - update: {$set: {'b.1.name': '2nd'}}, new: true - }, - {_id: 42, b: [{name: '2nd', value: 2}]}); + testFAMWorked({ + _id: 42, + b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] + }, + { + query: {_id: 42}, + fields: {b: {$elemMatch: {value: 2}}}, + update: {$set: {'b.1.name': '2nd'}}, + new: true + }, + {_id: 42, b: [{name: '2nd', value: 2}]}); // Query on an array of values while using a positional projection. testFAMFailed( @@ -244,29 +238,29 @@ {query: {a: 2}, fields: {'a.$': 1}, update: {$set: {'b.kind': 'xyz'}}, new: true}); // Query on an array of objects while using a positional projection. - testFAMFailed( - { - _id: 42, - b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] - }, - { - query: {_id: 42, 'b.name': 'third'}, - fields: {'b.$': 1}, - update: {$set: {'b.$.kind': 'xyz'}}, new: true - }); + testFAMFailed({ + _id: 42, + b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] + }, + { + query: {_id: 42, 'b.name': 'third'}, + fields: {'b.$': 1}, + update: {$set: {'b.$.kind': 'xyz'}}, + new: true + }); // Query on an array of objects while using $elemMatch in the projection. - testFAMWorked( - { - _id: 42, - b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] - }, - { - query: {_id: 42}, - fields: {b: {$elemMatch: {value: 2}}, c: 1}, - update: {$set: {c: 'xyz'}}, new: true - }, - {_id: 42, b: [{name: 'second', value: 2}], c: 'xyz'}); + testFAMWorked({ + _id: 42, + b: [{name: 'first', value: 1}, {name: 'second', value: 2}, {name: 'third', value: 3}] + }, + { + query: {_id: 42}, + fields: {b: {$elemMatch: {value: 2}}, c: 1}, + update: {$set: {c: 'xyz'}}, + new: true + }, + {_id: 42, b: [{name: 'second', value: 2}], c: 'xyz'}); // Query on an array of objects while using $elemMatch in the projection, // where the matched array element is modified. @@ -276,30 +270,30 @@ {_id: 1, a: [{x: 1, y: 2}]}); // Query on an array of objects using $elemMatch while using an inclusion projection. - testFAMWorked( - { - _id: 42, - a: 5, - b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] - }, - { - query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, - fields: {_id: 0, a: 5}, - update: {$inc: {a: 6}}, new: true - }, - {a: 11}); + testFAMWorked({ + _id: 42, + a: 5, + b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] + }, + { + query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, + fields: {_id: 0, a: 5}, + update: {$inc: {a: 6}}, + new: true + }, + {a: 11}); // Query on an array of objects using $elemMatch while using the positional // operator in the projection. - testFAMFailed( - { - _id: 42, - b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] - }, - { - query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, - fields: {_id: 0, 'b.$': 1}, - update: {$set: {name: 'james'}}, new: true - }); + testFAMFailed({ + _id: 42, + b: [{name: 'john', value: 1}, {name: 'jess', value: 2}, {name: 'jeff', value: 3}] + }, + { + query: {b: {$elemMatch: {name: 'john', value: {$lt: 2}}}}, + fields: {_id: 0, 'b.$': 1}, + update: {$set: {name: 'james'}}, + new: true + }); })(); diff --git a/jstests/core/find_dedup.js b/jstests/core/find_dedup.js index a9160df7562..7a489bd185c 100644 --- a/jstests/core/find_dedup.js +++ b/jstests/core/find_dedup.js @@ -20,15 +20,14 @@ t.save({_id: 2, a: 1, b: 1}); t.save({_id: 3, a: 2, b: 2}); t.save({_id: 4, a: 3, b: 3}); t.save({_id: 5, a: 3, b: 3}); -checkDedup( - { - $or: [ - {a: {$gte: 0, $lte: 2}, b: {$gte: 0, $lte: 2}}, - {a: {$gte: 1, $lte: 3}, b: {$gte: 1, $lte: 3}}, - {a: {$gte: 1, $lte: 4}, b: {$gte: 1, $lte: 4}} - ] - }, - [1, 2, 3, 4, 5]); +checkDedup({ + $or: [ + {a: {$gte: 0, $lte: 2}, b: {$gte: 0, $lte: 2}}, + {a: {$gte: 1, $lte: 3}, b: {$gte: 1, $lte: 3}}, + {a: {$gte: 1, $lte: 4}, b: {$gte: 1, $lte: 4}} + ] +}, + [1, 2, 3, 4, 5]); // Deduping multikey t.drop(); diff --git a/jstests/core/find_getmore_bsonsize.js b/jstests/core/find_getmore_bsonsize.js index 904a9c33ab0..fdad2b1f1d6 100644 --- a/jstests/core/find_getmore_bsonsize.js +++ b/jstests/core/find_getmore_bsonsize.js @@ -74,10 +74,7 @@ bigStr += bigStr; } bigStr = bigStr.substring(0, (16 * oneMB) - 32); - var maxSizeDoc = { - _id: 0, - padding: bigStr - }; + var maxSizeDoc = {_id: 0, padding: bigStr}; assert.eq(Object.bsonsize(maxSizeDoc), 16 * oneMB); assert.writeOK(coll.insert(maxSizeDoc)); diff --git a/jstests/core/fts_blog.js b/jstests/core/fts_blog.js index 9f35836ef37..68cca6fa3a5 100644 --- a/jstests/core/fts_blog.js +++ b/jstests/core/fts_blog.js @@ -9,8 +9,9 @@ t.save({_id: 3, title: "knives are Fun", text: "this is a new blog i am writing. // specify weights if you want a field to be more meaningull t.ensureIndex({"title": "text", text: "text"}, {weights: {title: 10}}); -res = t.find({"$text": {"$search": "blog"}}, {score: {"$meta": "textScore"}}) - .sort({score: {"$meta": "textScore"}}); +res = t.find({"$text": {"$search": "blog"}}, {score: {"$meta": "textScore"}}).sort({ + score: {"$meta": "textScore"} +}); assert.eq(3, res.length()); assert.eq(1, res[0]._id); diff --git a/jstests/core/fts_blogwild.js b/jstests/core/fts_blogwild.js index dad96cd2836..377e4529f3e 100644 --- a/jstests/core/fts_blogwild.js +++ b/jstests/core/fts_blogwild.js @@ -24,17 +24,20 @@ t.dropIndex("dummy_text"); assert.eq(1, t.getIndexKeys().length, "C1"); t.ensureIndex({dummy: "text"}, {weights: {"$**": 1, title: 2}}); -res = t.find({"$text": {"$search": "write"}}, {score: {"$meta": "textScore"}}) - .sort({score: {"$meta": "textScore"}}); +res = t.find({"$text": {"$search": "write"}}, {score: {"$meta": "textScore"}}).sort({ + score: {"$meta": "textScore"} +}); assert.eq(3, res.length(), "C2"); assert.eq(3, res[0]._id, "C3"); -res = t.find({"$text": {"$search": "blog"}}, {score: {"$meta": "textScore"}}) - .sort({score: {"$meta": "textScore"}}); +res = t.find({"$text": {"$search": "blog"}}, {score: {"$meta": "textScore"}}).sort({ + score: {"$meta": "textScore"} +}); assert.eq(3, res.length(), "D1"); assert.eq(1, res[0]._id, "D2"); -res = t.find({"$text": {"$search": "eliot"}}, {score: {"$meta": "textScore"}}) - .sort({score: {"$meta": "textScore"}}); +res = t.find({"$text": {"$search": "eliot"}}, {score: {"$meta": "textScore"}}).sort({ + score: {"$meta": "textScore"} +}); assert.eq(2, res.length(), "E1"); assert.eq(3, res[0]._id, "E2"); diff --git a/jstests/core/fts_diacritic_and_casesensitive.js b/jstests/core/fts_diacritic_and_casesensitive.js index 397b6033f88..d5c15034dbc 100644 --- a/jstests/core/fts_diacritic_and_casesensitive.js +++ b/jstests/core/fts_diacritic_and_casesensitive.js @@ -19,8 +19,8 @@ load('jstests/libs/fts.js'); assert.eq( [0], queryIDS(coll, "próximo vôo à ", null, {$diacriticSensitive: true, $caseSensitive: true})); - assert.eq( - [0], queryIDS(coll, "Atlântico", null, {$diacriticSensitive: true, $caseSensitive: true})); + assert.eq([0], + queryIDS(coll, "Atlântico", null, {$diacriticSensitive: true, $caseSensitive: true})); assert.eq( [0], queryIDS(coll, "\"próximo\"", null, {$diacriticSensitive: true, $caseSensitive: true})); @@ -47,8 +47,7 @@ load('jstests/libs/fts.js'); queryIDS(coll, "proximo vôo à ", null, {$diacriticSensitive: true, $caseSensitive: true})); assert.eq( [], - queryIDS( - coll, "À -próximo -Vôo", null, {$diacriticSensitive: true, $caseSensitive: true})); + queryIDS(coll, "À -próximo -Vôo", null, {$diacriticSensitive: true, $caseSensitive: true})); assert.eq( [], queryIDS(coll, "à proximo -Vôo", null, {$diacriticSensitive: true, $caseSensitive: true})); diff --git a/jstests/core/fts_diacriticsensitive.js b/jstests/core/fts_diacriticsensitive.js index 29e7784a785..e21d5360051 100644 --- a/jstests/core/fts_diacriticsensitive.js +++ b/jstests/core/fts_diacriticsensitive.js @@ -24,8 +24,7 @@ load('jstests/libs/fts.js'); assert.eq([0], queryIDS(coll, "\"próximo\"", null, {$diacriticSensitive: true})); assert.eq([0], queryIDS(coll, "\"põe\" atlântico", null, {$diacriticSensitive: true})); assert.eq( - [0], - queryIDS(coll, "\"próximo vôo\" \"único médico\"", null, {$diacriticSensitive: true})); + [0], queryIDS(coll, "\"próximo vôo\" \"único médico\"", null, {$diacriticSensitive: true})); assert.eq( [0], queryIDS(coll, "\"próximo vôo\" -\"unico médico\"", null, {$diacriticSensitive: true})); @@ -38,7 +37,6 @@ load('jstests/libs/fts.js'); assert.eq([], queryIDS(coll, "mo vô", null, {$diacriticSensitive: true})); assert.eq([], queryIDS(coll, "\"unico medico\"", null, {$diacriticSensitive: true})); assert.eq( - [], - queryIDS(coll, "\"próximo vôo\" -\"único médico\"", null, {$diacriticSensitive: true})); + [], queryIDS(coll, "\"próximo vôo\" -\"único médico\"", null, {$diacriticSensitive: true})); })(); diff --git a/jstests/core/fts_index.js b/jstests/core/fts_index.js index 8cda28096d2..ab953a88624 100644 --- a/jstests/core/fts_index.js +++ b/jstests/core/fts_index.js @@ -17,48 +17,60 @@ coll.getDB().createCollection(coll.getName()); // Spec passes text-specific index validation. assert.commandWorked(coll.ensureIndex({a: "text"}, {name: indexName, default_language: "spanish"})); assert.eq(1, - coll.getIndexes().filter(function(z) { - return z.name == indexName; - }).length); + coll.getIndexes() + .filter(function(z) { + return z.name == indexName; + }) + .length); coll.dropIndexes(); // Spec fails text-specific index validation ("spanglish" unrecognized). -assert.commandFailed(coll.ensureIndex({a: "text"}, - {name: indexName, default_language: "spanglish"})); +assert.commandFailed( + coll.ensureIndex({a: "text"}, {name: indexName, default_language: "spanglish"})); assert.eq(0, - coll.getIndexes().filter(function(z) { - return z.name == indexName; - }).length); + coll.getIndexes() + .filter(function(z) { + return z.name == indexName; + }) + .length); coll.dropIndexes(); // Spec passes general index validation. assert.commandWorked(coll.ensureIndex({"$**": "text"}, {name: indexName})); assert.eq(1, - coll.getIndexes().filter(function(z) { - return z.name == indexName; - }).length); + coll.getIndexes() + .filter(function(z) { + return z.name == indexName; + }) + .length); coll.dropIndexes(); // Spec fails general index validation ("a.$**" invalid field name for key). assert.commandFailed(coll.ensureIndex({"a.$**": "text"}, {name: indexName})); assert.eq(0, - coll.getIndexes().filter(function(z) { - return z.name == indexName; - }).length); + coll.getIndexes() + .filter(function(z) { + return z.name == indexName; + }) + .length); coll.dropIndexes(); // SERVER-19519 Spec fails if '_fts' is specified on a non-text index. assert.commandFailed(coll.ensureIndex({_fts: 1}, {name: indexName})); assert.eq(0, - coll.getIndexes().filter(function(z) { - return z.name == indexName; - }).length); + coll.getIndexes() + .filter(function(z) { + return z.name == indexName; + }) + .length); coll.dropIndexes(); assert.commandFailed(coll.ensureIndex({_fts: "text"}, {name: indexName})); assert.eq(0, - coll.getIndexes().filter(function(z) { - return z.name == indexName; - }).length); + coll.getIndexes() + .filter(function(z) { + return z.name == indexName; + }) + .length); coll.dropIndexes(); // diff --git a/jstests/core/fts_phrase.js b/jstests/core/fts_phrase.js index d36df8aaeb0..d93e53b0898 100644 --- a/jstests/core/fts_phrase.js +++ b/jstests/core/fts_phrase.js @@ -8,14 +8,16 @@ t.save({_id: 3, title: "knives are Fun", text: "this is a new blog i am writing. t.ensureIndex({"title": "text", text: "text"}, {weights: {title: 10}}); -res = t.find({"$text": {"$search": "blog write"}}, {score: {"$meta": "textScore"}}) - .sort({score: {"$meta": "textScore"}}); +res = t.find({"$text": {"$search": "blog write"}}, {score: {"$meta": "textScore"}}).sort({ + score: {"$meta": "textScore"} +}); assert.eq(3, res.length()); assert.eq(1, res[0]._id); assert(res[0].score > (res[1].score * 2), tojson(res.toArray())); -res = t.find({"$text": {"$search": "write blog"}}, {score: {"$meta": "textScore"}}) - .sort({score: {"$meta": "textScore"}}); +res = t.find({"$text": {"$search": "write blog"}}, {score: {"$meta": "textScore"}}).sort({ + score: {"$meta": "textScore"} +}); assert.eq(3, res.length()); assert.eq(1, res[0]._id); assert(res[0].score > (res[1].score * 2), tojson(res.toArray())); diff --git a/jstests/core/fts_projection.js b/jstests/core/fts_projection.js index 50fe4755fc3..6cb1471505b 100644 --- a/jstests/core/fts_projection.js +++ b/jstests/core/fts_projection.js @@ -11,8 +11,10 @@ t.insert({_id: 2, a: "irrelevant content"}); t.ensureIndex({a: "text"}); // Project the text score. -var results = t.find({$text: {$search: "textual content -irrelevant"}}, - {_idCopy: 0, score: {$meta: "textScore"}}).toArray(); +var results = t.find({$text: {$search: "textual content -irrelevant"}}, { + _idCopy: 0, + score: {$meta: "textScore"} + }).toArray(); // printjson(results); // Scores should exist. assert.eq(results.length, 2); @@ -29,8 +31,10 @@ scores[results[1]._id] = results[1].score; // // Project text score into 2 fields. -results = t.find({$text: {$search: "textual content -irrelevant"}}, - {otherScore: {$meta: "textScore"}, score: {$meta: "textScore"}}).toArray(); +results = t.find({$text: {$search: "textual content -irrelevant"}}, { + otherScore: {$meta: "textScore"}, + score: {$meta: "textScore"} + }).toArray(); assert.eq(2, results.length); for (var i = 0; i < results.length; ++i) { assert.close(scores[results[i]._id], results[i].score); @@ -41,8 +45,9 @@ for (var i = 0; i < results.length; ++i) { // Project text score into "x.$" shouldn't crash assert.throws(function() { - t.find({$text: {$search: "textual content -irrelevant"}}, {'x.$': {$meta: "textScore"}}) - .toArray(); + t.find({$text: {$search: "textual content -irrelevant"}}, { + 'x.$': {$meta: "textScore"} + }).toArray(); }); // TODO: We can't project 'x.y':1 and 'x':1 (yet). @@ -71,8 +76,10 @@ assert.throws(function() { // SERVER-12173 // When $text operator is in $or, should evaluate first -results = t.find({$or: [{$text: {$search: "textual content -irrelevant"}}, {_id: 1}]}, - {_idCopy: 0, score: {$meta: "textScore"}}).toArray(); +results = t.find({$or: [{$text: {$search: "textual content -irrelevant"}}, {_id: 1}]}, { + _idCopy: 0, + score: {$meta: "textScore"} + }).toArray(); printjson(results); assert.eq(2, results.length); for (var i = 0; i < results.length; ++i) { diff --git a/jstests/core/geo10.js b/jstests/core/geo10.js index 10879fc5d80..640ae67e594 100644 --- a/jstests/core/geo10.js +++ b/jstests/core/geo10.js @@ -10,7 +10,13 @@ assert.writeOK(db.geo10.insert({c: [1, 1], t: 1})); assert.writeOK(db.geo10.insert({c: [3600, 3600], t: 1})); assert.writeOK(db.geo10.insert({c: [0.001, 0.001], t: 1})); -printjson(db.geo10.find({ - c: {$within: {$box: [[0.001, 0.001], [Math.pow(2, 40) - 0.001, Math.pow(2, 40) - 0.001]]}}, - t: 1 -}).toArray()); +printjson( + db.geo10 + .find({ + c: { + $within: + {$box: [[0.001, 0.001], [Math.pow(2, 40) - 0.001, Math.pow(2, 40) - 0.001]]} + }, + t: 1 + }) + .toArray()); diff --git a/jstests/core/geo3.js b/jstests/core/geo3.js index da3d8641049..feb93b783cb 100644 --- a/jstests/core/geo3.js +++ b/jstests/core/geo3.js @@ -29,9 +29,7 @@ filtered1.results.forEach(function(z) { function avgA(q, len) { if (!len) len = 10; - var realq = { - loc: {$near: [50, 50]} - }; + var realq = {loc: {$near: [50, 50]}}; if (q) Object.extend(realq, q); var as = t.find(realq).limit(len).map(function(z) { diff --git a/jstests/core/geo9.js b/jstests/core/geo9.js index 201bee7dfa5..7419615818e 100644 --- a/jstests/core/geo9.js +++ b/jstests/core/geo9.js @@ -15,9 +15,7 @@ t.ensureIndex({b: "2d"}); function check(field) { var q = {}; - q[field] = { - $near: [11, 11] - }; + q[field] = {$near: [11, 11]}; arr = t.find(q).limit(3).map(function(z) { return Geo.distance([11, 11], z[field]); }); diff --git a/jstests/core/geo_2d_with_geojson_point.js b/jstests/core/geo_2d_with_geojson_point.js index aaadf4be333..23592e004f8 100644 --- a/jstests/core/geo_2d_with_geojson_point.js +++ b/jstests/core/geo_2d_with_geojson_point.js @@ -6,10 +6,7 @@ var t = db.geo_2d_with_geojson_point; t.drop(); t.ensureIndex({loc: '2d'}); -var geoJSONPoint = { - type: 'Point', - coordinates: [0, 0] -}; +var geoJSONPoint = {type: 'Point', coordinates: [0, 0]}; print(assert.throws(function() { t.findOne({loc: {$near: {$geometry: geoJSONPoint}}}); diff --git a/jstests/core/geo_array2.js b/jstests/core/geo_array2.js index 33aad98930a..6195e038de3 100644 --- a/jstests/core/geo_array2.js +++ b/jstests/core/geo_array2.js @@ -40,8 +40,7 @@ for (var t = 0; t < 2; t++) { // Do near check var nearResults = - db.runCommand( - {geoNear: "geoarray2", near: center, num: count, query: {type: type}}) + db.runCommand({geoNear: "geoarray2", near: center, num: count, query: {type: type}}) .results; // printjson( nearResults ) @@ -76,10 +75,11 @@ for (var t = 0; t < 2; t++) { // Earth Radius from geoconstants.h var eRad = 6378.1; - nearResults = db.geoarray2.find({ - loc: {$nearSphere: center, $maxDistance: 500 /* km */ / eRad}, - type: type - }).toArray(); + nearResults = + db.geoarray2 + .find( + {loc: {$nearSphere: center, $maxDistance: 500 /* km */ / eRad}, type: type}) + .toArray(); assert.eq(nearResults.length, count); diff --git a/jstests/core/geo_big_polygon.js b/jstests/core/geo_big_polygon.js index 6f278c59147..9371e1954b2 100644 --- a/jstests/core/geo_big_polygon.js +++ b/jstests/core/geo_big_polygon.js @@ -9,10 +9,7 @@ coll.drop(); coll.getMongo().getDB("admin").runCommand({setParameter: 1, verboseQueryLogging: true}); -var bigCRS = { - type: "name", - properties: {name: "urn:x-mongodb:crs:strictwinding:EPSG:4326"} -}; +var bigCRS = {type: "name", properties: {name: "urn:x-mongodb:crs:strictwinding:EPSG:4326"}}; var bigPoly20 = { type: "Polygon", @@ -36,20 +33,11 @@ var line10 = { coordinates: [[5.0, 5.0], [5.0, -5.0], [-5.0, -5.0], [-5.0, 5.0], [5.0, 5.0]] }; -var centerPoint = { - type: "Point", - coordinates: [0, 0] -}; +var centerPoint = {type: "Point", coordinates: [0, 0]}; -var polarPoint = { - type: "Point", - coordinates: [85, 85] -}; +var polarPoint = {type: "Point", coordinates: [85, 85]}; -var lineEquator = { - type: "LineString", - coordinates: [[-20, 0], [20, 0]] -}; +var lineEquator = {type: "LineString", coordinates: [[-20, 0], [20, 0]]}; assert.writeOK(coll.insert({loc: poly10})); assert.writeOK(coll.insert({loc: line10})); @@ -100,16 +88,8 @@ assert.commandWorked(coll.ensureIndex({loc: "2dsphere"})); assert.writeError(coll.insert({_id: "bigPoly10", loc: bigPoly10})); // Query geometries that don't support big CRS should error out. -var bigPoint = { - type: "Point", - coordinates: [0, 0], - crs: bigCRS -}; -var bigLine = { - type: "LineString", - coordinates: [[-20, 0], [20, 0]], - crs: bigCRS -}; +var bigPoint = {type: "Point", coordinates: [0, 0], crs: bigCRS}; +var bigLine = {type: "LineString", coordinates: [[-20, 0], [20, 0]], crs: bigCRS}; assert.throws(function() { coll.find({loc: {$geoIntersects: {$geometry: bigPoint}}}).itcount(); diff --git a/jstests/core/geo_big_polygon2.js b/jstests/core/geo_big_polygon2.js index 46ac327b7e0..2193229990d 100644 --- a/jstests/core/geo_big_polygon2.js +++ b/jstests/core/geo_big_polygon2.js @@ -5,23 +5,11 @@ // - Big polygon objects cannot be stored // Try all different shapes queries against various stored geo points, line & polygons -var crs84CRS = { - type: "name", - properties: {name: "urn:ogc:def:crs:OGC:1.3:CRS84"} -}; -var epsg4326CRS = { - type: "name", - properties: {name: "EPSG:4326"} -}; -var strictCRS = { - type: "name", - properties: {name: "urn:x-mongodb:crs:strictwinding:EPSG:4326"} -}; +var crs84CRS = {type: "name", properties: {name: "urn:ogc:def:crs:OGC:1.3:CRS84"}}; +var epsg4326CRS = {type: "name", properties: {name: "EPSG:4326"}}; +var strictCRS = {type: "name", properties: {name: "urn:x-mongodb:crs:strictwinding:EPSG:4326"}}; // invalid CRS name -var badCRS = { - type: "name", - properties: {name: "urn:x-mongodb:crs:invalid:EPSG:4326"} -}; +var badCRS = {type: "name", properties: {name: "urn:x-mongodb:crs:invalid:EPSG:4326"}}; // helper to generate a line along a longitudinal function genLonLine(lon, startLat, endLat, latStep) { @@ -206,8 +194,7 @@ var objects = [ }, { name: "two points (MultiPoint) but only one in: Shenzhen, Guangdong, China", - geo: - {type: "MultiPoint", coordinates: [[114.0538788, 22.5551603], [113.743858, 23.025815]]} + geo: {type: "MultiPoint", coordinates: [[114.0538788, 22.5551603], [113.743858, 23.025815]]} }, { name: "multi line string: new zealand bays", @@ -606,9 +593,7 @@ indexes.forEach(function(index) { // geoWithin query var docArray = []; - var q = { - geo: {$geoWithin: {$geometry: p}} - }; + var q = {geo: {$geoWithin: {$geometry: p}}}; // Test query in aggregate docArray = coll.aggregate({$match: q}).toArray(); assert.eq(p.nW, docArray.length, "aggregate within " + p.name); @@ -616,9 +601,7 @@ indexes.forEach(function(index) { assert.eq(p.nW, docArray.length, "within " + p.name); // geoIntersects query - q = { - geo: {$geoIntersects: {$geometry: p}} - }; + q = {geo: {$geoIntersects: {$geometry: p}}}; // Test query in aggregate docArray = coll.aggregate({$match: q}).toArray(); assert.eq(p.nI, docArray.length, "aggregate intersects " + p.name); diff --git a/jstests/core/geo_big_polygon3.js b/jstests/core/geo_big_polygon3.js index 049064ebc5b..cd59ed7a2fb 100644 --- a/jstests/core/geo_big_polygon3.js +++ b/jstests/core/geo_big_polygon3.js @@ -10,18 +10,9 @@ // MapReduce with a big polygon // CRS84 & EPSG4326 objects should be retrieved from query with big polygon -var crs84CRS = { - type: "name", - properties: {name: "urn:ogc:def:crs:OGC:1.3:CRS84"} -}; -var epsg4326CRS = { - type: "name", - properties: {name: "EPSG:4326"} -}; -var strictCRS = { - type: "name", - properties: {name: "urn:x-mongodb:crs:strictwinding:EPSG:4326"} -}; +var crs84CRS = {type: "name", properties: {name: "urn:ogc:def:crs:OGC:1.3:CRS84"}}; +var epsg4326CRS = {type: "name", properties: {name: "EPSG:4326"}}; +var strictCRS = {type: "name", properties: {name: "urn:x-mongodb:crs:strictwinding:EPSG:4326"}}; var coll = db.geo_bigpoly_edgecases; coll.drop(); @@ -125,12 +116,9 @@ objects = [ name: "NYC - Times Square to CitiField to JFK to Times Square - polygon", geo: { type: "Polygon", - coordinates: [[ - [-73.9857, 40.7577], - [-73.7789, 40.6397], - [-73.8458, 40.7569], - [-73.9857, 40.7577] - ]], + coordinates: [ + [[-73.9857, 40.7577], [-73.7789, 40.6397], [-73.8458, 40.7569], [-73.9857, 40.7577]] + ], crs: strictCRS } } @@ -150,9 +138,8 @@ var poly = { crs: strictCRS }; -assert.eq(0, - coll.count({geo: {$geoWithin: {$geometry: poly}}}), - "ignore objects with strictCRS within"); +assert.eq( + 0, coll.count({geo: {$geoWithin: {$geometry: poly}}}), "ignore objects with strictCRS within"); assert.eq(0, coll.count({geo: {$geoIntersects: {$geometry: poly}}}), "ignore objects with strictCRS intersects"); @@ -162,9 +149,8 @@ coll.update({}, {$unset: {"geo.crs": ""}}, {multi: true}); var totalDocs = coll.count(); assert.eq(totalDocs, coll.count({geo: {$geoWithin: {$geometry: poly}}}), "no strictCRS within"); -assert.eq(totalDocs, - coll.count({geo: {$geoIntersects: {$geometry: poly}}}), - "no strictCRS intersects"); +assert.eq( + totalDocs, coll.count({geo: {$geoIntersects: {$geometry: poly}}}), "no strictCRS intersects"); // Clear collection coll.remove({}); diff --git a/jstests/core/geo_borders.js b/jstests/core/geo_borders.js index f0a47339591..f8a94d997dd 100644 --- a/jstests/core/geo_borders.js +++ b/jstests/core/geo_borders.js @@ -33,81 +33,75 @@ assert.commandWorked(res); // ************ // If the bounds are bigger than the box itself, just clip at the borders -assert.eq(numItems, - t.find({ - loc: { - $within: { - $box: [ - [overallMin - 2 * epsilon, overallMin - 2 * epsilon], - [overallMax + 2 * epsilon, overallMax + 2 * epsilon] - ] - } - } - }).count()); +assert.eq(numItems, t.find({ + loc: { + $within: { + $box: [ + [overallMin - 2 * epsilon, overallMin - 2 * epsilon], + [overallMax + 2 * epsilon, overallMax + 2 * epsilon] + ] + } + } + }).count()); // Check this works also for bounds where only a single dimension is off-bounds -assert.eq(numItems - 5, - t.find({ - loc: { - $within: { - $box: [ - [overallMin - 2 * epsilon, overallMin - 0.5 * epsilon], - [overallMax - epsilon, overallMax - epsilon] - ] - } - } - }).count()); +assert.eq(numItems - 5, t.find({ + loc: { + $within: { + $box: [ + [overallMin - 2 * epsilon, overallMin - 0.5 * epsilon], + [overallMax - epsilon, overallMax - epsilon] + ] + } + } + }).count()); // Make sure we can get at least close to the bounds of the index -assert.eq(numItems, - t.find({ - loc: { - $within: { - $box: [ - [overallMin - epsilon / 2, overallMin - epsilon / 2], - [overallMax + epsilon / 2, overallMax + epsilon / 2] - ] - } - } - }).count()); +assert.eq(numItems, t.find({ + loc: { + $within: { + $box: [ + [overallMin - epsilon / 2, overallMin - epsilon / 2], + [overallMax + epsilon / 2, overallMax + epsilon / 2] + ] + } + } + }).count()); // Make sure we can get at least close to the bounds of the index -assert.eq(numItems, - t.find({ - loc: { - $within: { - $box: [ - [overallMax + epsilon / 2, overallMax + epsilon / 2], - [overallMin - epsilon / 2, overallMin - epsilon / 2] - ] - } - } - }).count()); +assert.eq(numItems, t.find({ + loc: { + $within: { + $box: [ + [overallMax + epsilon / 2, overallMax + epsilon / 2], + [overallMin - epsilon / 2, overallMin - epsilon / 2] + ] + } + } + }).count()); // Check that swapping min/max has good behavior -assert.eq(numItems, - t.find({ - loc: { - $within: { - $box: [ - [overallMax + epsilon / 2, overallMax + epsilon / 2], - [overallMin - epsilon / 2, overallMin - epsilon / 2] - ] - } - } - }).count()); - -assert.eq(numItems, - t.find({ - loc: { - $within: { - $box: [ - [overallMax + epsilon / 2, overallMin - epsilon / 2], - [overallMin - epsilon / 2, overallMax + epsilon / 2] - ] - } - } - }).count()); +assert.eq(numItems, t.find({ + loc: { + $within: { + $box: [ + [overallMax + epsilon / 2, overallMax + epsilon / 2], + [overallMin - epsilon / 2, overallMin - epsilon / 2] + ] + } + } + }).count()); + +assert.eq(numItems, t.find({ + loc: { + $within: { + $box: [ + [overallMax + epsilon / 2, overallMin - epsilon / 2], + [overallMin - epsilon / 2, overallMax + epsilon / 2] + ] + } + } + }).count()); // ************** // Circle tests @@ -206,6 +200,6 @@ assert.commandWorked(db.runCommand({geoNear: "borders", near: onBounds})); // Make sure we can get all nearby points within one step (4 points in top // corner) -assert.eq(4, - db.runCommand({geoNear: "borders", near: offCenter, maxDistance: step * 1.5}) - .results.length); +assert.eq( + 4, + db.runCommand({geoNear: "borders", near: offCenter, maxDistance: step * 1.5}).results.length); diff --git a/jstests/core/geo_box1.js b/jstests/core/geo_box1.js index 45e9aab9118..b1949063568 100644 --- a/jstests/core/geo_box1.js +++ b/jstests/core/geo_box1.js @@ -5,25 +5,25 @@ t.drop(); num = 0; for (x = 0; x <= 20; x++) { for (y = 0; y <= 20; y++) { - o = { - _id: num++, - loc: [x, y] - }; + o = {_id: num++, loc: [x, y]}; t.save(o); } } t.ensureIndex({loc: "2d"}); -searches = [[[1, 2], [4, 5]], [[1, 1], [2, 2]], [[0, 2], [4, 5]], [[1, 1], [2, 8]], ]; +searches = [ + [[1, 2], [4, 5]], + [[1, 1], [2, 2]], + [[0, 2], [4, 5]], + [[1, 1], [2, 8]], +]; for (i = 0; i < searches.length; i++) { b = searches[i]; // printjson( b ); - q = { - loc: {$within: {$box: b}} - }; + q = {loc: {$within: {$box: b}}}; numWanetd = (1 + b[1][0] - b[0][0]) * (1 + b[1][1] - b[0][1]); assert.eq(numWanetd, t.find(q).itcount(), "itcount: " + tojson(q)); printjson(t.find(q).explain()); diff --git a/jstests/core/geo_box1_noindex.js b/jstests/core/geo_box1_noindex.js index 36e932105a6..a953149c59f 100644 --- a/jstests/core/geo_box1_noindex.js +++ b/jstests/core/geo_box1_noindex.js @@ -5,21 +5,21 @@ t.drop(); num = 0; for (x = 0; x <= 20; x++) { for (y = 0; y <= 20; y++) { - o = { - _id: num++, - loc: [x, y] - }; + o = {_id: num++, loc: [x, y]}; t.save(o); } } -searches = [[[1, 2], [4, 5]], [[1, 1], [2, 2]], [[0, 2], [4, 5]], [[1, 1], [2, 8]], ]; +searches = [ + [[1, 2], [4, 5]], + [[1, 1], [2, 2]], + [[0, 2], [4, 5]], + [[1, 1], [2, 8]], +]; for (i = 0; i < searches.length; i++) { b = searches[i]; - q = { - loc: {$within: {$box: b}} - }; + q = {loc: {$within: {$box: b}}}; numWanted = (1 + b[1][0] - b[0][0]) * (1 + b[1][1] - b[0][1]); assert.eq(numWanted, t.find(q).itcount(), "itcount: " + tojson(q)); printjson(t.find(q).explain()); diff --git a/jstests/core/geo_center_sphere1.js b/jstests/core/geo_center_sphere1.js index f3b39b552cd..1ee46b03486 100644 --- a/jstests/core/geo_center_sphere1.js +++ b/jstests/core/geo_center_sphere1.js @@ -27,10 +27,7 @@ function test(index) { var bulk = t.initializeUnorderedBulkOp(); for (x = -179; x <= 179; x += skip) { for (y = -89; y <= 89; y += skip) { - o = { - _id: num++, - loc: [x, y] - }; + o = {_id: num++, loc: [x, y]}; bulk.insert(o); for (i = 0; i < searches.length; i++) { if (Geo.sphereDistance([x, y], searches[i][0]) <= searches[i][1]) @@ -48,9 +45,7 @@ function test(index) { for (i = 0; i < searches.length; i++) { print('------------'); print(tojson(searches[i]) + "\t" + correct[i].length); - q = { - loc: {$within: {$centerSphere: searches[i]}} - }; + q = {loc: {$within: {$centerSphere: searches[i]}}}; // correct[i].forEach( printjson ) // printjson( q ); diff --git a/jstests/core/geo_center_sphere2.js b/jstests/core/geo_center_sphere2.js index f3dc465e350..79c69de1ab4 100644 --- a/jstests/core/geo_center_sphere2.js +++ b/jstests/core/geo_center_sphere2.js @@ -131,12 +131,12 @@ for (var test = 0; test < numTests; test++) { // geoNear results = db.runCommand({ - geoNear: "sphere", - near: startPoint, - maxDistance: radius, - num: 2 * pointsIn, - spherical: true - }).results; + geoNear: "sphere", + near: startPoint, + maxDistance: radius, + num: 2 * pointsIn, + spherical: true + }).results; /* printjson( results ); diff --git a/jstests/core/geo_circle1.js b/jstests/core/geo_circle1.js index a679a408b32..c5b6841b9a8 100644 --- a/jstests/core/geo_circle1.js +++ b/jstests/core/geo_circle1.js @@ -2,7 +2,12 @@ t = db.geo_circle1; t.drop(); -searches = [[[5, 5], 3], [[5, 5], 1], [[5, 5], 5], [[0, 5], 5], ]; +searches = [ + [[5, 5], 3], + [[5, 5], 1], + [[5, 5], 5], + [[0, 5], 5], +]; correct = searches.map(function(z) { return []; }); @@ -11,10 +16,7 @@ num = 0; for (x = 0; x <= 20; x++) { for (y = 0; y <= 20; y++) { - o = { - _id: num++, - loc: [x, y] - }; + o = {_id: num++, loc: [x, y]}; t.save(o); for (i = 0; i < searches.length; i++) if (Geo.distance([x, y], searches[i][0]) <= searches[i][1]) @@ -26,9 +28,7 @@ t.ensureIndex({loc: "2d"}); for (i = 0; i < searches.length; i++) { // print( tojson( searches[i] ) + "\t" + correct[i].length ) - q = { - loc: {$within: {$center: searches[i]}} - }; + q = {loc: {$within: {$center: searches[i]}}}; // correct[i].forEach( printjson ) // printjson( q ); diff --git a/jstests/core/geo_circle1_noindex.js b/jstests/core/geo_circle1_noindex.js index 872883dbf74..6c3135855a5 100644 --- a/jstests/core/geo_circle1_noindex.js +++ b/jstests/core/geo_circle1_noindex.js @@ -2,7 +2,12 @@ t = db.geo_circle1_noindex; t.drop(); -searches = [[[5, 5], 3], [[5, 5], 1], [[5, 5], 5], [[0, 5], 5], ]; +searches = [ + [[5, 5], 3], + [[5, 5], 1], + [[5, 5], 5], + [[0, 5], 5], +]; correct = searches.map(function(z) { return []; }); @@ -11,10 +16,7 @@ num = 0; for (x = 0; x <= 20; x++) { for (y = 0; y <= 20; y++) { - o = { - _id: num++, - loc: [x, y] - }; + o = {_id: num++, loc: [x, y]}; t.save(o); for (i = 0; i < searches.length; i++) if (Geo.distance([x, y], searches[i][0]) <= searches[i][1]) @@ -23,9 +25,7 @@ for (x = 0; x <= 20; x++) { } for (i = 0; i < searches.length; i++) { - q = { - loc: {$within: {$center: searches[i]}} - }; + q = {loc: {$within: {$center: searches[i]}}}; assert.eq(correct[i].length, t.find(q).itcount(), "itcount : " + tojson(searches[i])); assert.eq(correct[i].length, t.find(q).count(), "count : " + tojson(searches[i])); } diff --git a/jstests/core/geo_distinct.js b/jstests/core/geo_distinct.js index 705bf1cc7ce..33ea7dd3461 100644 --- a/jstests/core/geo_distinct.js +++ b/jstests/core/geo_distinct.js @@ -60,10 +60,7 @@ for (var i = 0; i < 50; ++i) { coll.insert({zone: 4, loc: {type: 'Point', coordinates: [10, 10]}}); coll.insert({zone: 5, loc: {type: 'Point', coordinates: [20, 20]}}); } -var originGeoJSON = { - type: 'Point', - coordinates: [0, 0] -}; +var originGeoJSON = {type: 'Point', coordinates: [0, 0]}; // Test distinct with $nearSphere query predicate. diff --git a/jstests/core/geo_fiddly_box.js b/jstests/core/geo_fiddly_box.js index f5cd3ddcc6b..4e33780112d 100644 --- a/jstests/core/geo_fiddly_box.js +++ b/jstests/core/geo_fiddly_box.js @@ -19,9 +19,8 @@ t.insert({"loc": [3, -1]}); // OK! print(t.count()); -assert.eq(7, - t.count({"loc": {"$within": {"$box": [[2, -2], [46, 2]]}}}), - "Not all locations found!"); +assert.eq( + 7, t.count({"loc": {"$within": {"$box": [[2, -2], [46, 2]]}}}), "Not all locations found!"); // Test normal lookup of a small square of points as a sanity check. diff --git a/jstests/core/geo_group.js b/jstests/core/geo_group.js index 9ee5a76b7ea..34ecc2c3a84 100644 --- a/jstests/core/geo_group.js +++ b/jstests/core/geo_group.js @@ -20,22 +20,18 @@ assert.eq(t.find({loc: {$near: [56, 8, 10]}}).count(), 81); // Test basic group that effectively does a count assert.eq(t.group({ reduce: function(obj, prev) { - prev.sums = { - count: prev.sums.count + 1 - }; + prev.sums = {count: prev.sums.count + 1}; }, initial: {sums: {count: 0}} }), - [{"sums": {"count": 10000}}]); + [{"sums": {"count": 10000}}]); // Test basic group + $near that does a count assert.eq(t.group({ reduce: function(obj, prev) { - prev.sums = { - count: prev.sums.count + 1 - }; + prev.sums = {count: prev.sums.count + 1}; }, initial: {sums: {count: 0}}, cond: {loc: {$near: [56, 8, 10]}} }), - [{"sums": {"count": 81}}]); + [{"sums": {"count": 81}}]); diff --git a/jstests/core/geo_haystack1.js b/jstests/core/geo_haystack1.js index 5abb166a6f9..97e746ccdfa 100644 --- a/jstests/core/geo_haystack1.js +++ b/jstests/core/geo_haystack1.js @@ -16,13 +16,12 @@ function distanceTotal(a, arr, f) { return total; } -queries = [{near: [7, 8], maxDistance: 3, search: {z: 3}}, ]; +queries = [ + {near: [7, 8], maxDistance: 3, search: {z: 3}}, +]; answers = queries.map(function() { - return { - totalDistance: 0, - results: [] - }; + return {totalDistance: 0, results: []}; }); n = 0; diff --git a/jstests/core/geo_haystack2.js b/jstests/core/geo_haystack2.js index cb684239a63..3420feeed1c 100644 --- a/jstests/core/geo_haystack2.js +++ b/jstests/core/geo_haystack2.js @@ -16,13 +16,12 @@ function distanceTotal(a, arr, f) { return total; } -queries = [{near: [7, 8], maxDistance: 3, search: {z: 3}}, ]; +queries = [ + {near: [7, 8], maxDistance: 3, search: {z: 3}}, +]; answers = queries.map(function() { - return { - totalDistance: 0, - results: [] - }; + return {totalDistance: 0, results: []}; }); n = 0; diff --git a/jstests/core/geo_invalid_polygon.js b/jstests/core/geo_invalid_polygon.js index c3d244a504f..0eab7ca5406 100644 --- a/jstests/core/geo_invalid_polygon.js +++ b/jstests/core/geo_invalid_polygon.js @@ -5,10 +5,7 @@ t.drop(); // Self-intersecting polygon, triggers // "Exterior shell of polygon is invalid". -var geometry = { - type: "Polygon", - coordinates: [[[0, 0], [0, 1], [1, 1], [-2, -1], [0, 0]]] -}; +var geometry = {type: "Polygon", coordinates: [[[0, 0], [0, 1], [1, 1], [-2, -1], [0, 0]]]}; t.insert({_id: 42, geometry: geometry}); var err = t.createIndex({geometry: '2dsphere'}); diff --git a/jstests/core/geo_mapreduce.js b/jstests/core/geo_mapreduce.js index e15a4911763..ebea034d00c 100644 --- a/jstests/core/geo_mapreduce.js +++ b/jstests/core/geo_mapreduce.js @@ -32,9 +32,7 @@ r = function(key, values) { for (var i = 0; i < values.length; i++) { total += values[i].apples; } - return { - "apples": total - }; + return {"apples": total}; }; // mapreduce without geo query works fine diff --git a/jstests/core/geo_mapreduce2.js b/jstests/core/geo_mapreduce2.js index d71eb8ef216..679b6474cc9 100644 --- a/jstests/core/geo_mapreduce2.js +++ b/jstests/core/geo_mapreduce2.js @@ -21,19 +21,15 @@ r = function(key, values) { total += values[i].count; } - return { - count: total - }; + return {count: total}; }; try { - coll.mapReduce(m, - r, - { - out: coll.getName() + "_mr", - sort: {_id: 1}, - query: {'location': {$within: {$centerSphere: [[10, 20], 0.01]}}} - }); + coll.mapReduce(m, r, { + out: coll.getName() + "_mr", + sort: {_id: 1}, + query: {'location': {$within: {$centerSphere: [[10, 20], 0.01]}}} + }); } catch (e) { // This should occur, since we can't in-mem sort for mreduce diff --git a/jstests/core/geo_mindistance.js b/jstests/core/geo_mindistance.js index 6a2329bc524..4bbb77db9bf 100644 --- a/jstests/core/geo_mindistance.js +++ b/jstests/core/geo_mindistance.js @@ -47,12 +47,7 @@ for (var x = 0; x <= 10; x += 1) { /* $minDistance is supported for 2dsphere index only, not 2d or geoHaystack. */ t.ensureIndex({loc: "2dsphere"}); -var n_docs = t.count(), geoJSONPoint = - { - type: 'Point', - coordinates: [0, 0] - }, - legacyPoint = [0, 0]; +var n_docs = t.count(), geoJSONPoint = {type: 'Point', coordinates: [0, 0]}, legacyPoint = [0, 0]; // // Test $near with GeoJSON point (required for $near with 2dsphere index). @@ -67,9 +62,10 @@ assert.eq(n_docs - n_docs_within(1400), "Expected " + (n_docs - n_docs_within(1400)) + " points $near (0, 0) with $minDistance 1400 km, got " + n_min1400_count); -var n_bw500_and_1000_count = t.find({ - loc: {$near: {$geometry: geoJSONPoint, $minDistance: 500 * km, $maxDistance: 1000 * km}} -}).count(); +var n_bw500_and_1000_count = + t.find({ + loc: {$near: {$geometry: geoJSONPoint, $minDistance: 500 * km, $maxDistance: 1000 * km}} + }).count(); assert.eq(n_docs_within(1000) - n_docs_within(500), n_bw500_and_1000_count, @@ -92,12 +88,12 @@ assert.eq(n_docs - n_docs_within(1400), " points $nearSphere (0, 0) with $minDistance 1400 km, got " + n_min1400_count); n_bw500_and_1000_count = t.find({ - loc: { - $nearSphere: legacyPoint, - $minDistance: metersToRadians(500 * km), - $maxDistance: metersToRadians(1000 * km) - } -}).count(); + loc: { + $nearSphere: legacyPoint, + $minDistance: metersToRadians(500 * km), + $maxDistance: metersToRadians(1000 * km) + } + }).count(); assert.eq(n_docs_within(1000) - n_docs_within(500), n_bw500_and_1000_count, @@ -118,8 +114,9 @@ assert.eq(n_docs - n_docs_within(1400), " points $nearSphere (0, 0) with $minDistance 1400 km, got " + n_min1400_count); n_bw500_and_1000_count = - t.find({loc: {$nearSphere: geoJSONPoint, $minDistance: 500 * km, $maxDistance: 1000 * km}}) - .count(); + t.find({ + loc: {$nearSphere: geoJSONPoint, $minDistance: 500 * km, $maxDistance: 1000 * km} + }).count(); assert.eq(n_docs_within(1000) - n_docs_within(500), n_bw500_and_1000_count, diff --git a/jstests/core/geo_mindistance_boundaries.js b/jstests/core/geo_mindistance_boundaries.js index 6cbae8015e9..7e97732dfd1 100644 --- a/jstests/core/geo_mindistance_boundaries.js +++ b/jstests/core/geo_mindistance_boundaries.js @@ -12,11 +12,7 @@ t.ensureIndex({loc: "2dsphere"}); // Useful constants. // -var km = 1000, earthRadiusMeters = 6378.1 * km, geoJSONPoint = - { - type: 'Point', - coordinates: [0, 0] - }, +var km = 1000, earthRadiusMeters = 6378.1 * km, geoJSONPoint = {type: 'Point', coordinates: [0, 0]}, // One degree of longitude at the equator, about 111 km. degreeInMeters = 2 * Math.PI * earthRadiusMeters / 360, metersEpsilon = Number.MIN_VALUE; @@ -43,33 +39,37 @@ assert.eq(1, assert.eq( 1, - t.find({loc: {$near: {$geometry: geoJSONPoint, $minDistance: degreeInMeters - metersEpsilon}}}) - .itcount(), + t.find({ + loc: {$near: {$geometry: geoJSONPoint, $minDistance: degreeInMeters - metersEpsilon}} + }).itcount(), "Expected to find (0, 1) within $minDistance (1 degree - epsilon) from origin"); assert.eq( 0, - t.find({loc: {$near: {$geometry: geoJSONPoint, $minDistance: degreeInMeters + metersEpsilon}}}) - .itcount(), + t.find({ + loc: {$near: {$geometry: geoJSONPoint, $minDistance: degreeInMeters + metersEpsilon}} + }).itcount(), "Expected *not* to find (0, 1) within $minDistance (1 degree + epsilon) from origin"); // // Test boundary conditions for $nearSphere and GeoJSON, in meters. // -assert.eq(1, - t.find({loc: {$nearSphere: {$geometry: geoJSONPoint, $minDistance: degreeInMeters}}}) - .itcount(), - "Expected to find (0, 1) within $minDistance 1 degree from origin"); +assert.eq( + 1, + t.find({loc: {$nearSphere: {$geometry: geoJSONPoint, $minDistance: degreeInMeters}}}).itcount(), + "Expected to find (0, 1) within $minDistance 1 degree from origin"); assert.eq(1, - t.find({loc: {$nearSphere: geoJSONPoint, $minDistance: degreeInMeters - metersEpsilon}}) - .itcount(), + t.find({ + loc: {$nearSphere: geoJSONPoint, $minDistance: degreeInMeters - metersEpsilon} + }).itcount(), "Expected to find (0, 1) within $minDistance (1 degree - epsilon) from origin"); assert.eq(0, - t.find({loc: {$nearSphere: geoJSONPoint, $minDistance: degreeInMeters + metersEpsilon}}) - .itcount(), + t.find({ + loc: {$nearSphere: geoJSONPoint, $minDistance: degreeInMeters + metersEpsilon} + }).itcount(), "Expected *not* to find (0, 1) within $minDistance (1 degree + epsilon) from origin"); // @@ -90,11 +90,13 @@ assert.eq(1, "Expected to find (0, 1) within $minDistance 1 degree from origin"); assert.eq(1, - t.find({loc: {$nearSphere: legacyPoint, $minDistance: degreeInRadians - radiansEpsilon}}) - .itcount(), + t.find({ + loc: {$nearSphere: legacyPoint, $minDistance: degreeInRadians - radiansEpsilon} + }).itcount(), "Expected to find (0, 1) within $minDistance (1 degree - epsilon) from origin"); assert.eq(0, - t.find({loc: {$nearSphere: legacyPoint, $minDistance: degreeInRadians + radiansEpsilon}}) - .itcount(), + t.find({ + loc: {$nearSphere: legacyPoint, $minDistance: degreeInRadians + radiansEpsilon} + }).itcount(), "Expected *not* to find (0, 1) within $minDistance (1 degree + epsilon) from origin"); diff --git a/jstests/core/geo_operator_crs.js b/jstests/core/geo_operator_crs.js index b9e242309dc..13353f2262d 100644 --- a/jstests/core/geo_operator_crs.js +++ b/jstests/core/geo_operator_crs.js @@ -12,15 +12,9 @@ coll.drop(); assert.commandWorked(coll.ensureIndex({geo: "2dsphere"})); var legacyZeroPt = [0, 0]; -var jsonZeroPt = { - type: "Point", - coordinates: [0, 0] -}; +var jsonZeroPt = {type: "Point", coordinates: [0, 0]}; var legacy90Pt = [90, 0]; -var json90Pt = { - type: "Point", - coordinates: [90, 0] -}; +var json90Pt = {type: "Point", coordinates: [90, 0]}; assert.writeOK(coll.insert({geo: json90Pt})); diff --git a/jstests/core/geo_or.js b/jstests/core/geo_or.js index 20eb7b7dce1..341ce32d397 100644 --- a/jstests/core/geo_or.js +++ b/jstests/core/geo_or.js @@ -30,54 +30,54 @@ assert.throws(function() { assert.eq(2, t.find({ - $or: [ - {loc: {$geoWithin: {$centerSphere: [p, 10]}}}, - {loc: {$geoWithin: {$centerSphere: [p, 10]}}} - ] - }).itcount(), + $or: [ + {loc: {$geoWithin: {$centerSphere: [p, 10]}}}, + {loc: {$geoWithin: {$centerSphere: [p, 10]}}} + ] + }).itcount(), 'multiple $geoWithin clauses not supported by $or. index type: ' + indexname); +assert.eq( + 2, + t.find({ + $or: [ + {loc: {$geoIntersects: {$geometry: {type: 'LineString', coordinates: [p, q]}}}}, + { + loc: { + $geoIntersects: + {$geometry: {type: 'LineString', coordinates: [[0, 0], [1, 1]]}} + } + } + ] + }).itcount(), + 'multiple $geoIntersects LineString clauses not supported by $or. index type: ' + indexname); assert.eq(2, t.find({ - $or: [ - {loc: {$geoIntersects: {$geometry: {type: 'LineString', coordinates: [p, q]}}}}, - { - loc: { - $geoIntersects: - {$geometry: {type: 'LineString', coordinates: [[0, 0], [1, 1]]}} - } - } - ] - }).itcount(), - 'multiple $geoIntersects LineString clauses not supported by $or. index type: ' + - indexname); -assert.eq(2, - t.find({ - $or: [ - {loc: {$geoIntersects: {$geometry: {type: 'Point', coordinates: p}}}}, - {loc: {$geoIntersects: {$geometry: {type: 'Point', coordinates: q}}}} - ] - }).itcount(), + $or: [ + {loc: {$geoIntersects: {$geometry: {type: 'Point', coordinates: p}}}}, + {loc: {$geoIntersects: {$geometry: {type: 'Point', coordinates: q}}}} + ] + }).itcount(), 'multiple $geoIntersects Point clauses not supported by $or. index type: ' + indexname); assert.eq( 2, t.find({ - $or: [ - { - loc: { - $geoIntersects: - {$geometry: {type: 'Polygon', coordinates: [[[0, 0], p, q, [0, 0]]]}} - } - }, - { - loc: { - $geoIntersects: { - $geometry: - {type: 'Polygon', coordinates: [[[0, 0], [1, 1], [0, 1], [0, 0]]]} - } - } - } - ] - }).itcount(), + $or: [ + { + loc: { + $geoIntersects: + {$geometry: {type: 'Polygon', coordinates: [[[0, 0], p, q, [0, 0]]]}} + } + }, + { + loc: { + $geoIntersects: { + $geometry: + {type: 'Polygon', coordinates: [[[0, 0], [1, 1], [0, 1], [0, 0]]]} + } + } + } + ] + }).itcount(), 'multiple $geoIntersects Polygon clauses not supported by $or. index type: ' + indexname); t.dropIndexes(); @@ -88,9 +88,9 @@ t.ensureIndex({loc: indexname}); assert.eq(2, t.find({ - $or: [ - {loc: {$geoWithin: {$centerSphere: [p, 10]}}}, - {loc: {$geoWithin: {$centerSphere: [p, 10]}}} - ] - }).itcount(), + $or: [ + {loc: {$geoWithin: {$centerSphere: [p, 10]}}}, + {loc: {$geoWithin: {$centerSphere: [p, 10]}}} + ] + }).itcount(), 'multiple $geoWithin clauses not supported by $or. index type: ' + indexname); diff --git a/jstests/core/geo_poly_edge.js b/jstests/core/geo_poly_edge.js index 380fe533861..a8239cde0af 100644 --- a/jstests/core/geo_poly_edge.js +++ b/jstests/core/geo_poly_edge.js @@ -17,6 +17,6 @@ assert.eq(coll.find({loc: {$within: {$polygon: [[10, 10], [10, 10], [10, 10]]}}} coll.insert({loc: [179, 0]}); coll.insert({loc: [0, 179]}); -assert.eq(coll.find({loc: {$within: {$polygon: [[0, 0], [1000, 0], [1000, 1000], [0, 1000]]}}}) - .itcount(), - 3); +assert.eq( + coll.find({loc: {$within: {$polygon: [[0, 0], [1000, 0], [1000, 1000], [0, 1000]]}}}).itcount(), + 3); diff --git a/jstests/core/geo_polygon1.js b/jstests/core/geo_polygon1.js index d1dbf0c19dc..45f0eb71d64 100644 --- a/jstests/core/geo_polygon1.js +++ b/jstests/core/geo_polygon1.js @@ -8,10 +8,7 @@ t.drop(); num = 0; for (x = 1; x < 9; x++) { for (y = 1; y < 9; y++) { - o = { - _id: num++, - loc: [x, y] - }; + o = {_id: num++, loc: [x, y]}; t.save(o); } } @@ -29,15 +26,14 @@ assert.eq(num, t.find({loc: {"$within": {"$polygon": boxBounds}}}).count(), "Bou // Make sure we can add object-based polygons assert.eq( - num, - t.find({loc: {$within: {$polygon: {a: [-10, -10], b: [-10, 10], c: [10, 10], d: [10, -10]}}}}) - .count()); + num, t.find({ + loc: {$within: {$polygon: {a: [-10, -10], b: [-10, 10], c: [10, 10], d: [10, -10]}}} + }).count()); // Look in a box much bigger than the one we have data in boxBounds = [[-100, -100], [-100, 100], [100, 100], [100, -100]]; -assert.eq(num, - t.find({loc: {"$within": {"$polygon": boxBounds}}}).count(), - "Big Bounding Box Test"); +assert.eq( + num, t.find({loc: {"$within": {"$polygon": boxBounds}}}).count(), "Big Bounding Box Test"); t.drop(); diff --git a/jstests/core/geo_polygon1_noindex.js b/jstests/core/geo_polygon1_noindex.js index 22f90e7157c..e5aabb5043d 100644 --- a/jstests/core/geo_polygon1_noindex.js +++ b/jstests/core/geo_polygon1_noindex.js @@ -6,10 +6,7 @@ t.drop(); num = 0; for (x = 1; x < 9; x++) { for (y = 1; y < 9; y++) { - o = { - _id: num++, - loc: [x, y] - }; + o = {_id: num++, loc: [x, y]}; t.save(o); } } @@ -25,15 +22,14 @@ assert.eq(num, t.find({loc: {"$within": {"$polygon": boxBounds}}}).count(), "Bou // Make sure we can add object-based polygons assert.eq( - num, - t.find({loc: {$within: {$polygon: {a: [-10, -10], b: [-10, 10], c: [10, 10], d: [10, -10]}}}}) - .count()); + num, t.find({ + loc: {$within: {$polygon: {a: [-10, -10], b: [-10, 10], c: [10, 10], d: [10, -10]}}} + }).count()); // Look in a box much bigger than the one we have data in boxBounds = [[-100, -100], [-100, 100], [100, 100], [100, -100]]; -assert.eq(num, - t.find({loc: {"$within": {"$polygon": boxBounds}}}).count(), - "Big Bounding Box Test"); +assert.eq( + num, t.find({loc: {"$within": {"$polygon": boxBounds}}}).count(), "Big Bounding Box Test"); t.drop(); diff --git a/jstests/core/geo_polygon3.js b/jstests/core/geo_polygon3.js index ed8f040fa8d..1f81e70adfa 100644 --- a/jstests/core/geo_polygon3.js +++ b/jstests/core/geo_polygon3.js @@ -11,10 +11,7 @@ for (var n = 0; n < numTests; n++) { num = 0; for (x = 1; x < 9; x++) { for (y = 1; y < 9; y++) { - o = { - _id: num++, - loc: [x, y] - }; + o = {_id: num++, loc: [x, y]}; t.save(o); } } diff --git a/jstests/core/geo_s2cursorlimitskip.js b/jstests/core/geo_s2cursorlimitskip.js index 25ae81beb2d..427fbf8fe29 100644 --- a/jstests/core/geo_s2cursorlimitskip.js +++ b/jstests/core/geo_s2cursorlimitskip.js @@ -23,9 +23,7 @@ function insertRandomPoints(num, minDist, maxDist) { for (var i = 0; i < num; i++) { var lat = sign() * (minDist + random() * (maxDist - minDist)); var lng = sign() * (minDist + random() * (maxDist - minDist)); - var point = { - geo: {type: "Point", coordinates: [lng, lat]} - }; + var point = {geo: {type: "Point", coordinates: [lng, lat]}}; assert.writeOK(t.insert(point)); } } @@ -37,8 +35,9 @@ var batchSize = 4; // Insert points between 0.01 and 1.0 away. insertRandomPoints(totalPointCount, 0.01, 1.0); -var cursor = t.find({geo: {$geoNear: {$geometry: {type: "Point", coordinates: [0.0, 0.0]}}}}) - .batchSize(batchSize); +var cursor = t.find({ + geo: {$geoNear: {$geometry: {type: "Point", coordinates: [0.0, 0.0]}}} + }).batchSize(batchSize); assert.eq(cursor.count(), totalPointCount); // Disable profiling in order to drop the system.profile collection. @@ -48,8 +47,8 @@ testDB.setProfilingLevel(0); testDB.system.profile.drop(); // Create 4MB system.profile collection to prevent the 'getmore' operations from overwriting the // original query. -assert.commandWorked(testDB.createCollection("system.profile", - {capped: true, size: 4 * 1024 * 1024})); +assert.commandWorked( + testDB.createCollection("system.profile", {capped: true, size: 4 * 1024 * 1024})); testDB.setProfilingLevel(2); for (var j = 0; j < initialAdvance; j++) { @@ -81,14 +80,16 @@ assert(!cursor.hasNext()); var someLimit = 23; // Make sure limit does something. -cursor = t.find({geo: {$geoNear: {$geometry: {type: "Point", coordinates: [0.0, 0.0]}}}}) - .limit(someLimit); +cursor = t.find({ + geo: {$geoNear: {$geometry: {type: "Point", coordinates: [0.0, 0.0]}}} + }).limit(someLimit); // Count doesn't work here -- ignores limit/skip, so we use itcount. assert.eq(cursor.itcount(), someLimit); // Make sure skip works by skipping some stuff ourselves. var someSkip = 3; -cursor = t.find({geo: {$geoNear: {$geometry: {type: "Point", coordinates: [0.0, 0.0]}}}}) - .limit(someLimit + someSkip); +cursor = t.find({ + geo: {$geoNear: {$geometry: {type: "Point", coordinates: [0.0, 0.0]}}} + }).limit(someLimit + someSkip); for (var i = 0; i < someSkip; ++i) { cursor.next(); } diff --git a/jstests/core/geo_s2descindex.js b/jstests/core/geo_s2descindex.js index d6dca95213d..daf5531b31d 100644 --- a/jstests/core/geo_s2descindex.js +++ b/jstests/core/geo_s2descindex.js @@ -5,24 +5,14 @@ var coll = db.getCollection("twodspheredesc"); var descriptors = [["field1", -1], ["field2", -1], ["coordinates", "2dsphere"]]; -var docA = { - field1: "a", - field2: 1, - coordinates: [-118.2400013, 34.073893] -}; -var docB = { - field1: "b", - field2: 1, - coordinates: [-118.2400012, 34.073894] -}; +var docA = {field1: "a", field2: 1, coordinates: [-118.2400013, 34.073893]}; +var docB = {field1: "b", field2: 1, coordinates: [-118.2400012, 34.073894]}; // Try both regular and near index cursors var query = { coordinates: {$geoWithin: {$centerSphere: [[-118.240013, 34.073893], 0.44915760491198753]}} }; -var queryNear = { - coordinates: {$geoNear: {"type": "Point", "coordinates": [0, 0]}} -}; +var queryNear = {coordinates: {$geoNear: {"type": "Point", "coordinates": [0, 0]}}}; // // The idea here is we try "2dsphere" indexes in combination with descending diff --git a/jstests/core/geo_s2disjoint_holes.js b/jstests/core/geo_s2disjoint_holes.js index a3988e9a614..f7731b416e4 100644 --- a/jstests/core/geo_s2disjoint_holes.js +++ b/jstests/core/geo_s2disjoint_holes.js @@ -8,18 +8,14 @@ // http://geojson.org/geojson-spec.html#polygon // -var t = db.geo_s2disjoint_holes, coordinates = [ - // One square. - [[9, 9], [9, 11], [11, 11], [11, 9], [9, 9]], - // Another disjoint square. - [[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]] -], - poly = - { - type: 'Polygon', - coordinates: coordinates - }, - multiPoly = { +var t = db.geo_s2disjoint_holes, coordinates = + [ + // One square. + [[9, 9], [9, 11], [11, 11], [11, 9], [9, 9]], + // Another disjoint square. + [[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]] + ], + poly = {type: 'Polygon', coordinates: coordinates}, multiPoly = { type: 'MultiPolygon', // Multi-polygon's coordinates are wrapped in one more array. coordinates: [coordinates] diff --git a/jstests/core/geo_s2dupe_points.js b/jstests/core/geo_s2dupe_points.js index 63e4369d2fa..406a7b1ff4c 100644 --- a/jstests/core/geo_s2dupe_points.js +++ b/jstests/core/geo_s2dupe_points.js @@ -28,10 +28,7 @@ var lineWithDupes = { _id: "line", geo: {type: "LineString", coordinates: [[40, 5], [40, 5], [40, 5], [41, 6], [41, 6]]} }; -var lineWithoutDupes = { - type: "LineString", - coordinates: [[40, 5], [41, 6]] -}; +var lineWithoutDupes = {type: "LineString", coordinates: [[40, 5], [41, 6]]}; // Polygon var polygonWithDupes = { diff --git a/jstests/core/geo_s2explain.js b/jstests/core/geo_s2explain.js index c8d32e00379..97f45e89a68 100644 --- a/jstests/core/geo_s2explain.js +++ b/jstests/core/geo_s2explain.js @@ -4,12 +4,8 @@ var t = db.jstests_geo_s2explain; t.drop(); -var point1 = { - loc: {type: "Point", coordinates: [10, 10]} -}; -var point2 = { - loc: {type: "Point", coordinates: [10.001, 10]} -}; +var point1 = {loc: {type: "Point", coordinates: [10, 10]}}; +var point2 = {loc: {type: "Point", coordinates: [10.001, 10]}}; assert.writeOK(t.insert([point1, point2])); assert.commandWorked(t.ensureIndex({loc: "2dsphere"})); diff --git a/jstests/core/geo_s2holesameasshell.js b/jstests/core/geo_s2holesameasshell.js index 29f00b88f7a..5407fe45c26 100644 --- a/jstests/core/geo_s2holesameasshell.js +++ b/jstests/core/geo_s2holesameasshell.js @@ -3,18 +3,9 @@ var t = db.geo_s2holessameasshell; t.drop(); t.ensureIndex({geo: "2dsphere"}); -var centerPoint = { - "type": "Point", - "coordinates": [0.5, 0.5] -}; -var edgePoint = { - "type": "Point", - "coordinates": [0, 0.5] -}; -var cornerPoint = { - "type": "Point", - "coordinates": [0, 0] -}; +var centerPoint = {"type": "Point", "coordinates": [0.5, 0.5]}; +var edgePoint = {"type": "Point", "coordinates": [0, 0.5]}; +var cornerPoint = {"type": "Point", "coordinates": [0, 0]}; // Various "edge" cases. None of them should be returned by the non-polygon // polygon below. diff --git a/jstests/core/geo_s2index.js b/jstests/core/geo_s2index.js index cc25b4fabfe..99c3852aae9 100644 --- a/jstests/core/geo_s2index.js +++ b/jstests/core/geo_s2index.js @@ -89,10 +89,12 @@ assert.throws(function() { return t.count({loc: {$foo: [0, 0]}}); }); assert.throws(function() { - return t.find({ - "nonGeo": "pointA", - "geo": {"$geoIntersects": {"$geometry": somepoly}, "$near": {"$geometry": somepoly}} - }).count(); + return t + .find({ + "nonGeo": "pointA", + "geo": {"$geoIntersects": {"$geometry": somepoly}, "$near": {"$geometry": somepoly}} + }) + .count(); }); // If we specify a datum, it has to be valid (WGS84). diff --git a/jstests/core/geo_s2indexversion1.js b/jstests/core/geo_s2indexversion1.js index 49aa80dbbca..4fa58bb589f 100644 --- a/jstests/core/geo_s2indexversion1.js +++ b/jstests/core/geo_s2indexversion1.js @@ -106,15 +106,9 @@ coll.drop(); // Test compatibility of various GeoJSON objects with both 2dsphere index versions. // -var pointDoc = { - geo: {type: "Point", coordinates: [40, 5]} -}; -var lineStringDoc = { - geo: {type: "LineString", coordinates: [[40, 5], [41, 6]]} -}; -var polygonDoc = { - geo: {type: "Polygon", coordinates: [[[0, 0], [3, 6], [6, 1], [0, 0]]]} -}; +var pointDoc = {geo: {type: "Point", coordinates: [40, 5]}}; +var lineStringDoc = {geo: {type: "LineString", coordinates: [[40, 5], [41, 6]]}}; +var polygonDoc = {geo: {type: "Polygon", coordinates: [[[0, 0], [3, 6], [6, 1], [0, 0]]]}}; var multiPointDoc = { geo: { type: "MultiPoint", @@ -144,12 +138,7 @@ var multiPolygonDoc = { [-73.9814, 40.7681], [-73.958, 40.8003] ]], - [[ - [-73.958, 40.8003], - [-73.9498, 40.7968], - [-73.9737, 40.7648], - [-73.958, 40.8003] - ]] + [[[-73.958, 40.8003], [-73.9498, 40.7968], [-73.9737, 40.7648], [-73.958, 40.8003]]] ] } }; diff --git a/jstests/core/geo_s2intersection.js b/jstests/core/geo_s2intersection.js index bf65c02c0c2..faf9304396c 100644 --- a/jstests/core/geo_s2intersection.js +++ b/jstests/core/geo_s2intersection.js @@ -10,10 +10,7 @@ var canonLine = { geo: {type: "LineString", coordinates: [[0.0, 0.0], [1.0, 0.0]]} }; -var canonPoint = { - name: 'canonPoint', - geo: {type: "Point", coordinates: [10.0, 10.0]} -}; +var canonPoint = {name: 'canonPoint', geo: {type: "Point", coordinates: [10.0, 10.0]}}; var canonPoly = { name: 'canonPoly', @@ -28,10 +25,7 @@ t.insert(canonPoint); t.insert(canonPoly); // Case 1: Basic sanity intersection. -var testLine = { - type: "LineString", - coordinates: [[0.5, 0.5], [0.5, -0.5]] -}; +var testLine = {type: "LineString", coordinates: [[0.5, 0.5], [0.5, -0.5]]}; var result = t.find({geo: {$geoIntersects: {$geometry: testLine}}}); assert.eq(result.count(), 1); @@ -127,10 +121,7 @@ assert.eq(result.count(), 1); assert.eq(result[0]['name'], 'canonPoint'); // Case 10: Sanity point non-intersection. -var testPoint = { - type: "Point", - coordinates: [12.0, 12.0] -}; +var testPoint = {type: "Point", coordinates: [12.0, 12.0]}; result = t.find({geo: {$geoIntersects: {$geometry: testPoint}}}); assert.eq(result.count(), 0); @@ -152,12 +143,8 @@ t.drop(); t.ensureIndex({a: "2dsphere"}); t.insert({a: {type: "Polygon", coordinates: [[[0, 0], [3, 6], [6, 0], [0, 0]]]}}); -var firstPoint = { - $geometry: {type: "Point", coordinates: [3.0, 1.0]} -}; -var secondPoint = { - $geometry: {type: "Point", coordinates: [4.0, 1.0]} -}; +var firstPoint = {$geometry: {type: "Point", coordinates: [3.0, 1.0]}}; +var secondPoint = {$geometry: {type: "Point", coordinates: [4.0, 1.0]}}; // First point should intersect with the polygon. result = t.find({a: {$geoIntersects: firstPoint}}); diff --git a/jstests/core/geo_s2multi.js b/jstests/core/geo_s2multi.js index 2cd6a3d73d7..8899c9d5561 100644 --- a/jstests/core/geo_s2multi.js +++ b/jstests/core/geo_s2multi.js @@ -28,39 +28,39 @@ multiPolygonA = { }; assert.writeOK(t.insert({geo: multiPolygonA})); -assert.eq(3, - t.find({geo: {$geoIntersects: {$geometry: {"type": "Point", "coordinates": [100, 0]}}}}) - .itcount()); +assert.eq(3, t.find({ + geo: {$geoIntersects: {$geometry: {"type": "Point", "coordinates": [100, 0]}}} + }).itcount()); assert.eq(3, t.find({ - geo: {$geoIntersects: {$geometry: {"type": "Point", "coordinates": [101.0, 1.0]}}} - }).itcount()); + geo: {$geoIntersects: {$geometry: {"type": "Point", "coordinates": [101.0, 1.0]}}} + }).itcount()); // Inside the hole in multiPolygonA assert.eq( - 0, - t.find({geo: {$geoIntersects: {$geometry: {"type": "Point", "coordinates": [100.21, 0.21]}}}}) - .itcount()); + 0, t.find({ + geo: {$geoIntersects: {$geometry: {"type": "Point", "coordinates": [100.21, 0.21]}}} + }).itcount()); // One point inside the hole, one out. assert.eq( 3, t.find({ - geo: { - $geoIntersects: - {$geometry: {"type": "MultiPoint", "coordinates": [[100, 0], [100.21, 0.21]]}} - } - }).itcount()); + geo: { + $geoIntersects: + {$geometry: {"type": "MultiPoint", "coordinates": [[100, 0], [100.21, 0.21]]}} + } + }).itcount()); assert.eq( 3, t.find({ - geo: { - $geoIntersects: { - $geometry: - {"type": "MultiPoint", "coordinates": [[100, 0], [100.21, 0.21], [101, 1]]} - } - } - }).itcount()); + geo: { + $geoIntersects: { + $geometry: + {"type": "MultiPoint", "coordinates": [[100, 0], [100.21, 0.21], [101, 1]]} + } + } + }).itcount()); // Polygon contains itself and the multipoint. assert.eq(2, t.find({geo: {$geoWithin: {$geometry: multiPolygonA}}}).itcount()); diff --git a/jstests/core/geo_s2near.js b/jstests/core/geo_s2near.js index 08bf5ab9081..f8bacf350b4 100644 --- a/jstests/core/geo_s2near.js +++ b/jstests/core/geo_s2near.js @@ -90,8 +90,8 @@ function testRadAndDegreesOK(distance) { assert.eq(resRadians.itcount(), resMeters.itcount()); // Also, geoNear should behave the same way. - resGNMeters = db.runCommand( - {geoNear: t.getName(), near: origin, maxDistance: distance, spherical: true}); + resGNMeters = + db.runCommand({geoNear: t.getName(), near: origin, maxDistance: distance, spherical: true}); resGNRadians = db.runCommand({ geoNear: t.getName(), near: [0, 0], diff --git a/jstests/core/geo_s2nearComplex.js b/jstests/core/geo_s2nearComplex.js index 0584c5e694a..bf9c76ffde4 100644 --- a/jstests/core/geo_s2nearComplex.js +++ b/jstests/core/geo_s2nearComplex.js @@ -11,15 +11,9 @@ var sin = Math.sin; var cos = Math.cos; var atan2 = Math.atan2; -var originGeo = { - type: "Point", - coordinates: [20.0, 20.0] -}; +var originGeo = {type: "Point", coordinates: [20.0, 20.0]}; // Center point for all tests. -var origin = { - name: "origin", - geo: originGeo -}; +var origin = {name: "origin", geo: originGeo}; /* * Convenience function for checking that coordinates match. threshold let's you @@ -163,9 +157,7 @@ function validateOrdering(query) { } } -var query = { - geo: {$geoNear: {$geometry: originGeo}} -}; +var query = {geo: {$geoNear: {$geometry: originGeo}}}; // Test a uniform distribution of 1000 points. uniformPoints(origin, 1000, 0.5, 1.5); diff --git a/jstests/core/geo_s2near_equator_opposite.js b/jstests/core/geo_s2near_equator_opposite.js index 13bbc776daa..754c27e523d 100644 --- a/jstests/core/geo_s2near_equator_opposite.js +++ b/jstests/core/geo_s2near_equator_opposite.js @@ -14,12 +14,16 @@ t.ensureIndex({loc: '2dsphere'}); // upper bound for half of earth's circumference in meters var dist = 40075000 / 2 + 1; -var nearSphereCount = t.find({ - loc: {$nearSphere: {$geometry: {type: 'Point', coordinates: [180, 0]}, $maxDistance: dist}} -}).itcount(); +var nearSphereCount = + t.find({ + loc: { + $nearSphere: {$geometry: {type: 'Point', coordinates: [180, 0]}, $maxDistance: dist} + } + }).itcount(); var nearCount = - t.find({loc: {$near: {$geometry: {type: 'Point', coordinates: [180, 0]}, $maxDistance: dist}}}) - .itcount(); + t.find({ + loc: {$near: {$geometry: {type: 'Point', coordinates: [180, 0]}, $maxDistance: dist}} + }).itcount(); var geoNearResult = db.runCommand( {geoNear: t.getName(), near: {type: 'Point', coordinates: [180, 0]}, spherical: true}); diff --git a/jstests/core/geo_s2nongeoarray.js b/jstests/core/geo_s2nongeoarray.js index 8684706d168..4b210f8f779 100644 --- a/jstests/core/geo_s2nongeoarray.js +++ b/jstests/core/geo_s2nongeoarray.js @@ -4,11 +4,7 @@ t = db.geo_s2nongeoarray; oldPoint = [40, 5]; -var data = { - geo: oldPoint, - nonGeo: [123, 456], - otherNonGeo: [{b: [1, 2]}, {b: [3, 4]}] -}; +var data = {geo: oldPoint, nonGeo: [123, 456], otherNonGeo: [{b: [1, 2]}, {b: [3, 4]}]}; t.drop(); assert.writeOK(t.insert(data)); diff --git a/jstests/core/geo_s2nonstring.js b/jstests/core/geo_s2nonstring.js index 43587f0c8e8..960f0c727a8 100644 --- a/jstests/core/geo_s2nonstring.js +++ b/jstests/core/geo_s2nonstring.js @@ -14,15 +14,13 @@ t.save({geo: {type: 'Point', coordinates: [0, 0]}, x: 'a'}); t.save({geo: {type: 'Point', coordinates: [0, 0]}}); // Expect 1 match, where x is 'a' -assert.eq(1, - t.count({ - geo: {$near: {$geometry: {type: 'Point', coordinates: [0, 0]}, $maxDistance: 20}}, - x: 'a' - })); +assert.eq(1, t.count({ + geo: {$near: {$geometry: {type: 'Point', coordinates: [0, 0]}, $maxDistance: 20}}, + x: 'a' +})); // Expect 1 match, where x matches null (missing matches null). -assert.eq(1, - t.count({ - geo: {$near: {$geometry: {type: 'Point', coordinates: [0, 0]}, $maxDistance: 20}}, - x: null - })); +assert.eq(1, t.count({ + geo: {$near: {$geometry: {type: 'Point', coordinates: [0, 0]}, $maxDistance: 20}}, + x: null +})); diff --git a/jstests/core/geo_s2oddshapes.js b/jstests/core/geo_s2oddshapes.js index 6f14533c928..4ae953696a0 100644 --- a/jstests/core/geo_s2oddshapes.js +++ b/jstests/core/geo_s2oddshapes.js @@ -5,10 +5,7 @@ var t = db.geo_s2oddshapes; t.drop(); t.ensureIndex({geo: "2dsphere"}); -var testPoint = { - name: "origin", - geo: {type: "Point", coordinates: [0.0, 0.0]} -}; +var testPoint = {name: "origin", geo: {type: "Point", coordinates: [0.0, 0.0]}}; var testHorizLine = { name: "horiz", @@ -60,10 +57,7 @@ assert.eq(result.itcount(), 3); t.drop(); t.ensureIndex({geo: "2dsphere"}); -var insidePoint = { - name: "inside", - geo: {type: "Point", name: "inside", coordinates: [100.0, 0.0]} -}; +var insidePoint = {name: "inside", geo: {type: "Point", name: "inside", coordinates: [100.0, 0.0]}}; var outsidePoint = { name: "inside", diff --git a/jstests/core/geo_s2polywithholes.js b/jstests/core/geo_s2polywithholes.js index 6ace711c718..80f7b0556c4 100644 --- a/jstests/core/geo_s2polywithholes.js +++ b/jstests/core/geo_s2polywithholes.js @@ -2,18 +2,9 @@ var t = db.geo_s2weirdpolys; t.drop(); t.ensureIndex({geo: "2dsphere"}); -var centerPoint = { - "type": "Point", - "coordinates": [0.5, 0.5] -}; -var edgePoint = { - "type": "Point", - "coordinates": [0, 0.5] -}; -var cornerPoint = { - "type": "Point", - "coordinates": [0, 0] -}; +var centerPoint = {"type": "Point", "coordinates": [0.5, 0.5]}; +var edgePoint = {"type": "Point", "coordinates": [0, 0.5]}; +var cornerPoint = {"type": "Point", "coordinates": [0, 0]}; t.insert({geo: centerPoint}); t.insert({geo: edgePoint}); diff --git a/jstests/core/geo_s2sparse.js b/jstests/core/geo_s2sparse.js index ab3363b5860..d31905b5a92 100644 --- a/jstests/core/geo_s2sparse.js +++ b/jstests/core/geo_s2sparse.js @@ -3,15 +3,9 @@ var coll = db.geo_s2sparse; -var point = { - type: "Point", - coordinates: [5, 5] -}; - -var indexSpec = { - geo: "2dsphere", - nonGeo: 1 -}; +var point = {type: "Point", coordinates: [5, 5]}; + +var indexSpec = {geo: "2dsphere", nonGeo: 1}; var indexName = 'test.geo_s2sparse.$geo_2dsphere_nonGeo_1'; diff --git a/jstests/core/geo_s2twofields.js b/jstests/core/geo_s2twofields.js index 1868287cf5b..564d6fcd91a 100644 --- a/jstests/core/geo_s2twofields.js +++ b/jstests/core/geo_s2twofields.js @@ -13,14 +13,8 @@ function randomCoord(center, minDistDeg, maxDistDeg) { return [center[0] + dx, center[1] + dy]; } -var nyc = { - type: "Point", - coordinates: [-74.0064, 40.7142] -}; -var miami = { - type: "Point", - coordinates: [-80.1303, 25.7903] -}; +var nyc = {type: "Point", coordinates: [-74.0064, 40.7142]}; +var miami = {type: "Point", coordinates: [-80.1303, 25.7903]}; var maxPoints = 10000; var degrees = 5; @@ -29,10 +23,8 @@ for (var i = 0; i < maxPoints; ++i) { var fromCoord = randomCoord(nyc.coordinates, 0, degrees); var toCoord = randomCoord(miami.coordinates, 0, degrees); - arr.push({ - from: {type: "Point", coordinates: fromCoord}, - to: {type: "Point", coordinates: toCoord} - }); + arr.push( + {from: {type: "Point", coordinates: fromCoord}, to: {type: "Point", coordinates: toCoord}}); } res = t.insert(arr); assert.writeOK(res); @@ -65,31 +57,25 @@ function timeWithoutAndWithAnIndex(index, query) { var maxQueryRad = 0.5 * PI / 180.0; // When we're not looking at ALL the data, anything indexed should beat not-indexed. -var smallQuery = - timeWithoutAndWithAnIndex({to: "2dsphere", from: "2dsphere"}, - { - from: {$within: {$centerSphere: [nyc.coordinates, maxQueryRad]}}, - to: {$within: {$centerSphere: [miami.coordinates, maxQueryRad]}} - }); +var smallQuery = timeWithoutAndWithAnIndex({to: "2dsphere", from: "2dsphere"}, { + from: {$within: {$centerSphere: [nyc.coordinates, maxQueryRad]}}, + to: {$within: {$centerSphere: [miami.coordinates, maxQueryRad]}} +}); print("Indexed time " + smallQuery[1] + " unindexed " + smallQuery[0]); // assert(smallQuery[0] > smallQuery[1]); // Let's just index one field. -var smallQuery = - timeWithoutAndWithAnIndex({to: "2dsphere"}, - { - from: {$within: {$centerSphere: [nyc.coordinates, maxQueryRad]}}, - to: {$within: {$centerSphere: [miami.coordinates, maxQueryRad]}} - }); +var smallQuery = timeWithoutAndWithAnIndex({to: "2dsphere"}, { + from: {$within: {$centerSphere: [nyc.coordinates, maxQueryRad]}}, + to: {$within: {$centerSphere: [miami.coordinates, maxQueryRad]}} +}); print("Indexed time " + smallQuery[1] + " unindexed " + smallQuery[0]); // assert(smallQuery[0] > smallQuery[1]); // And the other one. -var smallQuery = - timeWithoutAndWithAnIndex({from: "2dsphere"}, - { - from: {$within: {$centerSphere: [nyc.coordinates, maxQueryRad]}}, - to: {$within: {$centerSphere: [miami.coordinates, maxQueryRad]}} - }); +var smallQuery = timeWithoutAndWithAnIndex({from: "2dsphere"}, { + from: {$within: {$centerSphere: [nyc.coordinates, maxQueryRad]}}, + to: {$within: {$centerSphere: [miami.coordinates, maxQueryRad]}} +}); print("Indexed time " + smallQuery[1] + " unindexed " + smallQuery[0]); // assert(smallQuery[0] > smallQuery[1]); diff --git a/jstests/core/geo_uniqueDocs.js b/jstests/core/geo_uniqueDocs.js index 8c4e11fc82e..d66d5243c01 100644 --- a/jstests/core/geo_uniqueDocs.js +++ b/jstests/core/geo_uniqueDocs.js @@ -36,9 +36,9 @@ assert.eq(2, t.find({locs: {$within: {$center: [[5, 5], 7], $uniqueDocs: false}} assert.eq(2, t.find({locs: {$within: {$centerSphere: [[5, 5], 1], $uniqueDocs: true}}}).itcount()); assert.eq(2, t.find({locs: {$within: {$centerSphere: [[5, 5], 1], $uniqueDocs: false}}}).itcount()); -assert.eq(2, - t.find({locs: {$within: {$polygon: [[0, 0], [0, 9], [9, 9]], $uniqueDocs: true}}}) - .itcount()); -assert.eq(2, - t.find({locs: {$within: {$polygon: [[0, 0], [0, 9], [9, 9]], $uniqueDocs: false}}}) - .itcount()); +assert.eq( + 2, + t.find({locs: {$within: {$polygon: [[0, 0], [0, 9], [9, 9]], $uniqueDocs: true}}}).itcount()); +assert.eq( + 2, + t.find({locs: {$within: {$polygon: [[0, 0], [0, 9], [9, 9]], $uniqueDocs: false}}}).itcount()); diff --git a/jstests/core/geo_uniqueDocs2.js b/jstests/core/geo_uniqueDocs2.js index f6481b30f41..6f5ceed3478 100644 --- a/jstests/core/geo_uniqueDocs2.js +++ b/jstests/core/geo_uniqueDocs2.js @@ -54,30 +54,27 @@ assert(notUniqueInclude.results[0].loc); assert(uniqueInclude.results[0].loc); // For geoNear / uniqueDocs, 'num' limit seems to apply to locs. -assert.eq( - 1, - db.runCommand( - {geoNear: collName, near: [50, 50], num: 1, uniqueDocs: false, includeLocs: false}) - .results.length); +assert.eq(1, + db.runCommand( + {geoNear: collName, near: [50, 50], num: 1, uniqueDocs: false, includeLocs: false}) + .results.length); // Check locs returned in includeLocs mode. t.remove({}); objLocs = [{x: 20, y: 30, z: ['loc1', 'loca']}, {x: 40, y: 50, z: ['loc2', 'locb']}]; t.save({loc: objLocs}); -results = - db.runCommand( - {geoNear: collName, near: [50, 50], num: 10, uniqueDocs: false, includeLocs: true}) - .results; +results = db.runCommand( + {geoNear: collName, near: [50, 50], num: 10, uniqueDocs: false, includeLocs: true}) + .results; assert.contains(results[0].loc, objLocs); // Check locs returned in includeLocs mode, where locs are arrays. t.remove({}); arrLocs = [[20, 30], [40, 50]]; t.save({loc: arrLocs}); -results = - db.runCommand( - {geoNear: collName, near: [50, 50], num: 10, uniqueDocs: false, includeLocs: true}) - .results; +results = db.runCommand( + {geoNear: collName, near: [50, 50], num: 10, uniqueDocs: false, includeLocs: true}) + .results; // The original loc arrays are returned as objects. expectedLocs = arrLocs; diff --git a/jstests/core/geo_update_btree.js b/jstests/core/geo_update_btree.js index ea1025b10a9..a85d4274415 100644 --- a/jstests/core/geo_update_btree.js +++ b/jstests/core/geo_update_btree.js @@ -19,16 +19,13 @@ var parallelInsert = startParallelShell( " db.jstests_geo_update_btree.insert(doc);" + "}"); for (i = 0; i < 1000; i++) { - coll.update( - { - loc: { - $within: - {$center: [[Random.rand() * 180, Random.rand() * 180], Random.rand() * 50]} - } - }, - {$set: {v: big}}, - false, - true); + coll.update({ + loc: + {$within: {$center: [[Random.rand() * 180, Random.rand() * 180], Random.rand() * 50]}} + }, + {$set: {v: big}}, + false, + true); if (i % 10 == 0) print(i); diff --git a/jstests/core/geo_update_dedup.js b/jstests/core/geo_update_dedup.js index b354f3ca7ae..a630954e8ca 100644 --- a/jstests/core/geo_update_dedup.js +++ b/jstests/core/geo_update_dedup.js @@ -9,9 +9,7 @@ t.drop(); t.ensureIndex({locs: "2d"}); t.save({locs: [[49.999, 49.999], [50.0, 50.0], [50.001, 50.001]]}); -var q = { - locs: {$near: [50.0, 50.0]} -}; +var q = {locs: {$near: [50.0, 50.0]}}; assert.eq(1, t.find(q).itcount(), 'duplicates returned from query'); var res = t.update({locs: {$near: [50.0, 50.0]}}, {$inc: {touchCount: 1}}, false, true); diff --git a/jstests/core/geo_withinquery.js b/jstests/core/geo_withinquery.js index 3a71608ab6d..7f712ba1e86 100644 --- a/jstests/core/geo_withinquery.js +++ b/jstests/core/geo_withinquery.js @@ -5,15 +5,16 @@ t.drop(); num = 0; for (x = 0; x <= 20; x++) { for (y = 0; y <= 20; y++) { - o = { - _id: num++, - loc: [x, y] - }; + o = {_id: num++, loc: [x, y]}; t.save(o); } } assert.eq(21 * 21 - 1, - t.find({$and: [{loc: {$ne: [0, 0]}}, {loc: {$within: {$box: [[0, 0], [100, 100]]}}}, ]}) - .itcount(), + t.find({ + $and: [ + {loc: {$ne: [0, 0]}}, + {loc: {$within: {$box: [[0, 0], [100, 100]]}}}, + ] + }).itcount(), "UHOH!"); diff --git a/jstests/core/geob.js b/jstests/core/geob.js index b78eaa453df..c711a676b2b 100644 --- a/jstests/core/geob.js +++ b/jstests/core/geob.js @@ -1,18 +1,10 @@ var t = db.geob; t.drop(); -var a = { - p: [0, 0] -}; -var b = { - p: [1, 0] -}; -var c = { - p: [3, 4] -}; -var d = { - p: [0, 6] -}; +var a = {p: [0, 0]}; +var b = {p: [1, 0]}; +var c = {p: [3, 4]}; +var d = {p: [0, 6]}; t.save(a); t.save(b); diff --git a/jstests/core/geof.js b/jstests/core/geof.js index 1d7f13eb881..4eae803a856 100644 --- a/jstests/core/geof.js +++ b/jstests/core/geof.js @@ -13,9 +13,7 @@ t.insert({loc: [-0.9, 0]}); t.ensureIndex({loc: "2d"}); -t.find({loc: {$near: [0, 0]}}) - .limit(2) - .forEach(function(o) { - // printjson(o); - assert.lt(Geo.distance([0, 0], o.loc), 0.95); - }); +t.find({loc: {$near: [0, 0]}}).limit(2).forEach(function(o) { + // printjson(o); + assert.lt(Geo.distance([0, 0], o.loc), 0.95); +}); diff --git a/jstests/core/geonear_cmd_input_validation.js b/jstests/core/geonear_cmd_input_validation.js index ad3d56d240a..f9cfaa4ff21 100644 --- a/jstests/core/geonear_cmd_input_validation.js +++ b/jstests/core/geonear_cmd_input_validation.js @@ -24,11 +24,7 @@ indexTypes.forEach(function(indexType) { pointDescription = (isLegacy ? "legacy coordinates" : "GeoJSON point"); function makeCommand(distance) { - var command = { - geoNear: t.getName(), - near: pointType, - spherical: spherical - }; + var command = {geoNear: t.getName(), near: pointType, spherical: spherical}; command[optionName] = distance; return command; } @@ -59,16 +55,14 @@ indexTypes.forEach(function(indexType) { } // Try several bad values for min/maxDistance. - badNumbers.concat(outOfRangeDistances) - .forEach(function(badDistance) { + badNumbers.concat(outOfRangeDistances).forEach(function(badDistance) { - var msg = - ("geoNear with spherical=" + spherical + " and " + pointDescription + - " and " + indexType + " index should've failed with " + optionName + - " " + badDistance); + var msg = ("geoNear with spherical=" + spherical + " and " + pointDescription + + " and " + indexType + " index should've failed with " + optionName + + " " + badDistance); - assert.commandFailed(db.runCommand(makeCommand(badDistance)), msg); - }); + assert.commandFailed(db.runCommand(makeCommand(badDistance)), msg); + }); // Bad values for limit / num. ['num', 'limit'].forEach(function(limitOptionName) { diff --git a/jstests/core/getlog2.js b/jstests/core/getlog2.js index b6cf223b967..597a85e20ee 100644 --- a/jstests/core/getlog2.js +++ b/jstests/core/getlog2.js @@ -26,15 +26,14 @@ if (db.isMaster().msg != "isdbgrid") { }); // run a slow update - glcol.update( - { - "SENTINEL": 1, - "$where": function() { - sleep(1000); - return true; - } - }, - {"x": "x"}); + glcol.update({ + "SENTINEL": 1, + "$where": function() { + sleep(1000); + return true; + } + }, + {"x": "x"}); var resp = db.adminCommand({getLog: "global"}); assert(resp.ok == 1, "error executing getLog command"); @@ -42,21 +41,19 @@ if (db.isMaster().msg != "isdbgrid") { assert(resp.log.length > 0, "no log lines"); // ensure that slow query is logged in detail - assert(contains(resp.log, - function(v) { - print(v); - var opString = db.getMongo().useReadCommands() ? " find " : " query "; - var filterString = db.getMongo().useReadCommands() ? "filter:" : "query:"; - return v.indexOf(opString) != -1 && v.indexOf(filterString) != -1 && - v.indexOf("keysExamined:") != -1 && v.indexOf("docsExamined:") != -1 && - v.indexOf("SENTINEL") != -1; - })); + assert(contains(resp.log, function(v) { + print(v); + var opString = db.getMongo().useReadCommands() ? " find " : " query "; + var filterString = db.getMongo().useReadCommands() ? "filter:" : "query:"; + return v.indexOf(opString) != -1 && v.indexOf(filterString) != -1 && + v.indexOf("keysExamined:") != -1 && v.indexOf("docsExamined:") != -1 && + v.indexOf("SENTINEL") != -1; + })); // same, but for update - assert(contains(resp.log, - function(v) { - return v.indexOf(" update ") != -1 && v.indexOf("query") != -1 && - v.indexOf("keysExamined:") != -1 && v.indexOf("docsExamined:") != -1 && - v.indexOf("SENTINEL") != -1; - })); + assert(contains(resp.log, function(v) { + return v.indexOf(" update ") != -1 && v.indexOf("query") != -1 && + v.indexOf("keysExamined:") != -1 && v.indexOf("docsExamined:") != -1 && + v.indexOf("SENTINEL") != -1; + })); } diff --git a/jstests/core/group1.js b/jstests/core/group1.js index 6100ee94c70..5e4fcdea245 100644 --- a/jstests/core/group1.js +++ b/jstests/core/group1.js @@ -88,9 +88,8 @@ p = { initial: {count: 0}, finalize: "abc" }; -assert.commandFailedWithCode(db.runCommand({group: p}), - ErrorCodes.JSInterpreterFailure, - "Illegal finalize function"); +assert.commandFailedWithCode( + db.runCommand({group: p}), ErrorCodes.JSInterpreterFailure, "Illegal finalize function"); p = { ns: "group1", @@ -103,9 +102,8 @@ p = { ob; } }; -assert.commandFailedWithCode(db.runCommand({group: p}), - ErrorCodes.JSInterpreterFailure, - "Illegal finalize function 2"); +assert.commandFailedWithCode( + db.runCommand({group: p}), ErrorCodes.JSInterpreterFailure, "Illegal finalize function 2"); p = { ns: "group1", @@ -118,9 +116,8 @@ p = { ob; } }; -assert.commandFailedWithCode(db.runCommand({group: p}), - ErrorCodes.JSInterpreterFailure, - "Illegal keyf function"); +assert.commandFailedWithCode( + db.runCommand({group: p}), ErrorCodes.JSInterpreterFailure, "Illegal keyf function"); p = { ns: "group1", @@ -128,9 +125,8 @@ p = { $reduce: "abc", initial: {count: 0} }; -assert.commandFailedWithCode(db.runCommand({group: p}), - ErrorCodes.JSInterpreterFailure, - "Illegal reduce function"); +assert.commandFailedWithCode( + db.runCommand({group: p}), ErrorCodes.JSInterpreterFailure, "Illegal reduce function"); p = { ns: "group1", @@ -140,8 +136,7 @@ p = { }, initial: {count: 0} }; -assert.commandFailedWithCode(db.runCommand({group: p}), - ErrorCodes.JSInterpreterFailure, - "Illegal reduce function 2"); +assert.commandFailedWithCode( + db.runCommand({group: p}), ErrorCodes.JSInterpreterFailure, "Illegal reduce function 2"); t.drop(); diff --git a/jstests/core/group2.js b/jstests/core/group2.js index ada675f6f69..1577932beca 100644 --- a/jstests/core/group2.js +++ b/jstests/core/group2.js @@ -25,9 +25,7 @@ assert.eq(1, result[1].count, "G"); assert.eq(1, result[2].count, "H"); var keyFn = function(x) { - return { - a: 'a' in x ? x.a : null - }; + return {a: 'a' in x ? x.a : null}; }; delete cmd.key; diff --git a/jstests/core/grow_hash_table.js b/jstests/core/grow_hash_table.js index b26baae31af..d35ffa65405 100644 --- a/jstests/core/grow_hash_table.js +++ b/jstests/core/grow_hash_table.js @@ -11,12 +11,8 @@ var testDB = db.getSiblingDB('grow_hash_table'); var doTest = function(count) { print('Testing with count of ' + count); testDB.dropDatabase(); - var id = { - data: 1 - }; - var doc = { - _id: id - }; + var id = {data: 1}; + var doc = {_id: id}; var projection = {}; // Create a document and a projection with fields r1, r2, r3 ... diff --git a/jstests/core/hashindex1.js b/jstests/core/hashindex1.js index 778e31d84b2..93986ecfd5e 100644 --- a/jstests/core/hashindex1.js +++ b/jstests/core/hashindex1.js @@ -5,17 +5,12 @@ t.drop(); load("jstests/libs/analyze_plan.js"); // test non-single field hashed indexes don't get created (maybe change later) -var badspec = { - a: "hashed", - b: 1 -}; +var badspec = {a: "hashed", b: 1}; t.ensureIndex(badspec); assert.eq(t.getIndexes().length, 1, "only _id index should be created"); // test unique index not created (maybe change later) -var goodspec = { - a: "hashed" -}; +var goodspec = {a: "hashed"}; t.ensureIndex(goodspec, {"unique": true}); assert.eq(t.getIndexes().length, 1, "unique index got created."); @@ -67,9 +62,7 @@ var explain = t.find({$and: [{a: {$in: [1, 2]}}, {a: {$gt: 1}}]}).explain(); assert(isIxscan(explain.queryPlanner.winningPlan), "not using hashed index"); // test creation of index based on hash of _id index -var goodspec2 = { - '_id': "hashed" -}; +var goodspec2 = {'_id': "hashed"}; t.ensureIndex(goodspec2); assert.eq(t.getIndexes().length, 3, "_id index didn't get created"); @@ -79,9 +72,7 @@ assert.eq(t.find({_id: newid}).hint({_id: 1}).toArray()[0]._id, "using hashed index and different index returns different docs"); // test creation of sparse hashed index -var sparseindex = { - b: "hashed" -}; +var sparseindex = {b: "hashed"}; t.ensureIndex(sparseindex, {"sparse": true}); assert.eq(t.getIndexes().length, 4, "sparse index didn't get created"); diff --git a/jstests/core/hint1.js b/jstests/core/hint1.js index ddee0f369be..6542f9752bc 100644 --- a/jstests/core/hint1.js +++ b/jstests/core/hint1.js @@ -4,13 +4,10 @@ p.drop(); p.save({ts: new Date(1), cls: "entry", verticals: "alleyinsider", live: true}); p.ensureIndex({ts: 1}); -assert.eq(1, - p.find({ - live: true, - ts: {$lt: new Date(1234119308272)}, - cls: "entry", - verticals: "alleyinsider" - }) - .sort({ts: -1}) - .hint({ts: 1}) - .count()); +assert.eq( + 1, + p.find( + {live: true, ts: {$lt: new Date(1234119308272)}, cls: "entry", verticals: "alleyinsider"}) + .sort({ts: -1}) + .hint({ts: 1}) + .count()); diff --git a/jstests/core/idhack.js b/jstests/core/idhack.js index 292c2ed86b6..e26427f4b3c 100644 --- a/jstests/core/idhack.js +++ b/jstests/core/idhack.js @@ -25,9 +25,7 @@ assert.eq(8, t.findOne({_id: 2}).z, "C2"); assert.eq(8, t.findOne({_id: 3}).z, "C3"); // explain output should show that the ID hack was applied. -var query = { - _id: {x: 2} -}; +var query = {_id: {x: 2}}; var explain = t.find(query).explain(true); print("explain for " + tojson(query, "", true) + " = " + tojson(explain)); assert.eq(1, explain.executionStats.nReturned, "D1"); @@ -67,11 +65,10 @@ assert.eq({_id: 0, a: 0}, t.find({_id: 0}, {_id: 1, a: 1}).next()); // Non-simple: exclusion. assert.eq({_id: 1, a: 1}, t.find({_id: 1}, {b: 0}).next()); -assert.eq( - { - _id: 0, - }, - t.find({_id: 0}, {a: 0, b: 0}).next()); +assert.eq({ + _id: 0, +}, + t.find({_id: 0}, {a: 0, b: 0}).next()); // Non-simple: dotted fields. assert.eq({b: [{c: 1}, {c: 2}]}, t.find({_id: 0}, {_id: 0, "b.c": 1}).next()); diff --git a/jstests/core/in5.js b/jstests/core/in5.js index c56621c91f3..772427365b7 100644 --- a/jstests/core/in5.js +++ b/jstests/core/in5.js @@ -4,30 +4,20 @@ t = db.in5; function go(fn) { t.drop(); o = {}; - o[fn] = { - a: 1, - b: 2 - }; + o[fn] = {a: 1, b: 2}; t.insert(o); x = {}; - x[fn] = { - a: 1, - b: 2 - }; + x[fn] = {a: 1, b: 2}; assert.eq(1, t.find(x).itcount(), "A1 - " + fn); y = {}; - y[fn] = { - $in: [{a: 1, b: 2}] - }; + y[fn] = {$in: [{a: 1, b: 2}]}; assert.eq(1, t.find(y).itcount(), "A2 - " + fn); z = {}; z[fn + ".a"] = 1; - z[fn + ".b"] = { - $in: [2] - }; + z[fn + ".b"] = {$in: [2]}; assert.eq(1, t.find(z).itcount(), "A3 - " + fn); // SERVER-1366 i = {}; diff --git a/jstests/core/index_arr2.js b/jstests/core/index_arr2.js index 952be73ff13..a7e541add09 100644 --- a/jstests/core/index_arr2.js +++ b/jstests/core/index_arr2.js @@ -7,10 +7,7 @@ function test(withIndex) { t.drop(); // insert a bunch of items to force queries to use the index. - newObject = { - _id: 1, - a: [{b: {c: 1}}] - }; + newObject = {_id: 1, a: [{b: {c: 1}}]}; now = (new Date()).getTime() / 1000; for (created = now - NUM; created <= now; created++) { @@ -20,9 +17,7 @@ function test(withIndex) { } // change the last M items. - query = { - 'created': {'$gte': now - M} - }; + query = {'created': {'$gte': now - M}}; Z = t.find(query).count(); diff --git a/jstests/core/index_check3.js b/jstests/core/index_check3.js index 2c07ae6d50a..7ffcc8da411 100644 --- a/jstests/core/index_check3.js +++ b/jstests/core/index_check3.js @@ -19,9 +19,7 @@ assert.eq(1, t.find({a: {$gt: 2}}).itcount(), "D"); t.drop(); for (var i = 0; i < 100; i++) { - var o = { - i: i - }; + var o = {i: i}; if (i % 2 == 0) o.foo = i; t.save(o); diff --git a/jstests/core/index_check6.js b/jstests/core/index_check6.js index 4baeced8fb9..e85913aeec3 100644 --- a/jstests/core/index_check6.js +++ b/jstests/core/index_check6.js @@ -30,10 +30,10 @@ assert.eq(29, assert.eq(5, keysExamined({age: {$gte: 29, $lte: 30}, rating: 5}, {age: 1, rating: 1}), "C"); // SERVER-371 -assert.eq(7, - keysExamined({age: {$gte: 29, $lte: 30}, rating: {$gte: 4, $lte: 5}}, - {age: 1, rating: 1}), - "D"); // SERVER-371 +assert.eq( + 7, + keysExamined({age: {$gte: 29, $lte: 30}, rating: {$gte: 4, $lte: 5}}, {age: 1, rating: 1}), + "D"); // SERVER-371 assert.eq.automsg("2", "t.find( { age:30, rating:{ $gte:4, $lte:5} } )" + ".explain('executionStats')" + @@ -91,11 +91,7 @@ for (var a = -1; a <= 1; a += 2) { for (var b = -1; b <= 1; b += 2) { for (var c = -1; c <= 1; c += 2) { t.dropIndexes(); - var spec = { - a: a, - b: b, - c: c - }; + var spec = {a: a, b: b, c: c}; t.ensureIndex(spec); doTest(spec, spec); doTest({a: -a, b: -b, c: -c}, spec); diff --git a/jstests/core/index_create_too_many.js b/jstests/core/index_create_too_many.js index 44d5016a7cf..0b2002d9cc1 100644 --- a/jstests/core/index_create_too_many.js +++ b/jstests/core/index_create_too_many.js @@ -6,10 +6,7 @@ coll.drop(); // create 62 indexes, which leaves us with 63 indexes total (+1 for the _id index) for (var i = 0; i < 62; i++) { var name = 'i' + i; - var spec = { - key: {}, - name: name - }; + var spec = {key: {}, name: name}; spec.key[name] = 1; var res = coll.runCommand('createIndexes', {indexes: [spec]}); diff --git a/jstests/core/index_create_with_nul_in_name.js b/jstests/core/index_create_with_nul_in_name.js index 9134649c086..c128dcc5880 100644 --- a/jstests/core/index_create_with_nul_in_name.js +++ b/jstests/core/index_create_with_nul_in_name.js @@ -6,11 +6,7 @@ var coll = db.create_index_with_nul_in_name; coll.drop(); - var idx = { - key: {'a': 1}, - name: 'foo\0bar', - ns: coll.getFullName() - }; + var idx = {key: {'a': 1}, name: 'foo\0bar', ns: coll.getFullName()}; var res = coll.runCommand('createIndexes', {indexes: [idx]}); assert.commandFailed(res, tojson(res)); diff --git a/jstests/core/index_diag.js b/jstests/core/index_diag.js index 3e25bf2a1eb..e458a590dda 100644 --- a/jstests/core/index_diag.js +++ b/jstests/core/index_diag.js @@ -16,10 +16,7 @@ function r(a) { } for (i = 1; i < 4; i++) { - o = { - _id: i, - x: -i - }; + o = {_id: i, x: -i}; t.insert(o); all.push(o); ids.push({_id: i}); diff --git a/jstests/core/index_filter_commands.js b/jstests/core/index_filter_commands.js index 027731e97cf..8d00d69cbe7 100644 --- a/jstests/core/index_filter_commands.js +++ b/jstests/core/index_filter_commands.js @@ -36,32 +36,16 @@ t.save({a: 1, b: 1}); // Add 2 indexes. // 1st index is more efficient. // 2nd and 3rd indexes will be used to test index filters. -var indexA1 = { - a: 1 -}; -var indexA1B1 = { - a: 1, - b: 1 -}; -var indexA1C1 = { - a: 1, - c: 1 -}; +var indexA1 = {a: 1}; +var indexA1B1 = {a: 1, b: 1}; +var indexA1C1 = {a: 1, c: 1}; t.ensureIndex(indexA1); t.ensureIndex(indexA1B1); t.ensureIndex(indexA1C1); -var queryA1 = { - a: 1, - b: 1 -}; -var projectionA1 = { - _id: 0, - a: 1 -}; -var sortA1 = { - a: -1 -}; +var queryA1 = {a: 1, b: 1}; +var projectionA1 = {_id: 0, a: 1}; +var sortA1 = {a: -1}; // // Tests for planCacheListFilters, planCacheClearFilters, planCacheSetFilter @@ -110,17 +94,12 @@ assert.eq(0, filters.length, 'unexpected number of index filters in planCacheLis // Check details of winning plan in plan cache before setting index filter. assert.eq(1, t.find(queryA1, projectionA1).sort(sortA1).itcount(), 'unexpected document count'); -var shape = { - query: queryA1, - sort: sortA1, - projection: projectionA1 -}; +var shape = {query: queryA1, sort: sortA1, projection: projectionA1}; var planBeforeSetFilter = getPlans(shape)[0]; print('Winning plan (before setting index filters) = ' + tojson(planBeforeSetFilter)); // Check filterSet field in plan details -assert.eq(false, - planBeforeSetFilter.filterSet, - 'missing or invalid filterSet field in plan details'); +assert.eq( + false, planBeforeSetFilter.filterSet, 'missing or invalid filterSet field in plan details'); // Adding index filters to a non-existent collection should be an error. assert.commandFailed(missingCollection.runCommand( @@ -132,9 +111,8 @@ assert.commandWorked(t.runCommand( 'planCacheSetFilter', {query: queryA1, sort: sortA1, projection: projectionA1, indexes: [indexA1B1, indexA1C1]})); filters = getFilters(); -assert.eq(1, - filters.length, - 'no change in query settings after successfully setting index filters'); +assert.eq( + 1, filters.length, 'no change in query settings after successfully setting index filters'); assert.eq(queryA1, filters[0].query, 'unexpected query in filters'); assert.eq(sortA1, filters[0].sort, 'unexpected sort in filters'); assert.eq(projectionA1, filters[0].projection, 'unexpected projection in filters'); @@ -196,13 +174,9 @@ if (db.isMaster().msg !== "isdbgrid") { .queryPlanner.indexFilterSet); // With two filters set. - assert.commandWorked(t.runCommand('planCacheSetFilter', - { - query: queryA1, - projection: projectionA1, - sort: sortA1, - indexes: [indexA1B1, indexA1C1] - })); + assert.commandWorked(t.runCommand( + 'planCacheSetFilter', + {query: queryA1, projection: projectionA1, sort: sortA1, indexes: [indexA1B1, indexA1C1]})); assert.eq(true, t.find({z: 1}).explain('queryPlanner').queryPlanner.indexFilterSet); assert.eq(true, t.find(queryA1, projectionA1) diff --git a/jstests/core/index_many.js b/jstests/core/index_many.js index 142c9bbc4a5..f2daa8c9fcf 100644 --- a/jstests/core/index_many.js +++ b/jstests/core/index_many.js @@ -15,13 +15,9 @@ function f() { patt = {}; patt[x] = 1; if (x == 20) - patt = { - x: 1 - }; + patt = {x: 1}; if (x == 64) - patt = { - y: 1 - }; + patt = {y: 1}; lastErr = t.ensureIndex(patt); x++; } diff --git a/jstests/core/index_partial_create_drop.js b/jstests/core/index_partial_create_drop.js index 483dc26f5e5..1c8552804b3 100644 --- a/jstests/core/index_partial_create_drop.js +++ b/jstests/core/index_partial_create_drop.js @@ -24,12 +24,10 @@ assert.commandFailed(coll.ensureIndex({x: 1}, {partialFilterExpression: {x: {$asdasd: 3}}})); assert.commandFailed(coll.ensureIndex({x: 1}, {partialFilterExpression: {$and: 5}})); assert.commandFailed(coll.ensureIndex({x: 1}, {partialFilterExpression: {x: /abc/}})); - assert.commandFailed(coll.ensureIndex( - {x: 1}, - { - partialFilterExpression: - {$and: [{$and: [{x: {$lt: 2}}, {x: {$gt: 0}}]}, {x: {$exists: true}}]} - })); + assert.commandFailed(coll.ensureIndex({x: 1}, { + partialFilterExpression: + {$and: [{$and: [{x: {$lt: 2}}, {x: {$gt: 0}}]}, {x: {$exists: true}}]} + })); for (var i = 0; i < 10; i++) { assert.writeOK(coll.insert({x: i, a: i})); diff --git a/jstests/core/index_stats.js b/jstests/core/index_stats.js index 7db4559210c..16d5a16d8d2 100644 --- a/jstests/core/index_stats.js +++ b/jstests/core/index_stats.js @@ -78,8 +78,8 @@ // // Confirm index stats tick on findAndModify() update. // - var res = db.runCommand( - {findAndModify: colName, query: {a: 1}, update: {$set: {d: 1}}, 'new': true}); + var res = + db.runCommand({findAndModify: colName, query: {a: 1}, update: {$set: {d: 1}}, 'new': true}); assert.commandWorked(res); countA++; assert.eq(countA, getUsageCount("a_1")); diff --git a/jstests/core/indexu.js b/jstests/core/indexu.js index 923356bf79b..088f0b86d44 100644 --- a/jstests/core/indexu.js +++ b/jstests/core/indexu.js @@ -4,15 +4,9 @@ t = db.jstests_indexu; t.drop(); -var dupDoc = { - a: [{'0': 1}] -}; // There are two 'a.0' fields in this doc. -var dupDoc2 = { - a: [{'1': 1}, 'c'] -}; -var noDupDoc = { - a: [{'1': 1}] -}; +var dupDoc = {a: [{'0': 1}]}; // There are two 'a.0' fields in this doc. +var dupDoc2 = {a: [{'1': 1}, 'c']}; +var noDupDoc = {a: [{'1': 1}]}; // Test that we can't index dupDoc. assert.writeOK(t.save(dupDoc)); diff --git a/jstests/core/insert1.js b/jstests/core/insert1.js index 0f4f6977a1a..d6886491999 100644 --- a/jstests/core/insert1.js +++ b/jstests/core/insert1.js @@ -1,9 +1,7 @@ t = db.insert1; t.drop(); -var o = { - a: 1 -}; +var o = {a: 1}; t.insert(o); var doc = t.findOne(); assert.eq(1, doc.a); diff --git a/jstests/core/js1.js b/jstests/core/js1.js index 89910f4bd23..66462237417 100644 --- a/jstests/core/js1.js +++ b/jstests/core/js1.js @@ -6,17 +6,15 @@ t.remove({}); t.save({z: 1}); t.save({z: 2}); assert(2 == t.find().length()); -assert(2 == - t.find({ - $where: function() { - return 1; - } - }).length()); -assert(1 == - t.find({ - $where: function() { - return obj.z == 2; - } - }).length()); +assert(2 == t.find({ + $where: function() { + return 1; + } + }).length()); +assert(1 == t.find({ + $where: function() { + return obj.z == 2; + } + }).length()); assert(t.validate().valid); diff --git a/jstests/core/js2.js b/jstests/core/js2.js index 9dfb5c0b091..abd707fdbbd 100644 --- a/jstests/core/js2.js +++ b/jstests/core/js2.js @@ -11,11 +11,11 @@ t.save({z: 1}); t.save({z: 2}); assert.throws(function() { t.find({ - $where: function() { - db.jstests_js2_2.save({y: 1}); - return 1; - } - }).forEach(printjson); + $where: function() { + db.jstests_js2_2.save({y: 1}); + return 1; + } + }).forEach(printjson); }, null, "can't save from $where"); assert.eq(0, t2.find().length(), "B"); diff --git a/jstests/core/js3.js b/jstests/core/js3.js index 36d16051135..4d46c25bbf7 100644 --- a/jstests/core/js3.js +++ b/jstests/core/js3.js @@ -18,14 +18,12 @@ for (z = 0; z < 2; z++) { for (i = 0; i < 1000; i++) t.save({ i: i, - z: - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + z: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }); - assert(33 == - db.dbEval(function() { - return 33; - })); + assert(33 == db.dbEval(function() { + return 33; + })); db.dbEval(function() { db.jstests_js3.save({i: -1, z: "server side"}); @@ -33,12 +31,11 @@ for (z = 0; z < 2; z++) { assert(t.findOne({i: -1})); - assert(2 == - t.find({ - $where: function() { - return obj.i == 7 || obj.i == 8; - } - }).length()); + assert(2 == t.find({ + $where: function() { + return obj.i == 7 || obj.i == 8; + } + }).length()); // NPE test var ok = false; @@ -62,10 +59,10 @@ for (z = 0; z < 2; z++) { debug("before indexed find"); arr = t.find({ - $where: function() { - return obj.i == 7 || obj.i == 8; - } - }).toArray(); + $where: function() { + return obj.i == 7 || obj.i == 8; + } + }).toArray(); debug(arr); assert.eq(2, arr.length); @@ -74,8 +71,7 @@ for (z = 0; z < 2; z++) { for (i = 1000; i < 2000; i++) t.save({ i: i, - z: - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + z: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }); assert(t.find().count() == 2001); diff --git a/jstests/core/js7.js b/jstests/core/js7.js index aeaec66ff47..810f4692d4f 100644 --- a/jstests/core/js7.js +++ b/jstests/core/js7.js @@ -1,7 +1,6 @@ t = db.jstests_js7; t.drop(); -assert.eq(17, - db.eval(function(foo) { - return foo; - }, 17)); +assert.eq(17, db.eval(function(foo) { + return foo; +}, 17)); diff --git a/jstests/core/js8.js b/jstests/core/js8.js index 15b7ff7d7af..d670abb0587 100644 --- a/jstests/core/js8.js +++ b/jstests/core/js8.js @@ -6,30 +6,30 @@ t.save({a: 1, b: [2, 3, 4]}); assert.eq(1, t.find().length(), "A"); assert.eq(1, t.find(function() { - return this.a == 1; - }).length(), + return this.a == 1; + }).length(), "B"); assert.eq(1, t.find(function() { - if (!this.b.length) - return true; - return this.b.length == 3; - }).length(), + if (!this.b.length) + return true; + return this.b.length == 3; + }).length(), "B2"); assert.eq(1, t.find(function() { - return this.b[0] == 2; - }).length(), + return this.b[0] == 2; + }).length(), "C"); assert.eq(0, t.find(function() { - return this.b[0] == 3; - }).length(), + return this.b[0] == 3; + }).length(), "D"); assert.eq(1, t.find(function() { - return this.b[1] == 3; - }).length(), + return this.b[1] == 3; + }).length(), "E"); assert(t.validate().valid); diff --git a/jstests/core/js9.js b/jstests/core/js9.js index b29a31afdc4..515fa883aea 100644 --- a/jstests/core/js9.js +++ b/jstests/core/js9.js @@ -7,11 +7,10 @@ c.save({a: 2}); assert.eq(2, c.find().length()); assert.eq(2, c.find().count()); -assert.eq(2, - db.eval(function() { - num = 0; - db.jstests_js9.find().forEach(function(z) { - num++; - }); - return num; - })); +assert.eq(2, db.eval(function() { + num = 0; + db.jstests_js9.find().forEach(function(z) { + num++; + }); + return num; +})); diff --git a/jstests/core/list_collections1.js b/jstests/core/list_collections1.js index 04acb82290b..9745adc1f90 100644 --- a/jstests/core/list_collections1.js +++ b/jstests/core/list_collections1.js @@ -46,11 +46,9 @@ assert.commandWorked(mydb.dropDatabase()); assert.commandWorked(mydb.createCollection("foo")); - assert.eq(1, - cursorCountMatching(getListCollectionsCursor(), - function(c) { - return c.name === "foo"; - })); + assert.eq(1, cursorCountMatching(getListCollectionsCursor(), function(c) { + return c.name === "foo"; + })); // // Test that the collection metadata object is returned correctly. @@ -59,16 +57,12 @@ assert.commandWorked(mydb.dropDatabase()); assert.commandWorked(mydb.createCollection("foo")); assert.commandWorked(mydb.createCollection("bar", {temp: true})); - assert.eq(1, - cursorCountMatching(getListCollectionsCursor(), - function(c) { - return c.name === "foo" && c.options.temp === undefined; - })); - assert.eq(1, - cursorCountMatching(getListCollectionsCursor(), - function(c) { - return c.name === "bar" && c.options.temp === true; - })); + assert.eq(1, cursorCountMatching(getListCollectionsCursor(), function(c) { + return c.name === "foo" && c.options.temp === undefined; + })); + assert.eq(1, cursorCountMatching(getListCollectionsCursor(), function(c) { + return c.name === "bar" && c.options.temp === true; + })); // // Test basic usage of "filter" option. @@ -77,29 +71,23 @@ assert.commandWorked(mydb.dropDatabase()); assert.commandWorked(mydb.createCollection("foo")); assert.commandWorked(mydb.createCollection("bar", {temp: true})); - assert.eq(2, - cursorCountMatching(getListCollectionsCursor({filter: {}}), - function(c) { - return c.name === "foo" || c.name === "bar"; - })); + assert.eq(2, cursorCountMatching(getListCollectionsCursor({filter: {}}), function(c) { + return c.name === "foo" || c.name === "bar"; + })); assert.eq(2, getListCollectionsCursor({filter: {name: {$in: ["foo", "bar"]}}}).itcount()); assert.eq(1, getListCollectionsCursor({filter: {name: /^foo$/}}).itcount()); assert.eq(1, getListCollectionsCursor({filter: {"options.temp": true}}).itcount()); mydb.foo.drop(); - assert.eq(1, - cursorCountMatching(getListCollectionsCursor({filter: {}}), - function(c) { - return c.name === "foo" || c.name === "bar"; - })); + assert.eq(1, cursorCountMatching(getListCollectionsCursor({filter: {}}), function(c) { + return c.name === "foo" || c.name === "bar"; + })); assert.eq(1, getListCollectionsCursor({filter: {name: {$in: ["foo", "bar"]}}}).itcount()); assert.eq(0, getListCollectionsCursor({filter: {name: /^foo$/}}).itcount()); assert.eq(1, getListCollectionsCursor({filter: {"options.temp": true}}).itcount()); mydb.bar.drop(); - assert.eq(0, - cursorCountMatching(getListCollectionsCursor({filter: {}}), - function(c) { - return c.name === "foo" || c.name === "bar"; - })); + assert.eq(0, cursorCountMatching(getListCollectionsCursor({filter: {}}), function(c) { + return c.name === "foo" || c.name === "bar"; + })); assert.eq(0, getListCollectionsCursor({filter: {name: {$in: ["foo", "bar"]}}}).itcount()); assert.eq(0, getListCollectionsCursor({filter: {name: /^foo$/}}).itcount()); assert.eq(0, getListCollectionsCursor({filter: {"options.temp": true}}).itcount()); @@ -130,50 +118,38 @@ assert.commandWorked(mydb.createCollection("bar")); cursor = getListCollectionsCursor({cursor: {batchSize: 2}}); assert.eq(2, cursor.objsLeftInBatch()); - assert.eq(2, - cursorCountMatching(cursor, - function(c) { - return c.name === "foo" || c.name === "bar"; - })); + assert.eq(2, cursorCountMatching(cursor, function(c) { + return c.name === "foo" || c.name === "bar"; + })); cursor = getListCollectionsCursor({cursor: {batchSize: 1}}); assert.eq(1, cursor.objsLeftInBatch()); - assert.eq(2, - cursorCountMatching(cursor, - function(c) { - return c.name === "foo" || c.name === "bar"; - })); + assert.eq(2, cursorCountMatching(cursor, function(c) { + return c.name === "foo" || c.name === "bar"; + })); cursor = getListCollectionsCursor({cursor: {batchSize: 0}}); assert.eq(0, cursor.objsLeftInBatch()); - assert.eq(2, - cursorCountMatching(cursor, - function(c) { - return c.name === "foo" || c.name === "bar"; - })); + assert.eq(2, cursorCountMatching(cursor, function(c) { + return c.name === "foo" || c.name === "bar"; + })); cursor = getListCollectionsCursor({cursor: {batchSize: NumberInt(2)}}); assert.eq(2, cursor.objsLeftInBatch()); - assert.eq(2, - cursorCountMatching(cursor, - function(c) { - return c.name === "foo" || c.name === "bar"; - })); + assert.eq(2, cursorCountMatching(cursor, function(c) { + return c.name === "foo" || c.name === "bar"; + })); cursor = getListCollectionsCursor({cursor: {batchSize: NumberLong(2)}}); assert.eq(2, cursor.objsLeftInBatch()); - assert.eq(2, - cursorCountMatching(cursor, - function(c) { - return c.name === "foo" || c.name === "bar"; - })); + assert.eq(2, cursorCountMatching(cursor, function(c) { + return c.name === "foo" || c.name === "bar"; + })); // Test a large batch size, and assert that at least 2 results are returned in the initial // batch. cursor = getListCollectionsCursor({cursor: {batchSize: Math.pow(2, 62)}}); assert.lte(2, cursor.objsLeftInBatch()); - assert.eq(2, - cursorCountMatching(cursor, - function(c) { - return c.name === "foo" || c.name === "bar"; - })); + assert.eq(2, cursorCountMatching(cursor, function(c) { + return c.name === "foo" || c.name === "bar"; + })); // Ensure that the server accepts an empty object for "cursor". This is equivalent to not // specifying "cursor" at all. @@ -181,11 +157,9 @@ // We do not test for objsLeftInBatch() here, since the default batch size for this command // is not specified. cursor = getListCollectionsCursor({cursor: {}}); - assert.eq(2, - cursorCountMatching(cursor, - function(c) { - return c.name === "foo" || c.name === "bar"; - })); + assert.eq(2, cursorCountMatching(cursor, function(c) { + return c.name === "foo" || c.name === "bar"; + })); // // Test for invalid values of "cursor" and "cursor.batchSize". @@ -245,11 +219,9 @@ assert.commandWorked(mydb.dropDatabase()); cursor = getListCollectionsCursor(); - assert.eq(0, - cursorCountMatching(cursor, - function(c) { - return c.name === "foo"; - })); + assert.eq(0, cursorCountMatching(cursor, function(c) { + return c.name === "foo"; + })); // // Test on empty database. @@ -259,11 +231,9 @@ assert.commandWorked(mydb.createCollection("foo")); mydb.foo.drop(); cursor = getListCollectionsCursor(); - assert.eq(0, - cursorCountMatching(cursor, - function(c) { - return c.name === "foo"; - })); + assert.eq(0, cursorCountMatching(cursor, function(c) { + return c.name === "foo"; + })); // // Test killCursors against a listCollections cursor. diff --git a/jstests/core/list_collections_filter.js b/jstests/core/list_collections_filter.js index 4b5c42bbc78..e0d18f055d0 100644 --- a/jstests/core/list_collections_filter.js +++ b/jstests/core/list_collections_filter.js @@ -67,10 +67,20 @@ // Filter with $and and $in. testListCollections({name: {$in: ["lists", /.*_sets$/]}, options: {}}, ["lists", "ordered_sets", "unordered_sets"]); - testListCollections( - {$and: [{name: {$in: ["lists", /.*_sets$/]}}, {name: "lists"}, {options: {}}, ]}, - ["lists"]); - testListCollections( - {$and: [{name: {$in: ["lists", /.*_sets$/]}}, {name: "non-existent"}, {options: {}}, ]}, - []); + testListCollections({ + $and: [ + {name: {$in: ["lists", /.*_sets$/]}}, + {name: "lists"}, + {options: {}}, + ] + }, + ["lists"]); + testListCollections({ + $and: [ + {name: {$in: ["lists", /.*_sets$/]}}, + {name: "non-existent"}, + {options: {}}, + ] + }, + []); }()); diff --git a/jstests/core/long_index_rename.js b/jstests/core/long_index_rename.js index df3397bbb46..a0bf96aa894 100644 --- a/jstests/core/long_index_rename.js +++ b/jstests/core/long_index_rename.js @@ -11,11 +11,9 @@ for (i = 1; i < 10; i++) { } t.createIndex({a: 1}, {name: "aaa"}); -var result = t.createIndex( - {a: 1}, - { - name: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }); +var result = t.createIndex({a: 1}, { + name: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +}); assert(!result.ok); assert(result.errmsg.indexOf("too long") >= 0); diff --git a/jstests/core/max_doc_size.js b/jstests/core/max_doc_size.js index 03deeafb307..383e4b4b76d 100644 --- a/jstests/core/max_doc_size.js +++ b/jstests/core/max_doc_size.js @@ -53,10 +53,7 @@ assert.neq(null, res.writeErrors); coll.drop(); id = new ObjectId(); coll.insert({_id: id}); -res = db.runCommand({ - update: coll.getName(), - ordered: true, - updates: [{q: {_id: id}, u: {$set: {x: overBigStr}}}] -}); +res = db.runCommand( + {update: coll.getName(), ordered: true, updates: [{q: {_id: id}, u: {$set: {x: overBigStr}}}]}); assert(res.ok); assert.neq(null, res.writeErrors); diff --git a/jstests/core/mr1.js b/jstests/core/mr1.js index 0225ab3cb62..00a5726db0d 100644 --- a/jstests/core/mr1.js +++ b/jstests/core/mr1.js @@ -34,9 +34,7 @@ r = function(key, values) { for (var i = 0; i < values.length; i++) { total += values[i].count; } - return { - count: total - }; + return {count: total}; }; r2 = function(key, values) { @@ -136,19 +134,14 @@ if (true) { printjson(db.runCommand({mapreduce: "mr1", map: m, reduce: r, verbose: true, out: "mr1_out"})); } -print("t1: " + - Date.timeFunc( - function() { - var out = db.runCommand({mapreduce: "mr1", map: m, reduce: r, out: "mr1_out"}); - if (ks == "_id") - assert(out.ok, "XXX : " + tojson(out)); - db[out.result].drop(); - }, - 10) + - " (~500 on 2.8ghz) - itcount: " + - Date.timeFunc(function() { - db.mr1.find().itcount(); - }, 10)); +print("t1: " + Date.timeFunc(function() { + var out = db.runCommand({mapreduce: "mr1", map: m, reduce: r, out: "mr1_out"}); + if (ks == "_id") + assert(out.ok, "XXX : " + tojson(out)); + db[out.result].drop(); +}, 10) + " (~500 on 2.8ghz) - itcount: " + Date.timeFunc(function() { + db.mr1.find().itcount(); +}, 10)); // test doesn't exist res = @@ -169,10 +162,9 @@ if (true) { res = db.runCommand({mapreduce: "mr1", out: "mr1_foo", map: m, reduce: r}); d(res); - print("t2: " + res.timeMillis + " (~3500 on 2.8ghz) - itcount: " + - Date.timeFunc(function() { - db.mr1.find().itcount(); - })); + print("t2: " + res.timeMillis + " (~3500 on 2.8ghz) - itcount: " + Date.timeFunc(function() { + db.mr1.find().itcount(); + })); x = db[res.result]; z = {}; x.find().forEach(function(a) { diff --git a/jstests/core/mr2.js b/jstests/core/mr2.js index c13ff447970..744fb916088 100644 --- a/jstests/core/mr2.js +++ b/jstests/core/mr2.js @@ -15,10 +15,7 @@ function m() { } function r(who, values) { - var n = { - totalSize: 0, - num: 0 - }; + var n = {totalSize: 0, num: 0}; for (var i = 0; i < values.length; i++) { n.totalSize += values[i].totalSize; n.num += values[i].num; diff --git a/jstests/core/mr3.js b/jstests/core/mr3.js index a2cee1f2d8f..f5a45e0fd1c 100644 --- a/jstests/core/mr3.js +++ b/jstests/core/mr3.js @@ -20,9 +20,7 @@ r = function(key, values) { for (var i = 0; i < values.length; i++) { total += values[i].count; } - return { - count: total - }; + return {count: total}; }; res = t.mapReduce(m, r, {out: "mr3_out"}); diff --git a/jstests/core/mr4.js b/jstests/core/mr4.js index ae5e11528af..58ea303f7e8 100644 --- a/jstests/core/mr4.js +++ b/jstests/core/mr4.js @@ -18,9 +18,7 @@ r = function(key, values) { for (var i = 0; i < values.length; i++) { total += values[i].count; } - return { - count: total - }; + return {count: total}; }; res = t.mapReduce(m, r, {out: "mr4_out", scope: {xx: 1}}); diff --git a/jstests/core/mr5.js b/jstests/core/mr5.js index 537625e954b..8552f891358 100644 --- a/jstests/core/mr5.js +++ b/jstests/core/mr5.js @@ -22,10 +22,7 @@ r = function(k, v) { total += v[i].stats[j]; } } - return { - stats: stats, - total: total - }; + return {stats: stats, total: total}; }; res = t.mapReduce(m, r, {out: "mr5_out", scope: {xx: 1}}); @@ -41,11 +38,7 @@ res.drop(); m = function() { var x = "partner"; var y = "visits"; - emit(this [x], - { - stats: - [this[y]] - }); + emit(this[x], {stats: [this[y]]}); }; res = t.mapReduce(m, r, {out: "mr5_out", scope: {xx: 1}}); diff --git a/jstests/core/mr_bigobject.js b/jstests/core/mr_bigobject.js index d87b2af4cdc..ff8e3cd1652 100644 --- a/jstests/core/mr_bigobject.js +++ b/jstests/core/mr_bigobject.js @@ -41,8 +41,7 @@ r = function(k, v) { return total; }; -assert.eq({1: t.count() * s.length}, - t.mapReduce(m, r, "mr_bigobject_out").convertToSingleObject(), - "A1"); +assert.eq( + {1: t.count() * s.length}, t.mapReduce(m, r, "mr_bigobject_out").convertToSingleObject(), "A1"); t.drop(); diff --git a/jstests/core/mr_bigobject_replace.js b/jstests/core/mr_bigobject_replace.js index 28a295c1b2e..c30b6e5de48 100644 --- a/jstests/core/mr_bigobject_replace.js +++ b/jstests/core/mr_bigobject_replace.js @@ -14,10 +14,7 @@ // Returns a document of the form { _id: ObjectId(...), value: '...' } with the specified // 'targetSize' in bytes. function makeDocWithSize(targetSize) { - var doc = { - _id: new ObjectId(), - value: '' - }; + var doc = {_id: new ObjectId(), value: ''}; var size = Object.bsonsize(doc); assert.gte(targetSize, size); @@ -41,13 +38,12 @@ // Insert a document so the mapper gets run. assert.writeOK(db.input.insert({})); - var res = db.runCommand(Object.extend( - { - mapReduce: "input", - map: mapper, - out: {replace: "mr_bigobject_replace"}, - }, - testOptions)); + var res = db.runCommand(Object.extend({ + mapReduce: "input", + map: mapper, + out: {replace: "mr_bigobject_replace"}, + }, + testOptions)); assert.commandFailed(res, "creating a document larger than 16MB didn't fail"); assert.lte(0, diff --git a/jstests/core/mr_index3.js b/jstests/core/mr_index3.js index bac61cb6bc1..885089ade4d 100644 --- a/jstests/core/mr_index3.js +++ b/jstests/core/mr_index3.js @@ -17,20 +17,16 @@ r = function(key, values) { }; a1 = db.runCommand({mapreduce: 'mr_index3', map: m, reduce: r, out: {inline: true}}).results; -a2 = db.runCommand({ - mapreduce: 'mr_index3', - map: m, - reduce: r, - query: {name: 'name1'}, - out: {inline: true} -}).results; +a2 = db.runCommand( + {mapreduce: 'mr_index3', map: m, reduce: r, query: {name: 'name1'}, out: {inline: true}}) + .results; a3 = db.runCommand({ - mapreduce: 'mr_index3', - map: m, - reduce: r, - query: {name: {$gt: 'name'}}, - out: {inline: true} -}).results; + mapreduce: 'mr_index3', + map: m, + reduce: r, + query: {name: {$gt: 'name'}}, + out: {inline: true} + }).results; assert.eq([{"_id": "cat", "value": 3}, {"_id": "dog", "value": 2}, {"_id": "mouse", "value": 1}], a1, @@ -41,20 +37,16 @@ assert.eq(a1, a3, "A3"); t.ensureIndex({name: 1, tags: 1}); b1 = db.runCommand({mapreduce: 'mr_index3', map: m, reduce: r, out: {inline: true}}).results; -b2 = db.runCommand({ - mapreduce: 'mr_index3', - map: m, - reduce: r, - query: {name: 'name1'}, - out: {inline: true} -}).results; +b2 = db.runCommand( + {mapreduce: 'mr_index3', map: m, reduce: r, query: {name: 'name1'}, out: {inline: true}}) + .results; b3 = db.runCommand({ - mapreduce: 'mr_index3', - map: m, - reduce: r, - query: {name: {$gt: 'name'}}, - out: {inline: true} -}).results; + mapreduce: 'mr_index3', + map: m, + reduce: r, + query: {name: {$gt: 'name'}}, + out: {inline: true} + }).results; assert.eq(a1, b1, "AB1"); assert.eq(a2, b2, "AB2"); diff --git a/jstests/core/mr_killop.js b/jstests/core/mr_killop.js index 52865eacbe4..78e98f0bcaa 100644 --- a/jstests/core/mr_killop.js +++ b/jstests/core/mr_killop.js @@ -51,12 +51,7 @@ function testOne(map, reduce, finalize, scope, childLoop, wait) { t.save({a: 1}); t.save({a: 1}); - spec = { - mapreduce: "jstests_mr_killop", - out: "jstests_mr_killop_out", - map: map, - reduce: reduce - }; + spec = {mapreduce: "jstests_mr_killop", out: "jstests_mr_killop_out", map: map, reduce: reduce}; if (finalize) { spec["finalize"] = finalize; } diff --git a/jstests/core/mr_mutable_properties.js b/jstests/core/mr_mutable_properties.js index 12c52385275..84066bf76c0 100644 --- a/jstests/core/mr_mutable_properties.js +++ b/jstests/core/mr_mutable_properties.js @@ -8,28 +8,20 @@ collection.insert({a: 1}); var map = function() { // set property on receiver - this.feed = { - beef: 1 - }; + this.feed = {beef: 1}; // modify property on receiever - this.a = { - cake: 1 - }; + this.a = {cake: 1}; emit(this._id, this.feed); emit(this._id, this.a); }; var reduce = function(key, values) { // set property on receiver - this.feed = { - beat: 1 - }; + this.feed = {beat: 1}; // set property on key arg - key.fed = { - mochi: 1 - }; + key.fed = {mochi: 1}; // push properties onto values array arg values.push(this.feed); @@ -39,21 +31,15 @@ var reduce = function(key, values) { values.forEach(function(val) { val.mod = 1; }); - return { - food: values - }; + return {food: values}; }; var finalize = function(key, values) { // set property on receiver - this.feed = { - ice: 1 - }; + this.feed = {ice: 1}; // set property on key arg - key.fed = { - cream: 1 - }; + key.fed = {cream: 1}; // push properties onto values array arg printjson(values); diff --git a/jstests/core/mr_stored.js b/jstests/core/mr_stored.js index 63fa301e66d..5969638b8b9 100644 --- a/jstests/core/mr_stored.js +++ b/jstests/core/mr_stored.js @@ -22,10 +22,7 @@ r = function(k, v) { total += v[i].stats[j]; } } - return { - stats: stats, - total: total - }; + return {stats: stats, total: total}; }; // Test that map reduce works with stored javascript diff --git a/jstests/core/nestedarr1.js b/jstests/core/nestedarr1.js index 98ddc2193ea..720c1c27821 100644 --- a/jstests/core/nestedarr1.js +++ b/jstests/core/nestedarr1.js @@ -3,13 +3,9 @@ function makeNestArr(depth) { if (depth == 1) { - return { - a: [depth] - }; + return {a: [depth]}; } else { - return { - a: [makeNestArr(depth - 1)] - }; + return {a: [makeNestArr(depth - 1)]}; } } diff --git a/jstests/core/nestedobj1.js b/jstests/core/nestedobj1.js index 97b9460da6f..379224c1775 100644 --- a/jstests/core/nestedobj1.js +++ b/jstests/core/nestedobj1.js @@ -1,14 +1,10 @@ // SERVER-5127, SERVER-5036 function makeNestObj(depth) { - toret = { - a: 1 - }; + toret = {a: 1}; for (i = 1; i < depth; i++) { - toret = { - a: toret - }; + toret = {a: toret}; } return toret; diff --git a/jstests/core/nin.js b/jstests/core/nin.js index d6cd78ee7a4..e7bb66bed93 100644 --- a/jstests/core/nin.js +++ b/jstests/core/nin.js @@ -3,13 +3,9 @@ t.drop(); function checkEqual(name, key, value) { var o = {}; - o[key] = { - $in: [value] - }; + o[key] = {$in: [value]}; var i = t.find(o).count(); - o[key] = { - $nin: [value] - }; + o[key] = {$nin: [value]}; var n = t.find(o).count(); assert.eq(t.find().count(), diff --git a/jstests/core/not3.js b/jstests/core/not3.js index 9699f3838d1..9f3014f2c1a 100644 --- a/jstests/core/not3.js +++ b/jstests/core/not3.js @@ -9,15 +9,11 @@ t.save({_id: 0, arr: [1, 2, 3]}); t.save({_id: 1, arr: [10, 11]}); // Case 1: simple $ne over array field. -var case1 = { - arr: {$ne: 3} -}; +var case1 = {arr: {$ne: 3}}; assert.eq(1, t.find(case1).itcount(), "Case 1: wrong number of results"); assert.eq(1, t.findOne(case1)._id, "Case 1: wrong _id"); // Case 2: simple $not over array field. -var case2 = { - arr: {$not: {$gt: 6}} -}; +var case2 = {arr: {$not: {$gt: 6}}}; assert.eq(1, t.find(case2).itcount(), "Case 2: wrong number of results"); assert.eq(0, t.findOne(case2)._id, "Case 2: wrong _id"); diff --git a/jstests/core/or1.js b/jstests/core/or1.js index 0552524eb4c..e7c417800b6 100644 --- a/jstests/core/or1.js +++ b/jstests/core/or1.js @@ -41,14 +41,15 @@ doTest = function() { checkArrs([{_id: 0, a: 1}, {_id: 4, a: 1, b: 1}, {_id: 5, a: 1, b: 2}], a1); a1b2 = t.find({$or: [{a: 1}, {b: 2}]}).toArray(); - checkArrs([ - {_id: 0, a: 1}, - {_id: 3, b: 2}, - {_id: 4, a: 1, b: 1}, - {_id: 5, a: 1, b: 2}, - {_id: 7, a: 2, b: 2} - ], - a1b2); + checkArrs( + [ + {_id: 0, a: 1}, + {_id: 3, b: 2}, + {_id: 4, a: 1, b: 1}, + {_id: 5, a: 1, b: 2}, + {_id: 7, a: 2, b: 2} + ], + a1b2); t.drop(); t.save({a: [0, 1], b: [0, 1]}); diff --git a/jstests/core/or_inexact.js b/jstests/core/or_inexact.js index 8c9db1cc7ba..3e7e374d7f5 100644 --- a/jstests/core/or_inexact.js +++ b/jstests/core/or_inexact.js @@ -190,8 +190,8 @@ t.drop(); t.ensureIndex({"a.b": 1}); t.insert({_id: 0, a: [{b: 1}, {b: 2}]}); t.insert({_id: 1, a: [{b: 2}, {b: 4}]}); -cursor = t.find( - {"a.b": 2, $or: [{a: {$elemMatch: {b: {$lte: 1}}}}, {a: {$elemMatch: {b: {$gte: 4}}}}]}); +cursor = + t.find({"a.b": 2, $or: [{a: {$elemMatch: {b: {$lte: 1}}}}, {a: {$elemMatch: {b: {$gte: 4}}}}]}); assert.eq(2, cursor.itcount(), "case 14"); // Case 15: $or below $elemMatch. diff --git a/jstests/core/orc.js b/jstests/core/orc.js index 7d686972898..c68c6859651 100644 --- a/jstests/core/orc.js +++ b/jstests/core/orc.js @@ -22,24 +22,22 @@ t.ensureIndex({a: -1, b: 1, c: 1}); // sanity test t.save({a: null, b: 4, c: 4}); -assert.eq(1, - t.count({ - $or: [ - {a: null, b: {$gte: 0, $lte: 5}, c: {$gte: 0, $lte: 5}}, - {a: null, b: {$gte: 3, $lte: 8}, c: {$gte: 3, $lte: 8}} - ] - })); +assert.eq(1, t.count({ + $or: [ + {a: null, b: {$gte: 0, $lte: 5}, c: {$gte: 0, $lte: 5}}, + {a: null, b: {$gte: 3, $lte: 8}, c: {$gte: 3, $lte: 8}} + ] +})); // from here on is SERVER-2245 t.remove({}); t.save({b: 4, c: 4}); -assert.eq(1, - t.count({ - $or: [ - {a: null, b: {$gte: 0, $lte: 5}, c: {$gte: 0, $lte: 5}}, - {a: null, b: {$gte: 3, $lte: 8}, c: {$gte: 3, $lte: 8}} - ] - })); +assert.eq(1, t.count({ + $or: [ + {a: null, b: {$gte: 0, $lte: 5}, c: {$gte: 0, $lte: 5}}, + {a: null, b: {$gte: 3, $lte: 8}, c: {$gte: 3, $lte: 8}} + ] +})); // t.remove({}); // t.save( {a:[],b:4,c:4} ); diff --git a/jstests/core/ork.js b/jstests/core/ork.js index f367b6b4bad..7c9bc982776 100644 --- a/jstests/core/ork.js +++ b/jstests/core/ork.js @@ -7,17 +7,15 @@ t.ensureIndex({a: 1}); t.save({a: [1, 2], b: 5}); t.save({a: [2, 4], b: 5}); -assert.eq(2, - t.find({ - $or: [ - {a: 1, $and: [{$or: [{a: 2}, {a: 3}]}, {$or: [{b: 5}]}]}, - {a: 2, $or: [{a: 3}, {a: 4}]} - ] - }).itcount()); -assert.eq(1, - t.find({ - $or: [ - {a: 1, $and: [{$or: [{a: 2}, {a: 3}]}, {$or: [{b: 6}]}]}, - {a: 2, $or: [{a: 3}, {a: 4}]} - ] - }).itcount()); +assert.eq(2, t.find({ + $or: [ + {a: 1, $and: [{$or: [{a: 2}, {a: 3}]}, {$or: [{b: 5}]}]}, + {a: 2, $or: [{a: 3}, {a: 4}]} + ] + }).itcount()); +assert.eq(1, t.find({ + $or: [ + {a: 1, $and: [{$or: [{a: 2}, {a: 3}]}, {$or: [{b: 6}]}]}, + {a: 2, $or: [{a: 3}, {a: 4}]} + ] + }).itcount()); diff --git a/jstests/core/plan_cache_list_plans.js b/jstests/core/plan_cache_list_plans.js index b4be4ad46c4..7ca599483ff 100644 --- a/jstests/core/plan_cache_list_plans.js +++ b/jstests/core/plan_cache_list_plans.js @@ -5,11 +5,7 @@ t.drop(); // Utility function to list plans for a query. function getPlans(query, sort, projection) { - var key = { - query: query, - sort: sort, - projection: projection - }; + var key = {query: query, sort: sort, projection: projection}; var res = t.runCommand('planCacheListPlans', key); assert.commandWorked(res, 'planCacheListPlans(' + tojson(key, '', true) + ' failed'); assert(res.hasOwnProperty('plans'), @@ -32,9 +28,8 @@ assert.eq(0, 'planCacheListPlans should return empty results on unknown query shape'); // Create a cache entry. -assert.eq(1, - t.find({a: 1, b: 1}, {_id: 0, a: 1}).sort({a: -1}).itcount(), - 'unexpected document count'); +assert.eq( + 1, t.find({a: 1, b: 1}, {_id: 0, a: 1}).sort({a: -1}).itcount(), 'unexpected document count'); // Retrieve plans for valid cache entry. var plans = getPlans({a: 1, b: 1}, {a: -1}, {_id: 0, a: 1}); diff --git a/jstests/core/plan_cache_list_shapes.js b/jstests/core/plan_cache_list_shapes.js index 4711940870d..1c9ecdf9e1b 100644 --- a/jstests/core/plan_cache_list_shapes.js +++ b/jstests/core/plan_cache_list_shapes.js @@ -34,9 +34,8 @@ t.ensureIndex({a: 1}); t.ensureIndex({a: 1, b: 1}); // Run a query. -assert.eq(1, - t.find({a: 1, b: 1}, {_id: 1, a: 1}).sort({a: -1}).itcount(), - 'unexpected document count'); +assert.eq( + 1, t.find({a: 1, b: 1}, {_id: 1, a: 1}).sort({a: -1}).itcount(), 'unexpected document count'); // We now expect the two indices to be compared and a cache entry to exist. // Retrieve query shapes from the test collection diff --git a/jstests/core/plan_cache_shell_helpers.js b/jstests/core/plan_cache_shell_helpers.js index a61421afc7b..dc990b19dcc 100644 --- a/jstests/core/plan_cache_shell_helpers.js +++ b/jstests/core/plan_cache_shell_helpers.js @@ -16,11 +16,7 @@ function getShapes(collection) { } // Utility function to list plans for a query. function getPlans(query, sort, projection) { - var key = { - query: query, - sort: sort, - projection: projection - }; + var key = {query: query, sort: sort, projection: projection}; var res = t.runCommand('planCacheListPlans', key); assert.commandWorked(res, 'planCacheListPlans(' + tojson(key, '', true) + ' failed'); assert(res.hasOwnProperty('plans'), @@ -37,17 +33,9 @@ t.ensureIndex({a: 1}); t.ensureIndex({b: 1}); // Populate plan cache. -var queryB = { - a: {$gte: 199}, - b: -1 -}; -var projectionB = { - _id: 0, - b: 1 -}; -var sortC = { - c: -1 -}; +var queryB = {a: {$gte: 199}, b: -1}; +var projectionB = {_id: 0, b: 1}; +var sortC = {c: -1}; assert.eq(1, t.find(queryB, projectionB).sort(sortC).itcount(), 'unexpected document count'); assert.eq(1, t.find(queryB, projectionB).itcount(), 'unexpected document count'); assert.eq(1, t.find(queryB).sort(sortC).itcount(), 'unexpected document count'); @@ -124,11 +112,7 @@ assert.eq(getPlans(queryB, {}, {}), // projection: <projection>, // sort: <sort> // } -var shapeB = { - query: queryB, - projection: projectionB, - sort: sortC -}; +var shapeB = {query: queryB, projection: projectionB, sort: sortC}; assert.eq(getPlans(queryB, sortC, projectionB), planCache.getPlansByQuery(shapeB), 'collection.getPlanCache().getPlansByQuery() did not accept query shape object'); @@ -141,12 +125,13 @@ assert.eq(0, planCache.getPlansByQuery({query: queryB}).length, 'collection.getPlanCache.getPlansByQuery should return empty results on ' + 'incomplete query shape'); -assert.eq(0, - planCache.getPlansByQuery( - {query: queryB, sort: sortC, projection: projectionB, unknown_field: 1}) - .length, - 'collection.getPlanCache.getPlansByQuery should return empty results on ' + - 'invalid query shape'); +assert.eq( + 0, + planCache + .getPlansByQuery({query: queryB, sort: sortC, projection: projectionB, unknown_field: 1}) + .length, + 'collection.getPlanCache.getPlansByQuery should return empty results on ' + + 'invalid query shape'); // // collection.getPlanCache().clearPlansByQuery diff --git a/jstests/core/pop_server_13516.js b/jstests/core/pop_server_13516.js index 8d0bacbb3e5..008d0de79a1 100644 --- a/jstests/core/pop_server_13516.js +++ b/jstests/core/pop_server_13516.js @@ -4,10 +4,7 @@ var t = db.jstests_pop_server_13516; t.drop(); var id = NumberInt(0); -var object = { - _id: id, - data: [] -}; +var object = {_id: id, data: []}; for (var i = 0; i < 4096; i++) { object.data[i] = 0; diff --git a/jstests/core/profile1.js b/jstests/core/profile1.js index 67f4a53d2b9..b1024f6668c 100644 --- a/jstests/core/profile1.js +++ b/jstests/core/profile1.js @@ -87,12 +87,8 @@ resetProfile(2); db.profile1.drop(); - var q = { - _id: 5 - }; - var u = { - $inc: {x: 1} - }; + var q = {_id: 5}; + var u = {$inc: {x: 1}}; db.profile1.update(q, u); var r = profileCursor({ns: db.profile1.getFullName()}).sort({$natural: -1})[0]; assert.eq(q, r.query, "Y1: " + tojson(r)); diff --git a/jstests/core/profile_count.js b/jstests/core/profile_count.js index 09ba6520828..d79fb94df85 100644 --- a/jstests/core/profile_count.js +++ b/jstests/core/profile_count.js @@ -44,9 +44,7 @@ assert.writeOK(coll.insert({a: i})); } - var query = { - a: {$gte: 5} - }; + var query = {a: {$gte: 5}}; assert.eq(5, coll.count(query)); profileObj = getLatestProfilerEntry(testDB); @@ -62,9 +60,7 @@ } assert.commandWorked(coll.createIndex({a: 1})); - query = { - a: {$gte: 5} - }; + query = {a: {$gte: 5}}; assert.eq(5, coll.count(query)); profileObj = getLatestProfilerEntry(testDB); diff --git a/jstests/core/profile_insert.js b/jstests/core/profile_insert.js index 75a44fcb4e9..e49699a9d11 100644 --- a/jstests/core/profile_insert.js +++ b/jstests/core/profile_insert.js @@ -17,9 +17,7 @@ // // Test single insert. // - var doc = { - _id: 1 - }; + var doc = {_id: 1}; var result = coll.insert(doc); if (isWriteCommand) { assert.writeOK(result); @@ -76,9 +74,7 @@ // Test insert options. // coll.drop(); - doc = { - _id: 1 - }; + doc = {_id: 1}; var wtimeout = 60000; assert.writeOK(coll.insert(doc, {writeConcern: {w: 1, wtimeout: wtimeout}, ordered: false})); diff --git a/jstests/core/push_sort.js b/jstests/core/push_sort.js index 0e407d969ba..b9676f6c963 100644 --- a/jstests/core/push_sort.js +++ b/jstests/core/push_sort.js @@ -53,10 +53,7 @@ assert.eq([{a: {b: 2}}, {a: {b: 3}}], t.findOne({_id: 7}).x); // // $push with $sort should not push a "$sort" field -var doc8 = { - _id: 8, - x: [{a: 1}, {a: 2}] -}; +var doc8 = {_id: 8, x: [{a: 1}, {a: 2}]}; t.save(doc8); var res = t.update({_id: 8}, {$push: {x: {$sort: {a: -1}}}}); assert.writeError(res); diff --git a/jstests/core/ref.js b/jstests/core/ref.js index 02c4cb92a07..33d83738cd2 100644 --- a/jstests/core/ref.js +++ b/jstests/core/ref.js @@ -4,10 +4,7 @@ db.otherthings.drop(); db.things.drop(); -var other = { - s: "other thing", - n: 1 -}; +var other = {s: "other thing", n: 1}; db.otherthings.save(other); db.things.save({name: "abc"}); diff --git a/jstests/core/ref3.js b/jstests/core/ref3.js index 929e4152daf..4406863d899 100644 --- a/jstests/core/ref3.js +++ b/jstests/core/ref3.js @@ -4,10 +4,7 @@ db.otherthings3.drop(); db.things3.drop(); -var other = { - s: "other thing", - n: 1 -}; +var other = {s: "other thing", n: 1}; db.otherthings3.save(other); db.things3.save({name: "abc"}); diff --git a/jstests/core/ref4.js b/jstests/core/ref4.js index 07796d1e96a..882253f3883 100644 --- a/jstests/core/ref4.js +++ b/jstests/core/ref4.js @@ -5,10 +5,7 @@ b = db.ref4b; a.drop(); b.drop(); -var other = { - s: "other thing", - n: 17 -}; +var other = {s: "other thing", n: 17}; b.save(other); a.save({name: "abc", others: [new DBRef("ref4b", other._id), new DBPointer("ref4b", other._id)]}); diff --git a/jstests/core/regex2.js b/jstests/core/regex2.js index 80dec55f184..fe933892834 100644 --- a/jstests/core/regex2.js +++ b/jstests/core/regex2.js @@ -29,9 +29,8 @@ assert.eq(1, t.find({a: a}).count(), "C B"); assert.eq(1, t.find({a: b}).count(), "C C"); assert.eq(1, t.find({a: new RegExp(a)}).count(), "C D"); assert.eq(1, t.find({a: new RegExp(b)}).count(), "C E"); -assert.eq(2, - t.find({a: new RegExp(a, "i")}).count(), - "C F is spidermonkey built with UTF-8 support?"); +assert.eq( + 2, t.find({a: new RegExp(a, "i")}).count(), "C F is spidermonkey built with UTF-8 support?"); // same tests as above but using {$regex: "a|b", $options: "imx"} syntax. t.drop(); diff --git a/jstests/core/regex3.js b/jstests/core/regex3.js index bc1623cecea..23b7f3c69cc 100644 --- a/jstests/core/regex3.js +++ b/jstests/core/regex3.js @@ -8,9 +8,8 @@ t.save({name: "bob"}); t.save({name: "aaron"}); assert.eq(2, t.find({name: /^e.*/}).itcount(), "no index count"); -assert.eq(4, - t.find({name: /^e.*/}).explain(true).executionStats.totalDocsExamined, - "no index explain"); +assert.eq( + 4, t.find({name: /^e.*/}).explain(true).executionStats.totalDocsExamined, "no index explain"); t.ensureIndex({name: 1}); assert.eq(2, t.find({name: /^e.*/}).itcount(), "index count"); assert.eq(2, diff --git a/jstests/core/regex4.js b/jstests/core/regex4.js index 112375e2e09..131f93bcc26 100644 --- a/jstests/core/regex4.js +++ b/jstests/core/regex4.js @@ -8,9 +8,8 @@ t.save({name: "bob"}); t.save({name: "aaron"}); assert.eq(2, t.find({name: /^e.*/}).count(), "no index count"); -assert.eq(4, - t.find({name: /^e.*/}).explain(true).executionStats.totalDocsExamined, - "no index explain"); +assert.eq( + 4, t.find({name: /^e.*/}).explain(true).executionStats.totalDocsExamined, "no index explain"); // assert.eq( 2 , t.find( { name : { $ne : /^e.*/ } } ).count() , "no index count ne" ); // // SERVER-251 diff --git a/jstests/core/regex6.js b/jstests/core/regex6.js index 7b9ed1910ed..b7e90664c4d 100644 --- a/jstests/core/regex6.js +++ b/jstests/core/regex6.js @@ -11,30 +11,24 @@ t.save({name: "[with]some?symbols"}); t.ensureIndex({name: 1}); assert.eq(0, t.find({name: /^\//}).count(), "index count"); -assert.eq(1, - t.find({name: /^\//}).explain(true).executionStats.totalKeysExamined, - "index explain 1"); -assert.eq(0, - t.find({name: /^é/}).explain(true).executionStats.totalKeysExamined, - "index explain 2"); -assert.eq(0, - t.find({name: /^\é/}).explain(true).executionStats.totalKeysExamined, - "index explain 3"); -assert.eq(1, - t.find({name: /^\./}).explain(true).executionStats.totalKeysExamined, - "index explain 4"); -assert.eq(5, - t.find({name: /^./}).explain(true).executionStats.totalKeysExamined, - "index explain 5"); +assert.eq( + 1, t.find({name: /^\//}).explain(true).executionStats.totalKeysExamined, "index explain 1"); +assert.eq( + 0, t.find({name: /^é/}).explain(true).executionStats.totalKeysExamined, "index explain 2"); +assert.eq( + 0, t.find({name: /^\é/}).explain(true).executionStats.totalKeysExamined, "index explain 3"); +assert.eq( + 1, t.find({name: /^\./}).explain(true).executionStats.totalKeysExamined, "index explain 4"); +assert.eq( + 5, t.find({name: /^./}).explain(true).executionStats.totalKeysExamined, "index explain 5"); // SERVER-2862 assert.eq(0, t.find({name: /^\Qblah\E/}).count(), "index explain 6"); assert.eq(1, t.find({name: /^\Qblah\E/}).explain(true).executionStats.totalKeysExamined, "index explain 6"); -assert.eq(1, - t.find({name: /^blah/}).explain(true).executionStats.totalKeysExamined, - "index explain 6"); +assert.eq( + 1, t.find({name: /^blah/}).explain(true).executionStats.totalKeysExamined, "index explain 6"); assert.eq(1, t.find({name: /^\Q[\Ewi\Qth]some?s\Eym/}).count(), "index count 2"); assert.eq(2, t.find({name: /^\Q[\Ewi\Qth]some?s\Eym/}).explain(true).executionStats.totalKeysExamined, @@ -43,13 +37,11 @@ assert.eq(2, t.find({name: /^bob/}).explain(true).executionStats.totalKeysExamined, "index explain 6"); // proof executionStats.totalKeysExamined == count+1 -assert.eq(1, - t.find({name: {$regex: "^e", $gte: "emily"}}) - .explain(true) - .executionStats.totalKeysExamined, - "ie7"); -assert.eq(1, - t.find({name: {$gt: "a", $regex: "^emily"}}) - .explain(true) - .executionStats.totalKeysExamined, - "ie7"); +assert.eq( + 1, + t.find({name: {$regex: "^e", $gte: "emily"}}).explain(true).executionStats.totalKeysExamined, + "ie7"); +assert.eq( + 1, + t.find({name: {$gt: "a", $regex: "^emily"}}).explain(true).executionStats.totalKeysExamined, + "ie7"); diff --git a/jstests/core/remove7.js b/jstests/core/remove7.js index ef5500fa1fa..9c78b24eefa 100644 --- a/jstests/core/remove7.js +++ b/jstests/core/remove7.js @@ -22,9 +22,7 @@ t.ensureIndex({tags: 1}); for (i = 0; i < 200; i++) { for (var j = 0; j < 10; j++) t.save({tags: getTags(100)}); - var q = { - tags: {$in: getTags(10)} - }; + var q = {tags: {$in: getTags(10)}}; var before = t.find(q).count(); var res = t.remove(q); var after = t.find(q).count(); diff --git a/jstests/core/rename4.js b/jstests/core/rename4.js index 904709175f9..185193deaa9 100644 --- a/jstests/core/rename4.js +++ b/jstests/core/rename4.js @@ -101,9 +101,8 @@ good({aa: 1, b: 2}, {$rename: {z: 'c'}, $set: {b: 5}}, {aa: 1, b: 5}); good({a: {z: 1, b: 1}}, {$rename: {'a.b': 'a.c'}}, {a: {c: 1, z: 1}}); good({a: {z: 1, tomato: 1}}, {$rename: {'a.tomato': 'a.potato'}}, {a: {potato: 1, z: 1}}); good({a: {z: 1, b: 1, c: 1}}, {$rename: {'a.b': 'a.c'}}, {a: {c: 1, z: 1}}); -good({a: {z: 1, tomato: 1, potato: 1}}, - {$rename: {'a.tomato': 'a.potato'}}, - {a: {potato: 1, z: 1}}); +good( + {a: {z: 1, tomato: 1, potato: 1}}, {$rename: {'a.tomato': 'a.potato'}}, {a: {potato: 1, z: 1}}); good({a: {z: 1, b: 1}}, {$rename: {'a.b': 'a.cc'}}, {a: {cc: 1, z: 1}}); good({a: {z: 1, b: 1, c: 1}}, {$rename: {'a.b': 'aa.c'}}, {a: {c: 1, z: 1}, aa: {c: 1}}); diff --git a/jstests/core/repair_database.js b/jstests/core/repair_database.js index 45f936b022a..2005a7bf344 100644 --- a/jstests/core/repair_database.js +++ b/jstests/core/repair_database.js @@ -13,10 +13,7 @@ mydb.dropDatabase(); var myColl = mydb.a; // 2 -var doc = { - _id: 1, - a: "hello world" -}; +var doc = {_id: 1, a: "hello world"}; myColl.insert(doc); myColl.ensureIndex({a: 1}); mydb.repairDatabase(); diff --git a/jstests/core/return_key.js b/jstests/core/return_key.js index b39764846d4..3692521f58c 100644 --- a/jstests/core/return_key.js +++ b/jstests/core/return_key.js @@ -73,10 +73,9 @@ load("jstests/libs/analyze_plan.js"); .sort({b: 1}) .returnKey() .toArray(); - assert.eq(results, - [ - {a: 3, c: {'': 1}, d: {'': 1}}, - {a: 2, c: {'': 2}, d: {'': 2}}, - {a: 1, c: {'': 3}, d: {'': 3}} - ]); + assert.eq(results, [ + {a: 3, c: {'': 1}, d: {'': 1}}, + {a: 2, c: {'': 2}, d: {'': 2}}, + {a: 1, c: {'': 3}, d: {'': 3}} + ]); })(); diff --git a/jstests/core/role_management_helpers.js b/jstests/core/role_management_helpers.js index fa25d8a2d57..b47d87e5533 100644 --- a/jstests/core/role_management_helpers.js +++ b/jstests/core/role_management_helpers.js @@ -106,12 +106,10 @@ function assertHasPrivilege(privilegeArray, privilege) { assertHasRole(roleObj.roles, "roleC", db.getName()); // Privileges on the same resource get collapsed - db.grantPrivilegesToRole( - "roleA", - [ - {resource: {db: db.getName(), collection: ""}, actions: ['dropDatabase']}, - {resource: {db: db.getName(), collection: "foo"}, actions: ['insert']} - ]); + db.grantPrivilegesToRole("roleA", [ + {resource: {db: db.getName(), collection: ""}, actions: ['dropDatabase']}, + {resource: {db: db.getName(), collection: "foo"}, actions: ['insert']} + ]); roleObj = db.getRole("roleA", {showPrivileges: true}); assert.eq(0, roleObj.roles.length); assert.eq(2, roleObj.privileges.length); @@ -122,12 +120,10 @@ function assertHasPrivilege(privilegeArray, privilege) { {resource: {db: db.getName(), collection: ""}, actions: ['dropDatabase']}); // Update role - db.updateRole( - "roleA", - { - roles: ['roleB'], - privileges: [{resource: {db: db.getName(), collection: "foo"}, actions: ['find']}] - }); + db.updateRole("roleA", { + roles: ['roleB'], + privileges: [{resource: {db: db.getName(), collection: "foo"}, actions: ['find']}] + }); roleObj = db.getRole("roleA", {showPrivileges: true}); assert.eq(1, roleObj.roles.length); assertHasRole(roleObj.roles, "roleB", db.getName()); diff --git a/jstests/core/set_param1.js b/jstests/core/set_param1.js index 2df37442518..b0df18bccd3 100644 --- a/jstests/core/set_param1.js +++ b/jstests/core/set_param1.js @@ -28,14 +28,12 @@ assert.neq(undefined, assert.commandFailed(db.adminCommand({"setParameter": 1, logComponentVerbosity: "not an object"})); // Non-numeric verbosity for component should be rejected. -assert.commandFailed(db.adminCommand({ - "setParameter": 1, - logComponentVerbosity: {storage: {journal: {verbosity: "not a number"}}} -})); +assert.commandFailed(db.adminCommand( + {"setParameter": 1, logComponentVerbosity: {storage: {journal: {verbosity: "not a number"}}}})); // Invalid component shall be rejected -assert.commandFailed(db.adminCommand( - {"setParameter": 1, logComponentVerbosity: {NoSuchComponent: {verbosity: 2}}})); +assert.commandFailed( + db.adminCommand({"setParameter": 1, logComponentVerbosity: {NoSuchComponent: {verbosity: 2}}})); // Set multiple component log levels at once. (function() { diff --git a/jstests/core/sort3.js b/jstests/core/sort3.js index bfc1ee5134c..933f16da6cb 100644 --- a/jstests/core/sort3.js +++ b/jstests/core/sort3.js @@ -5,16 +5,13 @@ t.save({a: 1}); t.save({a: 5}); t.save({a: 3}); -assert.eq("1,5,3", - t.find().toArray().map(function(z) { - return z.a; - })); +assert.eq("1,5,3", t.find().toArray().map(function(z) { + return z.a; +})); -assert.eq("1,3,5", - t.find().sort({a: 1}).toArray().map(function(z) { - return z.a; - })); -assert.eq("5,3,1", - t.find().sort({a: -1}).toArray().map(function(z) { - return z.a; - })); +assert.eq("1,3,5", t.find().sort({a: 1}).toArray().map(function(z) { + return z.a; +})); +assert.eq("5,3,1", t.find().sort({a: -1}).toArray().map(function(z) { + return z.a; +})); diff --git a/jstests/core/sort5.js b/jstests/core/sort5.js index 399c9fb4e28..05fe781ae32 100644 --- a/jstests/core/sort5.js +++ b/jstests/core/sort5.js @@ -9,37 +9,29 @@ t.save({_id: 9, x: 4, y: {a: 9, b: 3}}); // test compound sorting assert.eq([4, 2, 3, 1], - t.find() - .sort({"y.b": 1, "y.a": -1}) - .map(function(z) { - return z.x; - }), + t.find().sort({"y.b": 1, "y.a": -1}).map(function(z) { + return z.x; + }), "A no index"); t.ensureIndex({"y.b": 1, "y.a": -1}); assert.eq([4, 2, 3, 1], - t.find() - .sort({"y.b": 1, "y.a": -1}) - .map(function(z) { - return z.x; - }), + t.find().sort({"y.b": 1, "y.a": -1}).map(function(z) { + return z.x; + }), "A index"); assert(t.validate().valid, "A valid"); // test sorting on compound key involving _id assert.eq([4, 2, 3, 1], - t.find() - .sort({"y.b": 1, _id: -1}) - .map(function(z) { - return z.x; - }), + t.find().sort({"y.b": 1, _id: -1}).map(function(z) { + return z.x; + }), "B no index"); t.ensureIndex({"y.b": 1, "_id": -1}); assert.eq([4, 2, 3, 1], - t.find() - .sort({"y.b": 1, _id: -1}) - .map(function(z) { - return z.x; - }), + t.find().sort({"y.b": 1, _id: -1}).map(function(z) { + return z.x; + }), "B index"); assert(t.validate().valid, "B valid"); diff --git a/jstests/core/sortk.js b/jstests/core/sortk.js index 7ecb86fa6df..76c381681eb 100644 --- a/jstests/core/sortk.js +++ b/jstests/core/sortk.js @@ -17,17 +17,10 @@ resetCollection(); t.ensureIndex({a: 1, b: 1}); function simpleQuery(extraFields, sort, hint) { - query = { - a: {$in: [1, 2]} - }; + query = {a: {$in: [1, 2]}}; Object.extend(query, extraFields); - sort = sort || { - b: 1 - }; - hint = hint || { - a: 1, - b: 1 - }; + sort = sort || {b: 1}; + hint = hint || {a: 1, b: 1}; return t.find(query).sort(sort).hint(hint); } @@ -133,9 +126,7 @@ assert.eq(0, andEqInQueryWithLimit(-2)[0].c); assert.eq(1, andEqInQueryWithLimit(-2)[1].c); function inQueryWithLimit(limit, sort) { - sort = sort || { - b: 1 - }; + sort = sort || {b: 1}; return t.find({a: {$in: [0, 1]}}).sort(sort).hint({a: 1, b: 1, c: 1}).limit(limit); } diff --git a/jstests/core/splitvector.js b/jstests/core/splitvector.js index 233911d29c6..9ba62e2df83 100644 --- a/jstests/core/splitvector.js +++ b/jstests/core/splitvector.js @@ -62,17 +62,17 @@ resetCollection(); // Case 1: missing parameters assert.eq(false, db.runCommand({splitVector: "test.jstests_splitvector"}).ok, "1a"); -assert.eq(false, - db.runCommand({splitVector: "test.jstests_splitvector", maxChunkSize: 1}).ok, - "1b"); +assert.eq( + false, db.runCommand({splitVector: "test.jstests_splitvector", maxChunkSize: 1}).ok, "1b"); // ------------------------- // Case 2: missing index -assert.eq(false, - db.runCommand( - {splitVector: "test.jstests_splitvector", keyPattern: {x: 1}, maxChunkSize: 1}).ok, - "2"); +assert.eq( + false, + db.runCommand({splitVector: "test.jstests_splitvector", keyPattern: {x: 1}, maxChunkSize: 1}) + .ok, + "2"); // ------------------------- // Case 3: empty collection diff --git a/jstests/core/stages_delete.js b/jstests/core/stages_delete.js index 1624b1fcc6a..f8e7380c75a 100644 --- a/jstests/core/stages_delete.js +++ b/jstests/core/stages_delete.js @@ -1,8 +1,6 @@ // Test basic delete stage functionality. var coll = db.stages_delete; -var collScanStage = { - cscan: {args: {direction: 1}, filter: {deleteMe: true}} -}; +var collScanStage = {cscan: {args: {direction: 1}, filter: {deleteMe: true}}}; var deleteStage; // Test delete stage with isMulti: true. diff --git a/jstests/core/stages_sort.js b/jstests/core/stages_sort.js index b6cb5a456af..6d25279fa27 100644 --- a/jstests/core/stages_sort.js +++ b/jstests/core/stages_sort.js @@ -25,9 +25,7 @@ if (false) { }; // Sort with foo ascending. - sort1 = { - sort: {args: {node: ixscan1, pattern: {foo: 1}}} - }; + sort1 = {sort: {args: {node: ixscan1, pattern: {foo: 1}}}}; res = db.runCommand({stageDebug: sort1}); assert.eq(res.ok, 1); assert.eq(res.results.length, 21); diff --git a/jstests/core/system_profile.js b/jstests/core/system_profile.js index 73d303a3277..09baf334290 100644 --- a/jstests/core/system_profile.js +++ b/jstests/core/system_profile.js @@ -26,25 +26,24 @@ assert.writeError(testDB.system.profile.remove({})); // Using findAndModify to write to "system.profile" should fail. assert.commandWorked(testDB.dropDatabase()); assert.commandWorked(testDB.createCollection("system.profile")); -assert.commandFailed(testDB.system.profile.runCommand("findAndModify", - {query: {}, update: {a: 1}})); -assert.commandFailed(testDB.system.profile.runCommand("findAndModify", - {query: {}, update: {a: 1}, upsert: true})); +assert.commandFailed( + testDB.system.profile.runCommand("findAndModify", {query: {}, update: {a: 1}})); +assert.commandFailed( + testDB.system.profile.runCommand("findAndModify", {query: {}, update: {a: 1}, upsert: true})); assert.commandFailed(testDB.system.profile.runCommand("findAndModify", {query: {}, remove: true})); // Using mapReduce to write to "system.profile" should fail. assert.commandWorked(testDB.dropDatabase()); assert.writeOK(testDB.foo.insert({val: 1})); -assert.commandFailed(testDB.foo.runCommand("mapReduce", - { - map: function() { - emit(0, this.val); - }, - reduce: function(id, values) { - return Array.sum(values); - }, - out: "system.profile" - })); +assert.commandFailed(testDB.foo.runCommand("mapReduce", { + map: function() { + emit(0, this.val); + }, + reduce: function(id, values) { + return Array.sum(values); + }, + out: "system.profile" +})); // Using aggregate to write to "system.profile" should fail. assert.commandWorked(testDB.dropDatabase()); diff --git a/jstests/core/update_find_and_modify_id.js b/jstests/core/update_find_and_modify_id.js index a75a5595451..ca565cb0e8c 100644 --- a/jstests/core/update_find_and_modify_id.js +++ b/jstests/core/update_find_and_modify_id.js @@ -2,10 +2,7 @@ // an _id in the update document, as long as the _id will not be modified var t = db.jstests_server4516; -var startingDoc = { - _id: 1, - a: 1 -}; +var startingDoc = {_id: 1, a: 1}; function prepare() { t.drop(); diff --git a/jstests/core/update_min_max_examples.js b/jstests/core/update_min_max_examples.js index a8a86f22986..7bcb6197f93 100644 --- a/jstests/core/update_min_max_examples.js +++ b/jstests/core/update_min_max_examples.js @@ -46,10 +46,7 @@ assert.writeOK(res); assert.eq(coll.findOne({_id: 6}).a, 1e-15); // $max with positional operator -var insertdoc = { - _id: 7, - y: [{a: 2}, {a: 6}, {a: [9, 1, 1]}] -}; +var insertdoc = {_id: 7, y: [{a: 2}, {a: 6}, {a: [9, 1, 1]}]}; coll.insert(insertdoc); res = coll.update({_id: 7, "y.a": 6}, {$max: {"y.$.a": 7}}); assert.writeOK(res); diff --git a/jstests/core/update_server-12848.js b/jstests/core/update_server-12848.js index c33e8dd9f62..0f86e0135b3 100644 --- a/jstests/core/update_server-12848.js +++ b/jstests/core/update_server-12848.js @@ -8,10 +8,7 @@ var res; var t = db.update_server_12848; t.drop(); -var orig = { - "_id": 1, - "a": [1, []] -}; +var orig = {"_id": 1, "a": [1, []]}; res = t.insert(orig); assert.writeOK(res, "insert"); assert.eq(orig, t.findOne()); @@ -19,8 +16,5 @@ assert.eq(orig, t.findOne()); res = t.update({"_id": 1}, {$addToSet: {"a.1": 1}}); assert.writeOK(res, "update"); -var updated = { - "_id": 1, - "a": [1, [1]] -}; +var updated = {"_id": 1, "a": [1, [1]]}; assert.eq(updated, t.findOne()); diff --git a/jstests/core/upsert_fields.js b/jstests/core/upsert_fields.js index ae385980b1b..910ae6d3e11 100644 --- a/jstests/core/upsert_fields.js +++ b/jstests/core/upsert_fields.js @@ -60,13 +60,9 @@ for (var i = 0; i < 3; i++) { // $op style if (i == 1) - expr = { - $set: {a: 1} - }; + expr = {$set: {a: 1}}; if (i == 2) - expr = { - $setOnInsert: {a: 1} - }; + expr = {$setOnInsert: {a: 1}}; var isReplStyle = i == 0; @@ -135,13 +131,9 @@ for (var i = 0; i < 3; i++) { // $op style if (i == 1) - expr = { - $set: {a: 1} - }; + expr = {$set: {a: 1}}; if (i == 2) - expr = { - $setOnInsert: {a: 1} - }; + expr = {$setOnInsert: {a: 1}}; var isReplStyle = i == 0; @@ -187,9 +179,7 @@ for (var i = 0; i < 3; i++) { } // nested field extraction - var docValue = isReplStyle ? undefined : { - x: 1 - }; + var docValue = isReplStyle ? undefined : {x: 1}; assert.docEq(docValue, upsertedXVal({"x.x": 1}, expr)); assert.docEq(docValue, upsertedXVal({"x.x": {$eq: 1}}, expr)); assert.docEq(docValue, upsertedXVal({"x.x": {$all: [1]}}, expr)); diff --git a/jstests/core/validate_user_documents.js b/jstests/core/validate_user_documents.js index 9c12e6075a7..676c47a301f 100644 --- a/jstests/core/validate_user_documents.js +++ b/jstests/core/validate_user_documents.js @@ -34,8 +34,7 @@ assert.commandWorked(mydb.runCommand({createUser: "spencer", pwd: "password", ro assert.commandWorked(mydb.runCommand({ createUser: "andy", pwd: "password", - roles: - [{role: "dbAdmin", db: "validate_user_documents", hasRole: true, canDelegate: false}] + roles: [{role: "dbAdmin", db: "validate_user_documents", hasRole: true, canDelegate: false}] })); // Non-existent role; insert should fail diff --git a/jstests/core/where1.js b/jstests/core/where1.js index 85466901016..53441580b90 100644 --- a/jstests/core/where1.js +++ b/jstests/core/where1.js @@ -8,8 +8,8 @@ t.save({a: 3}); assert.eq(1, t.find(function() { - return this.a == 2; - }).length(), + return this.a == 2; + }).length(), "A"); assert.eq(1, t.find({$where: "return this.a == 2"}).toArray().length, "B"); diff --git a/jstests/core/where3.js b/jstests/core/where3.js index 633276489a5..e26b36ffcf4 100644 --- a/jstests/core/where3.js +++ b/jstests/core/where3.js @@ -7,8 +7,8 @@ t.save({returned_date: 6}); assert.eq(1, t.find(function() { - return this.returned_date == 5; - }).count(), + return this.returned_date == 5; + }).count(), "A"); assert.eq(1, t.find({$where: "return this.returned_date == 5;"}).count(), "B"); assert.eq(1, t.find({$where: "this.returned_date == 5;"}).count(), "C"); diff --git a/jstests/core/where4.js b/jstests/core/where4.js index 612dba59e67..3db37ae6fe5 100644 --- a/jstests/core/where4.js +++ b/jstests/core/where4.js @@ -5,15 +5,14 @@ myDB.dropDatabase(); assert.writeOK(myDB.where4.insert({x: 1, y: 1})); assert.writeOK(myDB.where4.insert({x: 2, y: 1})); -assert.writeOK(myDB.where4.update( - { - $where: function() { - return this.x == 1; - } - }, - {$inc: {y: 1}}, - false, - true)); +assert.writeOK(myDB.where4.update({ + $where: function() { + return this.x == 1; + } +}, + {$inc: {y: 1}}, + false, + true)); assert.eq(2, myDB.where4.findOne({x: 1}).y); assert.eq(1, myDB.where4.findOne({x: 2}).y); diff --git a/jstests/decimal/decimal_find_query.js b/jstests/decimal/decimal_find_query.js index 47e5c7167d0..7f3d8c10284 100644 --- a/jstests/decimal/decimal_find_query.js +++ b/jstests/decimal/decimal_find_query.js @@ -29,11 +29,10 @@ assert.eq(col.find({'decimal': {$gte: NumberDecimal('2.000')}}).count(), 3); assert.eq(col.find({'decimal': {$lte: NumberDecimal('0.9999999999999999')}}).count(), 4); - assert.eq( - col.find({'decimal': {$nin: [NumberDecimal('Infinity'), NumberDecimal('-Infinity')]}}) - .count(), - 9, - 'Infinity count incorrect'); + assert.eq(col.find({'decimal': {$nin: [NumberDecimal('Infinity'), NumberDecimal('-Infinity')]}}) + .count(), + 9, + 'Infinity count incorrect'); // Test $mod col.drop(); diff --git a/jstests/disk/datafile_options.js b/jstests/disk/datafile_options.js index a7639c43d7d..d495e61cff2 100644 --- a/jstests/disk/datafile_options.js +++ b/jstests/disk/datafile_options.js @@ -3,9 +3,7 @@ var baseName = "jstests_disk_datafile_options"; load('jstests/libs/command_line/test_parsed_options.js'); jsTest.log("Testing \"noprealloc\" command line option"); -var expectedResult = { - "parsed": {"storage": {"mmapv1": {"preallocDataFiles": false}}} -}; +var expectedResult = {"parsed": {"storage": {"mmapv1": {"preallocDataFiles": false}}}}; testGetCmdLineOptsMongod({noprealloc: ""}, expectedResult); jsTest.log("Testing \"storage.mmapv1.preallocDataFiles\" config file option"); diff --git a/jstests/disk/dbNoCreate.js b/jstests/disk/dbNoCreate.js index f3498fcedb4..66c2cc74ad6 100644 --- a/jstests/disk/dbNoCreate.js +++ b/jstests/disk/dbNoCreate.js @@ -12,6 +12,5 @@ t.drop(); MongoRunner.stopMongod(m); m = MongoRunner.runMongod({restart: true, cleanData: false, dbpath: m.dbpath}); -assert.eq(-1, - m.getDBNames().indexOf(baseName), - "found " + baseName + " in " + tojson(m.getDBNames())); +assert.eq( + -1, m.getDBNames().indexOf(baseName), "found " + baseName + " in " + tojson(m.getDBNames())); diff --git a/jstests/disk/index_options.js b/jstests/disk/index_options.js index 68710de75a1..faa12e23fdd 100644 --- a/jstests/disk/index_options.js +++ b/jstests/disk/index_options.js @@ -3,9 +3,7 @@ var baseName = "jstests_disk_index_options"; load('jstests/libs/command_line/test_parsed_options.js'); jsTest.log("Testing \"noIndexBuildRetry\" command line option"); -var expectedResult = { - "parsed": {"storage": {"indexBuildRetry": false}} -}; +var expectedResult = {"parsed": {"storage": {"indexBuildRetry": false}}}; testGetCmdLineOptsMongod({noIndexBuildRetry: ""}, expectedResult); jsTest.log("Testing \"storage.indexBuildRetry\" config file option"); diff --git a/jstests/dur/journaling_options.js b/jstests/dur/journaling_options.js index d0600009a70..28402e9536c 100644 --- a/jstests/dur/journaling_options.js +++ b/jstests/dur/journaling_options.js @@ -5,27 +5,19 @@ function doTest() { load('jstests/libs/command_line/test_parsed_options.js'); jsTest.log("Testing \"dur\" command line option"); - var expectedResult = { - "parsed": {"storage": {"journal": {"enabled": true}}} - }; + var expectedResult = {"parsed": {"storage": {"journal": {"enabled": true}}}}; testGetCmdLineOptsMongod({dur: ""}, expectedResult); jsTest.log("Testing \"nodur\" command line option"); - expectedResult = { - "parsed": {"storage": {"journal": {"enabled": false}}} - }; + expectedResult = {"parsed": {"storage": {"journal": {"enabled": false}}}}; testGetCmdLineOptsMongod({nodur: ""}, expectedResult); jsTest.log("Testing \"journal\" command line option"); - expectedResult = { - "parsed": {"storage": {"journal": {"enabled": true}}} - }; + expectedResult = {"parsed": {"storage": {"journal": {"enabled": true}}}}; testGetCmdLineOptsMongod({journal: ""}, expectedResult); jsTest.log("Testing \"nojournal\" command line option"); - expectedResult = { - "parsed": {"storage": {"journal": {"enabled": false}}} - }; + expectedResult = {"parsed": {"storage": {"journal": {"enabled": false}}}}; testGetCmdLineOptsMongod({nojournal: ""}, expectedResult); jsTest.log("Testing \"storage.journal.enabled\" config file option"); diff --git a/jstests/gle/gle_explicit_optime.js b/jstests/gle/gle_explicit_optime.js index 476409c57b4..8a0bc0e4676 100644 --- a/jstests/gle/gle_explicit_optime.js +++ b/jstests/gle/gle_explicit_optime.js @@ -42,22 +42,13 @@ assert.eq(null, gleObj.err); // Using an explicit optime on the new client should work if the optime is earlier than the // secondary was locked -var gleOpTimeBefore = { - getLastError: true, - w: 2, - wOpTime: opTimeBeforeFailure -}; +var gleOpTimeBefore = {getLastError: true, w: 2, wOpTime: opTimeBeforeFailure}; gleObj = newClientConn.getCollection(coll.toString()).getDB().runCommand(gleOpTimeBefore); assert.eq(null, gleObj.err); // Using an explicit optime on the new client should not work if the optime is later than the // secondary was locked -var gleOpTimeAfter = { - getLastError: true, - w: 2, - wtimeout: 1000, - wOpTime: opTimeAfterFailure -}; +var gleOpTimeAfter = {getLastError: true, w: 2, wtimeout: 1000, wOpTime: opTimeAfterFailure}; gleObj = newClientConn.getCollection(coll.toString()).getDB().runCommand(gleOpTimeAfter); assert.neq(null, gleObj.err); assert(gleObj.wtimeout); diff --git a/jstests/gle/opcounters_legacy.js b/jstests/gle/opcounters_legacy.js index b243b8bc076..f4168305e2c 100644 --- a/jstests/gle/opcounters_legacy.js +++ b/jstests/gle/opcounters_legacy.js @@ -170,10 +170,7 @@ assert.eq(metricsObj.serverStatus.failed, serverStatus = db.runCommand({serverStatus: 1}); opCounters = serverStatus.opcounters; metricsObj = serverStatus.metrics.commands; -var countVal = { - "total": 0, - "failed": 0 -}; +var countVal = {"total": 0, "failed": 0}; if (metricsObj.count != null) { countVal = metricsObj.count; } diff --git a/jstests/httpinterface/network_options.js b/jstests/httpinterface/network_options.js index 0302c9ac15b..ff5e453b4ec 100644 --- a/jstests/httpinterface/network_options.js +++ b/jstests/httpinterface/network_options.js @@ -6,9 +6,7 @@ load('jstests/libs/command_line/test_parsed_options.js'); // Object Check jsTest.log("Testing \"objcheck\" command line option"); -var expectedResult = { - "parsed": {"net": {"wireObjectCheck": true}} -}; +var expectedResult = {"parsed": {"net": {"wireObjectCheck": true}}}; testGetCmdLineOptsMongod({objcheck: ""}, expectedResult); jsTest.log("Testing \"noobjcheck\" command line option"); @@ -35,9 +33,7 @@ testGetCmdLineOptsMongod({}, expectedResult); // HTTP Interface jsTest.log("Testing \"httpinterface\" command line option"); -var expectedResult = { - "parsed": {"net": {"http": {"enabled": true}}} -}; +var expectedResult = {"parsed": {"net": {"http": {"enabled": true}}}}; testGetCmdLineOptsMongod({httpinterface: ""}, expectedResult); jsTest.log("Testing \"nohttpinterface\" command line option"); @@ -77,9 +73,7 @@ testGetCmdLineOptsMongod({}, expectedResult); // Unix Socket if (!_isWindows()) { jsTest.log("Testing \"nounixsocket\" command line option"); - expectedResult = { - "parsed": {"net": {"unixDomainSocket": {"enabled": false}}} - }; + expectedResult = {"parsed": {"net": {"unixDomainSocket": {"enabled": false}}}}; testGetCmdLineOptsMongod({nounixsocket: ""}, expectedResult); jsTest.log("Testing \"net.wireObjectCheck\" config file option"); @@ -93,9 +87,7 @@ if (!_isWindows()) { expectedResult); jsTest.log("Testing with no explicit network option setting"); - expectedResult = { - "parsed": {"net": {}} - }; + expectedResult = {"parsed": {"net": {}}}; testGetCmdLineOptsMongod({}, expectedResult); } diff --git a/jstests/libs/chunk_manipulation_util.js b/jstests/libs/chunk_manipulation_util.js index a334cbe8aec..dcf46fe4529 100644 --- a/jstests/libs/chunk_manipulation_util.js +++ b/jstests/libs/chunk_manipulation_util.js @@ -28,9 +28,7 @@ function moveChunkParallel(staticMongod, mongosURL, findCriteria, bounds, ns, to assert((findCriteria || bounds) && !(findCriteria && bounds), 'Specify either findCriteria or bounds, but not both.'); - var mongos = new Mongo(mongosURL), admin = mongos.getDB('admin'), cmd = { - moveChunk: ns - }; + var mongos = new Mongo(mongosURL), admin = mongos.getDB('admin'), cmd = {moveChunk: ns}; if (findCriteria) { cmd.find = findCriteria; diff --git a/jstests/libs/cleanup_orphaned_util.js b/jstests/libs/cleanup_orphaned_util.js index cfd69ab128f..3990c148df4 100644 --- a/jstests/libs/cleanup_orphaned_util.js +++ b/jstests/libs/cleanup_orphaned_util.js @@ -94,12 +94,8 @@ function testCleanupOrphaned(options) { assert.commandWorked(admin.runCommand({split: coll.getFullName(), middle: oneQuarter})); - assert.commandWorked(admin.runCommand({ - moveChunk: coll.getFullName(), - find: beginning, - to: shards[1]._id, - _waitForDelete: true - })); + assert.commandWorked(admin.runCommand( + {moveChunk: coll.getFullName(), find: beginning, to: shards[1]._id, _waitForDelete: true})); // 1/4 of the data is on the first shard. // shard 0: [threeQuarters, middle) diff --git a/jstests/libs/csrs_upgrade_util.js b/jstests/libs/csrs_upgrade_util.js index 7dccccc3e7c..8d43507beee 100644 --- a/jstests/libs/csrs_upgrade_util.js +++ b/jstests/libs/csrs_upgrade_util.js @@ -127,12 +127,8 @@ var CSRSUpgradeCoordinator = function() { */ this.restartFirstConfigAsReplSet = function() { jsTest.log("Restarting " + st.c0.name + " as a standalone replica set"); - csrsConfig = { - _id: csrsName, - version: 1, - configsvr: true, - members: [{_id: 0, host: st.c0.name}] - }; + csrsConfig = + {_id: csrsName, version: 1, configsvr: true, members: [{_id: 0, host: st.c0.name}]}; assert.commandWorked(st.c0.adminCommand({replSetInitiate: csrsConfig})); csrs = []; csrs0Opts = Object.extend({}, st.c0.fullOptions, /* deep */ true); diff --git a/jstests/libs/election_timing_test.js b/jstests/libs/election_timing_test.js index f40ad5f931b..16634530abf 100644 --- a/jstests/libs/election_timing_test.js +++ b/jstests/libs/election_timing_test.js @@ -48,10 +48,7 @@ var ElectionTimingTest = function(opts) { ElectionTimingTest.prototype._runTimingTest = function() { for (var run = 0; run < this.testRuns; run++) { var collectionName = "test." + this.name; - var cycleData = { - testRun: run, - results: [] - }; + var cycleData = {testRun: run, results: []}; jsTestLog("Starting ReplSetTest for test " + this.name + " run: " + run); this.rst = diff --git a/jstests/libs/fts.js b/jstests/libs/fts.js index eb5baec8a5a..e46b492564a 100644 --- a/jstests/libs/fts.js +++ b/jstests/libs/fts.js @@ -1,13 +1,9 @@ // Utility functions for FTS tests // function queryIDS(coll, search, filter, extra, limit) { - var query = { - "$text": {"$search": search} - }; + var query = {"$text": {"$search": search}}; if (extra) - query = { - "$text": Object.extend({"$search": search}, extra) - }; + query = {"$text": Object.extend({"$search": search}, extra)}; if (filter) Object.extend(query, filter); @@ -17,8 +13,8 @@ function queryIDS(coll, search, filter, extra, limit) { .sort({score: {"$meta": "textScore"}}) .limit(limit); else - result = coll.find(query, {score: {"$meta": "textScore"}}) - .sort({score: {"$meta": "textScore"}}); + result = + coll.find(query, {score: {"$meta": "textScore"}}).sort({score: {"$meta": "textScore"}}); return getIDS(result); } diff --git a/jstests/libs/geo_near_random.js b/jstests/libs/geo_near_random.js index 2af13814173..91f0167ea31 100644 --- a/jstests/libs/geo_near_random.js +++ b/jstests/libs/geo_near_random.js @@ -65,12 +65,7 @@ GeoNearRandomTest.prototype.testPt = function(pt, opts) { print("testing point: " + tojson(pt) + " opts: " + tojson(opts)); - var cmd = { - geoNear: this.t.getName(), - near: pt, - num: 1, - spherical: opts.sphere - }; + var cmd = {geoNear: this.t.getName(), near: pt, num: 1, spherical: opts.sphere}; var last = db.runCommand(cmd).results; for (var i = 2; i <= opts.nToTest; i++) { @@ -97,9 +92,7 @@ GeoNearRandomTest.prototype.testPt = function(pt, opts) { return x.obj; }); - var query = { - loc: {} - }; + var query = {loc: {}}; query.loc[opts.sphere ? '$nearSphere' : '$near'] = pt; var near = this.t.find(query).limit(opts.nToTest).toArray(); diff --git a/jstests/libs/override_methods/implicitly_shard_accessed_collections.js b/jstests/libs/override_methods/implicitly_shard_accessed_collections.js index 313bd7faf7c..65e32bd8a53 100644 --- a/jstests/libs/override_methods/implicitly_shard_accessed_collections.js +++ b/jstests/libs/override_methods/implicitly_shard_accessed_collections.js @@ -14,7 +14,11 @@ var originalGetCollection = DB.prototype.getCollection; // Blacklisted namespaces that should not be sharded. - var blacklistedNamespaces = [/\$cmd/, /^admin\./, /\.system\./, ]; + var blacklistedNamespaces = [ + /\$cmd/, + /^admin\./, + /\.system\./, + ]; DB.prototype.getCollection = function() { var dbName = this.getName(); diff --git a/jstests/libs/override_methods/set_majority_read_and_write_concerns.js b/jstests/libs/override_methods/set_majority_read_and_write_concerns.js index 767134d43a4..232d97e6562 100644 --- a/jstests/libs/override_methods/set_majority_read_and_write_concerns.js +++ b/jstests/libs/override_methods/set_majority_read_and_write_concerns.js @@ -9,9 +9,7 @@ // Use a "signature" value that won't typically match a value assigned in normal use. wtimeout: 60321 }; - var defaultReadConcern = { - level: "majority" - }; + var defaultReadConcern = {level: "majority"}; var originalDBQuery = DBQuery; @@ -82,11 +80,19 @@ // These commands do writes but do not support a writeConcern argument. Emulate it with a // getLastError command. - var commandsToEmulateWriteConcern = ["createIndexes", ]; + var commandsToEmulateWriteConcern = [ + "createIndexes", + ]; // These are reading commands that support majority readConcern. - var commandsToForceReadConcern = - ["count", "distinct", "find", "geoNear", "geoSearch", "group", ]; + var commandsToForceReadConcern = [ + "count", + "distinct", + "find", + "geoNear", + "geoSearch", + "group", + ]; var forceWriteConcern = Array.contains(commandsToForceWriteConcern, cmdName); var emulateWriteConcern = Array.contains(commandsToEmulateWriteConcern, cmdName); diff --git a/jstests/libs/override_methods/sharding_continuous_config_stepdown.js b/jstests/libs/override_methods/sharding_continuous_config_stepdown.js index aea3e482961..d0d2814fc90 100644 --- a/jstests/libs/override_methods/sharding_continuous_config_stepdown.js +++ b/jstests/libs/override_methods/sharding_continuous_config_stepdown.js @@ -106,16 +106,10 @@ function retryOnNetworkError(func) { }
print('*** Continuous stepdown thread completed successfully');
- return {
- ok: 1
- };
+ return {ok: 1};
} catch (e) {
print('*** Continuous stepdown thread caught exception: ' + tojson(e));
- return {
- ok: 0,
- error: e.toString(),
- stack: e.stack
- };
+ return {ok: 0, error: e.toString(), stack: e.stack};
}
}
@@ -209,12 +203,12 @@ function retryOnNetworkError(func) { // Set electionTimeoutMillis to 5 seconds, from 10, so that chunk migrations don't
// time out because of the CSRS primary being down so often for so long.
- arguments[0].configReplSetTestOptions = Object.merge(arguments[0].configReplSetTestOptions,
- {
- settings: {
- electionTimeoutMillis: 5000,
- },
- });
+ arguments[0].configReplSetTestOptions =
+ Object.merge(arguments[0].configReplSetTestOptions, {
+ settings: {
+ electionTimeoutMillis: 5000,
+ },
+ });
// Construct the original object
originalShardingTest.apply(this, arguments);
diff --git a/jstests/libs/test_background_ops.js b/jstests/libs/test_background_ops.js index 384e0bd5b64..db2361d67c8 100644 --- a/jstests/libs/test_background_ops.js +++ b/jstests/libs/test_background_ops.js @@ -43,9 +43,7 @@ var waitForLock = function(mongo, name) { }; // Return an object we can invoke unlock on - return { - unlock: unlock - }; + return {unlock: unlock}; }; /** diff --git a/jstests/libs/trace_missing_docs.js b/jstests/libs/trace_missing_docs.js index 3bc9ef75333..d0052f55f6f 100644 --- a/jstests/libs/trace_missing_docs.js +++ b/jstests/libs/trace_missing_docs.js @@ -23,12 +23,8 @@ function traceMissingDoc(coll, doc, mongos) { if (doc[k] == undefined) { jsTest.log("Shard key " + tojson(shardKey) + " not found in doc " + tojson(doc) + ", falling back to _id search..."); - shardKeyPatt = { - _id: 1 - }; - shardKey = { - _id: doc['_id'] - }; + shardKeyPatt = {_id: 1}; + shardKey = {_id: doc['_id']}; break; } shardKey[k] = doc[k]; @@ -70,9 +66,7 @@ function traceMissingDoc(coll, doc, mongos) { // Find ops addToOps(oplog.find(addKeyQuery({op: 'i'}, 'o'))); - var updateQuery = { - $or: [addKeyQuery({op: 'u'}, 'o2'), {op: 'u', 'o2._id': doc['_id']}] - }; + var updateQuery = {$or: [addKeyQuery({op: 'u'}, 'o2'), {op: 'u', 'o2._id': doc['_id']}]}; addToOps(oplog.find(updateQuery)); addToOps(oplog.find({op: 'd', 'o._id': doc['_id']})); } diff --git a/jstests/mmap_v1/capped2.js b/jstests/mmap_v1/capped2.js index ae74a396f98..82a6dca3874 100644 --- a/jstests/mmap_v1/capped2.js +++ b/jstests/mmap_v1/capped2.js @@ -9,9 +9,7 @@ function debug(x) { var val = new Array(2000); var c = ""; for (i = 0; i < 2000; ++i, c += "---") { // bigger and bigger objects through the array... - val[i] = { - a: c - }; + val[i] = {a: c}; } function checkIncreasing(i) { diff --git a/jstests/mmap_v1/capped8.js b/jstests/mmap_v1/capped8.js index 68b3deb0b2a..78b9d1b2017 100644 --- a/jstests/mmap_v1/capped8.js +++ b/jstests/mmap_v1/capped8.js @@ -10,10 +10,7 @@ function debug(x) { /** Generate an object with a string field of specified length */ function obj(size, x) { - return { - X: x, - a: new Array(size + 1).toString() - }; + return {X: x, a: new Array(size + 1).toString()}; } function withinTwo(a, b) { diff --git a/jstests/mmap_v1/collmod.js b/jstests/mmap_v1/collmod.js index 53c83f7d927..0ac6e98df60 100644 --- a/jstests/mmap_v1/collmod.js +++ b/jstests/mmap_v1/collmod.js @@ -54,9 +54,8 @@ assert.eq(0, res.ok, "TTL mod shouldn't work with non-numeric expireAfterSeconds var res = db.runCommand({"collMod": coll, "index": {"keyPattern": {a: 1}, "expireAfterSeconds": 100}}); debug(res); -assert.eq(1, - db.system.indexes.count({key: {a: 1}, expireAfterSeconds: 100}), - "TTL index not modified"); +assert.eq( + 1, db.system.indexes.count({key: {a: 1}, expireAfterSeconds: 100}), "TTL index not modified"); // try to modify a faulty TTL index with a non-numeric expireAfterSeconds field t.dropIndex({a: 1}); diff --git a/jstests/mmap_v1/datasize.js b/jstests/mmap_v1/datasize.js index 8c61b927748..d12527a8922 100644 --- a/jstests/mmap_v1/datasize.js +++ b/jstests/mmap_v1/datasize.js @@ -27,20 +27,16 @@ assert.eq(96, db.runCommand({datasize: "test.jstests_datasize", min: {qq: 'a'}, max: {qq: 'z'}}).size); assert.eq(48, db.runCommand({datasize: "test.jstests_datasize", min: {qq: 'a'}, max: {qq: 'd'}}).size); -assert.eq(48, - db.runCommand({ - datasize: "test.jstests_datasize", - min: {qq: 'a'}, - max: {qq: 'd'}, - keyPattern: {qq: 1} - }).size); -assert.eq(48, - db.runCommand({ - datasize: "test.jstests_datasize", - min: {qq: 'd'}, - max: {qq: 'z'}, - keyPattern: {qq: 1} - }).size); +assert.eq( + 48, + db.runCommand( + {datasize: "test.jstests_datasize", min: {qq: 'a'}, max: {qq: 'd'}, keyPattern: {qq: 1}}) + .size); +assert.eq( + 48, + db.runCommand( + {datasize: "test.jstests_datasize", min: {qq: 'd'}, max: {qq: 'z'}, keyPattern: {qq: 1}}) + .size); assert.eq(0, db.runCommand({datasize: "test.jstests_datasize", min: {qq: 'c'}, max: {qq: 'c'}}).size); @@ -50,5 +46,5 @@ assert.eq(48, assert.eq( 0, db.runCommand( - {datasize: "test.jstests_datasize", min: {qq: 'a'}, max: {qq: 'd'}, keyPattern: {a: 1}}) + {datasize: "test.jstests_datasize", min: {qq: 'a'}, max: {qq: 'd'}, keyPattern: {a: 1}}) .ok); diff --git a/jstests/mmap_v1/datasize3.js b/jstests/mmap_v1/datasize3.js index cefcdcf9949..da5d89384b2 100644 --- a/jstests/mmap_v1/datasize3.js +++ b/jstests/mmap_v1/datasize3.js @@ -3,9 +3,7 @@ t = db.datasize3; t.drop(); function run(options) { - var c = { - dataSize: "test.datasize3" - }; + var c = {dataSize: "test.datasize3"}; if (options) Object.extend(c, options); return db.runCommand(c); diff --git a/jstests/mmap_v1/update.js b/jstests/mmap_v1/update.js index fd96337aacf..3e132ca666a 100644 --- a/jstests/mmap_v1/update.js +++ b/jstests/mmap_v1/update.js @@ -11,9 +11,7 @@ var iterations = _isWindows() ? 2500 : 5000; // fill db for (var i = 1; i <= iterations; i++) { - var obj = { - txt: txt - }; + var obj = {txt: txt}; asdf.save(obj); var obj2 = { @@ -36,7 +34,7 @@ var stats = db.runCommand({collstats: "asdf"}); // basic // testing of the collstats command at the same time assert(stats.count == iterations); -assert(stats.size<140433012 * 5 && stats.size> 1000000); +assert(stats.size < 140433012 * 5 && stats.size > 1000000); assert(stats.numExtents < 20); assert(stats.nindexes == 1); diff --git a/jstests/mmap_v1/use_power_of_2.js b/jstests/mmap_v1/use_power_of_2.js index a192a79653d..b3db7077e1d 100644 --- a/jstests/mmap_v1/use_power_of_2.js +++ b/jstests/mmap_v1/use_power_of_2.js @@ -5,14 +5,8 @@ */ // prepare a doc of 14K -var doc = { - _id: new Object(), - data: "a" -}; -var bigDoc = { - _id: new Object(), - data: "a" -}; +var doc = {_id: new Object(), data: "a"}; +var bigDoc = {_id: new Object(), data: "a"}; while (doc.data.length < 14 * 1024) doc.data += "a"; diff --git a/jstests/multiVersion/geo_2dsphere_v2_to_v3.js b/jstests/multiVersion/geo_2dsphere_v2_to_v3.js index 9fa3773e2a8..c00612a492f 100644 --- a/jstests/multiVersion/geo_2dsphere_v2_to_v3.js +++ b/jstests/multiVersion/geo_2dsphere_v2_to_v3.js @@ -3,9 +3,7 @@ function generatePoint() { var longitude = Math.random() * 10 - 5; var latitude = Math.random() * 10 - 5; - var pt = { - geometry: {type: "Point", coordinates: [longitude, latitude]} - }; + var pt = {geometry: {type: "Point", coordinates: [longitude, latitude]}}; return pt; } @@ -49,9 +47,7 @@ function get2dsphereIndexVersion(coll) { return -1; } -var nearQuery = { - geometry: {$near: {$geometry: {type: "Point", coordinates: [0, 0]}}} -}; +var nearQuery = {geometry: {$near: {$geometry: {type: "Point", coordinates: [0, 0]}}}}; var mongod = MongoRunner.runMongod({binVersion: "3.0"}); var coll = getCollection(mongod); diff --git a/jstests/multiVersion/initialsync.js b/jstests/multiVersion/initialsync.js index bbc06c11490..e9a424fd05c 100644 --- a/jstests/multiVersion/initialsync.js +++ b/jstests/multiVersion/initialsync.js @@ -8,10 +8,7 @@ var newVersion = "latest"; var name = "multiversioninitsync"; var multitest = function(replSetVersion, newNodeVersion) { - var nodes = { - n1: {binVersion: replSetVersion}, - n2: {binVersion: replSetVersion} - }; + var nodes = {n1: {binVersion: replSetVersion}, n2: {binVersion: replSetVersion}}; print("Start up a two-node " + replSetVersion + " replica set."); var rst = new ReplSetTest({name: name, nodes: nodes}); diff --git a/jstests/multiVersion/invalid_key_pattern_upgrade.js b/jstests/multiVersion/invalid_key_pattern_upgrade.js index ce71333ef40..a3098e34c0a 100644 --- a/jstests/multiVersion/invalid_key_pattern_upgrade.js +++ b/jstests/multiVersion/invalid_key_pattern_upgrade.js @@ -8,7 +8,11 @@ (function() { 'use strict'; - var testCases = [{a: 0}, {a: NaN}, {a: true}, ]; + var testCases = [ + {a: 0}, + {a: NaN}, + {a: true}, + ]; // The mongod should not start up when an index with an invalid key pattern exists. testCases.forEach(function(indexKeyPattern) { @@ -49,7 +53,10 @@ // replicates. testCases.forEach(function(indexKeyPattern) { var replSetName = 'invalid_key_pattern_replset'; - var nodes = [{binVersion: '3.2'}, {binVersion: 'latest'}, ]; + var nodes = [ + {binVersion: '3.2'}, + {binVersion: 'latest'}, + ]; var rst = new ReplSetTest({name: replSetName, nodes: nodes}); diff --git a/jstests/multiVersion/libs/data_generators.js b/jstests/multiVersion/libs/data_generators.js index c2af0638a5f..bc48845fbb2 100644 --- a/jstests/multiVersion/libs/data_generators.js +++ b/jstests/multiVersion/libs/data_generators.js @@ -56,9 +56,7 @@ function DataGenerator() { function GenObject(seed) { var seed = seed || 0; - return { - "object": true - }; + return {"object": true}; } // BSON Type: 4 function GenArray(seed) { @@ -647,9 +645,7 @@ function CollectionMetadataGenerator(options) { //"autoIndexId" : false // XXX: this doesn't exist in 2.4 }; // We need to explicitly enable usePowerOf2Sizes, since it's the default in 2.6 but not in 2.4 - var normalCollectionMetadata = { - "usePowerOf2Sizes": true - }; + var normalCollectionMetadata = {"usePowerOf2Sizes": true}; return { "get": function() { diff --git a/jstests/multiVersion/libs/dumprestore_helpers.js b/jstests/multiVersion/libs/dumprestore_helpers.js index 6ca7e3bd37f..bb552f855df 100644 --- a/jstests/multiVersion/libs/dumprestore_helpers.js +++ b/jstests/multiVersion/libs/dumprestore_helpers.js @@ -83,22 +83,20 @@ function multiVersionDumpRestoreTest(configObj) { // Dump using the specified version of mongodump from the running mongod or mongos instance. if (configObj.dumpType === "mongod") { - MongoRunner.runMongoTool("mongodump", - { - out: configObj.dumpDir, - binVersion: configObj.mongoDumpVersion, - host: serverSource.host, - db: testBaseName - }); + MongoRunner.runMongoTool("mongodump", { + out: configObj.dumpDir, + binVersion: configObj.mongoDumpVersion, + host: serverSource.host, + db: testBaseName + }); MongoRunner.stopMongod(serverSource.port); } else { /* "mongos" */ - MongoRunner.runMongoTool("mongodump", - { - out: configObj.dumpDir, - binVersion: configObj.mongoDumpVersion, - host: serverSource.host, - db: testBaseName - }); + MongoRunner.runMongoTool("mongodump", { + out: configObj.dumpDir, + binVersion: configObj.mongoDumpVersion, + host: serverSource.host, + db: testBaseName + }); shardingTest.stop(); } @@ -106,13 +104,12 @@ function multiVersionDumpRestoreTest(configObj) { if (configObj.restoreType === "mongod") { var serverDest = MongoRunner.runMongod({binVersion: configObj.serverDestVersion}); - MongoRunner.runMongoTool("mongorestore", - { - dir: configObj.dumpDir + "/" + testBaseName, - binVersion: configObj.mongoRestoreVersion, - host: serverDest.host, - db: testBaseName - }); + MongoRunner.runMongoTool("mongorestore", { + dir: configObj.dumpDir + "/" + testBaseName, + binVersion: configObj.mongoRestoreVersion, + host: serverDest.host, + db: testBaseName + }); } else { /* "mongos" */ var shardingTestConfig = { name: testBaseName + "_sharded_dest", @@ -124,13 +121,12 @@ function multiVersionDumpRestoreTest(configObj) { }; var shardingTest = new ShardingTest(shardingTestConfig); serverDest = shardingTest.s; - MongoRunner.runMongoTool("mongorestore", - { - dir: configObj.dumpDir + "/" + testBaseName, - binVersion: configObj.mongoRestoreVersion, - host: serverDest.host, - db: testBaseName - }); + MongoRunner.runMongoTool("mongorestore", { + dir: configObj.dumpDir + "/" + testBaseName, + binVersion: configObj.mongoRestoreVersion, + host: serverDest.host, + db: testBaseName + }); } var destDB = serverDest.getDB(testBaseName); diff --git a/jstests/multiVersion/minor_version_tags_new_old_new.js b/jstests/multiVersion/minor_version_tags_new_old_new.js index f39b3da4c68..c0fd26343cd 100644 --- a/jstests/multiVersion/minor_version_tags_new_old_new.js +++ b/jstests/multiVersion/minor_version_tags_new_old_new.js @@ -109,9 +109,7 @@ replTest.waitForState(replTest.nodes[nodeId], ReplSetTest.State.PRIMARY, 60 * 1000); primary = replTest.getPrimary(); primary.forceWriteMode('commands'); - var writeConcern = { - writeConcern: {w: expectedWritableNodes, wtimeout: 30 * 1000} - }; + var writeConcern = {writeConcern: {w: expectedWritableNodes, wtimeout: 30 * 1000}}; assert.writeOK(primary.getDB('foo').bar.insert({x: 100}, writeConcern)); return primary; }; @@ -136,9 +134,7 @@ jsTestLog('partitions: nodes with each set of brackets [N1, N2, N3] form a complete network.'); jsTestLog('partitions: [0-1-2] [3] [4] (only nodes 0 and 1 can replicate from primary node 2'); - var doc = { - x: 1 - }; + var doc = {x: 1}; // This timeout should be shorter in duration than the server parameter maxSyncSourceLagSecs. // Some writes are expected to block for this 'timeout' duration before failing. @@ -151,9 +147,7 @@ primary = ensurePrimary(2, 3); jsTestLog('Non-existent write concern should be rejected.'); - options = { - writeConcern: {w: 'blahblah', wtimeout: timeout} - }; + options = {writeConcern: {w: 'blahblah', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); var result = assert.writeError(primary.getDB('foo').bar.insert(doc, options)); assert.neq(null, result.getWriteConcernError()); @@ -162,9 +156,7 @@ tojson(result.getWriteConcernError())); jsTestLog('Write concern "3 or 4" should fail - 3 and 4 are not connected to the primary.'); - var options = { - writeConcern: {w: '3 or 4', wtimeout: timeout} - }; + var options = {writeConcern: {w: '3 or 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); result = primary.getDB('foo').bar.insert(doc, options); assert.neq(null, result.getWriteConcernError()); @@ -177,16 +169,12 @@ jsTestLog('Write concern "3 or 4" should work - 4 is now connected to the primary ' + primary.host + ' via node 1 ' + replTest.nodes[1].host); - options = { - writeConcern: {w: '3 or 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 or 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "3 and 4" should fail - 3 is not connected to the primary.'); - options = { - writeConcern: {w: '3 and 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 and 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); result = assert.writeError(primary.getDB('foo').bar.insert(doc, options)); assert.neq(null, result.getWriteConcernError()); @@ -201,31 +189,23 @@ jsTestLog('31003 should sync from 31004 (31024)'); jsTestLog('Write concern "3 and 4" should work - ' + 'nodes 3 and 4 are connected to primary via node 1.'); - options = { - writeConcern: {w: '3 and 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 and 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "2" - writes to primary only.'); - options = { - writeConcern: {w: '2', wtimeout: 0} - }; + options = {writeConcern: {w: '2', wtimeout: 0}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "1 and 2"'); - options = { - writeConcern: {w: '1 and 2', wtimeout: 0} - }; + options = {writeConcern: {w: '1 and 2', wtimeout: 0}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "2 dc and 3 server"'); primary = ensurePrimary(2, 5); - options = { - writeConcern: {w: '2 dc and 3 server', wtimeout: timeout} - }; + options = {writeConcern: {w: '2 dc and 3 server', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); @@ -250,17 +230,13 @@ primary = ensurePrimary(1, 4); jsTestLog('Write concern "3 and 4" should still work with new primary node 1 ' + primary.host); - options = { - writeConcern: {w: '3 and 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 and 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "2" should fail because node 2 ' + replTest.nodes[2].host + ' is down.'); - options = { - writeConcern: {w: '2', wtimeout: timeout} - }; + options = {writeConcern: {w: '2', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); result = assert.writeError(primary.getDB('foo').bar.insert(doc, options)); assert.neq(null, result.getWriteConcernError()); diff --git a/jstests/multiVersion/minor_version_tags_old_new_old.js b/jstests/multiVersion/minor_version_tags_old_new_old.js index 056aab2972a..1c3097da061 100644 --- a/jstests/multiVersion/minor_version_tags_old_new_old.js +++ b/jstests/multiVersion/minor_version_tags_old_new_old.js @@ -109,9 +109,7 @@ replTest.waitForState(replTest.nodes[nodeId], ReplSetTest.State.PRIMARY, 60 * 1000); primary = replTest.getPrimary(); primary.forceWriteMode('commands'); - var writeConcern = { - writeConcern: {w: expectedWritableNodes, wtimeout: 30 * 1000} - }; + var writeConcern = {writeConcern: {w: expectedWritableNodes, wtimeout: 30 * 1000}}; assert.writeOK(primary.getDB('foo').bar.insert({x: 100}, writeConcern)); return primary; }; @@ -136,9 +134,7 @@ jsTestLog('partitions: nodes with each set of brackets [N1, N2, N3] form a complete network.'); jsTestLog('partitions: [0-1-2] [3] [4] (only nodes 0 and 1 can replicate from primary node 2'); - var doc = { - x: 1 - }; + var doc = {x: 1}; // This timeout should be shorter in duration than the server parameter maxSyncSourceLagSecs. // Some writes are expected to block for this 'timeout' duration before failing. @@ -151,9 +147,7 @@ primary = ensurePrimary(2, 3); jsTestLog('Non-existent write concern should be rejected.'); - options = { - writeConcern: {w: 'blahblah', wtimeout: timeout} - }; + options = {writeConcern: {w: 'blahblah', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); var result = assert.writeError(primary.getDB('foo').bar.insert(doc, options)); assert.neq(null, result.getWriteConcernError()); @@ -162,9 +156,7 @@ tojson(result.getWriteConcernError())); jsTestLog('Write concern "3 or 4" should fail - 3 and 4 are not connected to the primary.'); - var options = { - writeConcern: {w: '3 or 4', wtimeout: timeout} - }; + var options = {writeConcern: {w: '3 or 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); result = primary.getDB('foo').bar.insert(doc, options); assert.neq(null, result.getWriteConcernError()); @@ -177,16 +169,12 @@ jsTestLog('Write concern "3 or 4" should work - 4 is now connected to the primary ' + primary.host + ' via node 1 ' + replTest.nodes[1].host); - options = { - writeConcern: {w: '3 or 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 or 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "3 and 4" should fail - 3 is not connected to the primary.'); - options = { - writeConcern: {w: '3 and 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 and 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); result = assert.writeError(primary.getDB('foo').bar.insert(doc, options)); assert.neq(null, result.getWriteConcernError()); @@ -201,31 +189,23 @@ jsTestLog('31003 should sync from 31004 (31024)'); jsTestLog('Write concern "3 and 4" should work - ' + 'nodes 3 and 4 are connected to primary via node 1.'); - options = { - writeConcern: {w: '3 and 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 and 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "2" - writes to primary only.'); - options = { - writeConcern: {w: '2', wtimeout: 0} - }; + options = {writeConcern: {w: '2', wtimeout: 0}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "1 and 2"'); - options = { - writeConcern: {w: '1 and 2', wtimeout: 0} - }; + options = {writeConcern: {w: '1 and 2', wtimeout: 0}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "2 dc and 3 server"'); primary = ensurePrimary(2, 5); - options = { - writeConcern: {w: '2 dc and 3 server', wtimeout: timeout} - }; + options = {writeConcern: {w: '2 dc and 3 server', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); @@ -250,17 +230,13 @@ primary = ensurePrimary(1, 4); jsTestLog('Write concern "3 and 4" should still work with new primary node 1 ' + primary.host); - options = { - writeConcern: {w: '3 and 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 and 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "2" should fail because node 2 ' + replTest.nodes[2].host + ' is down.'); - options = { - writeConcern: {w: '2', wtimeout: timeout} - }; + options = {writeConcern: {w: '2', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); result = assert.writeError(primary.getDB('foo').bar.insert(doc, options)); assert.neq(null, result.getWriteConcernError()); diff --git a/jstests/multiVersion/mixed_storage_version_replication.js b/jstests/multiVersion/mixed_storage_version_replication.js index 58c75803b4e..0973fbd85ff 100644 --- a/jstests/multiVersion/mixed_storage_version_replication.js +++ b/jstests/multiVersion/mixed_storage_version_replication.js @@ -211,9 +211,7 @@ var RandomOps = { } var field = this.randomChoice(this.fieldNames); - var updateDoc = { - $set: {} - }; + var updateDoc = {$set: {}}; updateDoc.$set[field] = this.randomChoice(this.fieldValues); if (this.verbose) { print("Updating:"); @@ -432,9 +430,8 @@ var RandomOps = { if (this.verbose) { print("Converting " + coll.getFullName() + " to a capped collection."); } - assert.commandWorked( - conn.getDB(coll.getDB()) - .runCommand({convertToCapped: coll.getName(), size: 1024 * 1024})); + assert.commandWorked(conn.getDB(coll.getDB()) + .runCommand({convertToCapped: coll.getName(), size: 1024 * 1024})); if (this.verbose) { print("done."); } @@ -671,18 +668,14 @@ function doMultiThreadedWork(primary, numThreads) { nodes["n" + node] = setups[i]; node++; } - nodes["n" + 2 * setups.length] = { - arbiter: true - }; + nodes["n" + 2 * setups.length] = {arbiter: true}; var replTest = new ReplSetTest({nodes: nodes, name: name}); var conns = replTest.startSet(); var config = replTest.getReplSetConfig(); // Make sure everyone is syncing from the primary, to ensure we have all combinations of // primary/secondary syncing. - config.settings = { - chainingAllowed: false - }; + config.settings = {chainingAllowed: false}; config.protocolVersion = 0; replTest.initiate(config); // Ensure all are synced. diff --git a/jstests/multiVersion/partial_index_upgrade.js b/jstests/multiVersion/partial_index_upgrade.js index 474252b4dc8..b19631ae3b3 100644 --- a/jstests/multiVersion/partial_index_upgrade.js +++ b/jstests/multiVersion/partial_index_upgrade.js @@ -58,7 +58,10 @@ // The secondary should terminate when the command to build an invalid partial index replicates. testCases.forEach(function(indexOptions) { var replSetName = 'partial_index_replset'; - var nodes = [{binVersion: '3.0'}, {binVersion: 'latest'}, ]; + var nodes = [ + {binVersion: '3.0'}, + {binVersion: 'latest'}, + ]; var rst = new ReplSetTest({name: replSetName, nodes: nodes}); diff --git a/jstests/multiVersion/transitioning_to_and_from_WT.js b/jstests/multiVersion/transitioning_to_and_from_WT.js index 97ac9b7af74..f51e21a2ef9 100644 --- a/jstests/multiVersion/transitioning_to_and_from_WT.js +++ b/jstests/multiVersion/transitioning_to_and_from_WT.js @@ -7,11 +7,10 @@ jsTestLog("Setting up initial data set with the last stable version of mongod"); - var toolTest = new ToolTest('transitioning_to_and_from_WT', - { - binVersion: MongoRunner.getBinVersionFor("last-stable"), - storageEngine: "mmapv1", - }); + var toolTest = new ToolTest('transitioning_to_and_from_WT', { + binVersion: MongoRunner.getBinVersionFor("last-stable"), + storageEngine: "mmapv1", + }); toolTest.dbpath = toolTest.root + "/original/"; resetDbpath(toolTest.dbpath); diff --git a/jstests/multiVersion/upgrade_cluster.js b/jstests/multiVersion/upgrade_cluster.js index a7703d8c30d..033df67611e 100644 --- a/jstests/multiVersion/upgrade_cluster.js +++ b/jstests/multiVersion/upgrade_cluster.js @@ -32,8 +32,8 @@ load('./jstests/multiVersion/libs/multi_cluster.js'); var unshardedDB = mongos.getDB('unshareded'); assert.commandWorked(unshardedDB.runCommand({insert: 'foo', documents: [{x: 1}]})); - assert.commandWorked(unshardedDB.runCommand( - {update: 'foo', updates: [{q: {x: 1}, u: {$set: {y: 1}}}]})); + assert.commandWorked( + unshardedDB.runCommand({update: 'foo', updates: [{q: {x: 1}, u: {$set: {y: 1}}}]})); var doc = unshardedDB.foo.findOne({x: 1}); assert.eq(1, doc.y); assert.commandWorked( diff --git a/jstests/multiVersion/wt_index_option_defaults_replset.js b/jstests/multiVersion/wt_index_option_defaults_replset.js index 9156d0b06ae..af17bd182b8 100644 --- a/jstests/multiVersion/wt_index_option_defaults_replset.js +++ b/jstests/multiVersion/wt_index_option_defaults_replset.js @@ -32,9 +32,7 @@ var secondary30 = conns[1].getDB('test'); // Create a collection with "indexOptionDefaults" specified. - var indexOptions = { - storageEngine: {wiredTiger: {configString: 'prefix_compression=false'}} - }; + var indexOptions = {storageEngine: {wiredTiger: {configString: 'prefix_compression=false'}}}; assert.commandWorked(primary32.runCommand({create: 'coll', indexOptionDefaults: indexOptions})); // Verify that the "indexOptionDefaults" field is present in the corresponding oplog entry. @@ -90,9 +88,7 @@ var secondary32 = conns[1].getDB('test'); // Create a collection with "indexOptionDefaults" specified. - var indexOptions = { - storageEngine: {wiredTiger: {configString: 'prefix_compression=false'}} - }; + var indexOptions = {storageEngine: {wiredTiger: {configString: 'prefix_compression=false'}}}; assert.commandWorked(primary30.runCommand({create: 'coll', indexOptionDefaults: indexOptions})); // Verify that the "indexOptionDefaults" field is present in the corresponding oplog entry. diff --git a/jstests/noPassthrough/backup_restore.js b/jstests/noPassthrough/backup_restore.js index 2a896dcb2c7..3e15e2b114b 100644 --- a/jstests/noPassthrough/backup_restore.js +++ b/jstests/noPassthrough/backup_restore.js @@ -229,12 +229,8 @@ rst.waitForState(rst.getSecondaries(), ReplSetTest.State.SECONDARY, 60 * 1000); // Add new hidden node to replSetTest - var hiddenCfg = { - restart: true, - oplogSize: 1024, - dbpath: hiddenDbpath, - replSet: replSetName - }; + var hiddenCfg = + {restart: true, oplogSize: 1024, dbpath: hiddenDbpath, replSet: replSetName}; rst.add(hiddenCfg); var hiddenHost = rst.nodes[numNodes].host; @@ -257,12 +253,7 @@ // Add new hidden secondary to replica set var rsConfig = primary.getDB("local").system.replset.findOne(); rsConfig.version += 1; - var hiddenMember = { - _id: numNodes, - host: hiddenHost, - priority: 0, - hidden: true - }; + var hiddenMember = {_id: numNodes, host: hiddenHost, priority: 0, hidden: true}; rsConfig.members.push(hiddenMember); assert.commandWorked(primary.adminCommand({replSetReconfig: rsConfig}), testName + ' failed to reconfigure replSet ' + tojson(rsConfig)); diff --git a/jstests/noPassthrough/commands_handle_kill.js b/jstests/noPassthrough/commands_handle_kill.js index b7ad6ea1bea..d2aedb8f4ea 100644 --- a/jstests/noPassthrough/commands_handle_kill.js +++ b/jstests/noPassthrough/commands_handle_kill.js @@ -70,12 +70,8 @@ // group command errors if plan executor is killed. res = db.runCommand({ - group: { - ns: coll.getFullName(), - key: "_id", - $reduce: function(curr, result) {}, - initial: {} - } + group: + {ns: coll.getFullName(), key: "_id", $reduce: function(curr, result) {}, initial: {}} }); assert.commandFailed(res); assert(res.errmsg.indexOf("hit planExecutorAlwaysDead fail point") > -1); diff --git a/jstests/noPassthrough/count_helper_read_preference.js b/jstests/noPassthrough/count_helper_read_preference.js index a049e586598..b07621f3498 100644 --- a/jstests/noPassthrough/count_helper_read_preference.js +++ b/jstests/noPassthrough/count_helper_read_preference.js @@ -10,10 +10,7 @@ MockMongo.prototype = Mongo.prototype; MockMongo.prototype.runCommand = function(db, cmd, opts) { commandsRan.push({db: db, cmd: cmd, opts: opts}); - return { - ok: 1, - n: 100 - }; + return {ok: 1, n: 100}; }; var db = new DB(new MockMongo(), "test"); diff --git a/jstests/noPassthrough/currentop_query.js b/jstests/noPassthrough/currentop_query.js index deb470666af..b72da385564 100644 --- a/jstests/noPassthrough/currentop_query.js +++ b/jstests/noPassthrough/currentop_query.js @@ -47,9 +47,7 @@ testObj.currentOpFilter.ns = coll.getFullName(); testObj.currentOpFilter.planSummary = testObj.planSummary; if (testObj.hasOwnProperty("command")) { - testObj.currentOpFilter["query." + testObj.command] = { - $exists: true - }; + testObj.currentOpFilter["query." + testObj.command] = {$exists: true}; } else if (testObj.hasOwnProperty("operation")) { testObj.currentOpFilter.op = testObj.operation; } @@ -132,7 +130,7 @@ reduce: function() {}, initial: {} }), - [{"a": 1}]); + [{"a": 1}]); }, command: "group", planSummary: "COLLSCAN", diff --git a/jstests/noPassthrough/cursor_timeout.js b/jstests/noPassthrough/cursor_timeout.js index f74521b9bc9..46a054da0ea 100644 --- a/jstests/noPassthrough/cursor_timeout.js +++ b/jstests/noPassthrough/cursor_timeout.js @@ -39,12 +39,7 @@ for (x = 0; x < 200; x++) { var chunkDoc = configDB.chunks.findOne(); var chunkOwner = chunkDoc.shard; var toShard = configDB.shards.findOne({_id: {$ne: chunkOwner}})._id; -var cmd = { - moveChunk: coll.getFullName(), - find: chunkDoc.min, - to: toShard, - _waitForDelete: true -}; +var cmd = {moveChunk: coll.getFullName(), find: chunkDoc.min, to: toShard, _waitForDelete: true}; var res = adminDB.runCommand(cmd); jsTest.log('move result: ' + tojson(res)); diff --git a/jstests/noPassthrough/exit_logging.js b/jstests/noPassthrough/exit_logging.js index 0647f312cc4..f996766866f 100644 --- a/jstests/noPassthrough/exit_logging.js +++ b/jstests/noPassthrough/exit_logging.js @@ -25,23 +25,23 @@ function checkOutput() { var logContents = ""; - assert.soon(() => - { - logContents = rawMongoProgramOutput(); - return matchFn(logContents); - }, - function() { - // We can't just return a string because it will be well over the max - // line length. - // So we just print manually. - print("================ BEGIN LOG CONTENTS =================="); - logContents.split(/\n/).forEach((line) => { - print(line); - }); - print("================ END LOG CONTENTS ====================="); - return ""; - }, - 30000); + assert.soon( + () => { + logContents = rawMongoProgramOutput(); + return matchFn(logContents); + }, + function() { + // We can't just return a string because it will be well over the max + // line length. + // So we just print manually. + print("================ BEGIN LOG CONTENTS =================="); + logContents.split(/\n/).forEach((line) => { + print(line); + }); + print("================ END LOG CONTENTS ====================="); + return ""; + }, + 30000); } try { @@ -55,12 +55,9 @@ function runAllTests(launcher) { const SIGSEGV = 11; const SIGABRT = 6; - testShutdownLogging(launcher, - function(conn) { - conn.getDB('admin').shutdownServer(); - }, - makeRegExMatchFn(/shutdown command received/), - MongoRunner.EXIT_CLEAN); + testShutdownLogging(launcher, function(conn) { + conn.getDB('admin').shutdownServer(); + }, makeRegExMatchFn(/shutdown command received/), MongoRunner.EXIT_CLEAN); testShutdownLogging(launcher, makeShutdownByCrashFn('fault'), @@ -88,9 +85,7 @@ runAllTests({ start: function(opts) { - var actualOpts = { - nojournal: "" - }; + var actualOpts = {nojournal: ""}; Object.extend(actualOpts, opts); return MongoRunner.runMongod(actualOpts); }, @@ -105,9 +100,7 @@ var st = new ShardingTest({shards: 1, other: {shardOptions: {nojournal: ""}}}); var mongosLauncher = { start: function(opts) { - var actualOpts = { - configdb: st._configDB - }; + var actualOpts = {configdb: st._configDB}; Object.extend(actualOpts, opts); return MongoRunner.runMongos(actualOpts); }, diff --git a/jstests/noPassthrough/ftdc_setparam.js b/jstests/noPassthrough/ftdc_setparam.js index 73e3f8720a6..d4cf4029426 100644 --- a/jstests/noPassthrough/ftdc_setparam.js +++ b/jstests/noPassthrough/ftdc_setparam.js @@ -7,9 +7,7 @@ // Check the defaults are correct // function getparam(field) { - var q = { - getParameter: 1 - }; + var q = {getParameter: 1}; q[field] = 1; var ret = m.getDB("admin").runCommand(q); diff --git a/jstests/noPassthrough/geo_full.js b/jstests/noPassthrough/geo_full.js index 505a0efab33..491229233f5 100644 --- a/jstests/noPassthrough/geo_full.js +++ b/jstests/noPassthrough/geo_full.js @@ -46,13 +46,7 @@ var randEnvironment = function() { var range = max - min; var bucketSize = range / (4 * 1024 * 1024 * 1024); - return { - max: max, - min: min, - bits: bits, - earth: false, - bucketSize: bucketSize - }; + return {max: max, min: min, bits: bits, earth: false, bucketSize: bucketSize}; }; var randPoint = function(env, query) { @@ -107,10 +101,7 @@ var randDataType = function() { maxLocs = Math.floor(Random.rand() * locScale) + 1; } - return { - numDocs: numDocs, - maxLocs: maxLocs - }; + return {numDocs: numDocs, maxLocs: maxLocs}; }; function deg2rad(arg) { @@ -241,22 +232,13 @@ var queryResults = function(locs, query, results) { if (!results["center"]) { for (var type in resultTypes) { - results[type] = { - docsIn: 0, - docsOut: 0, - locsIn: 0, - locsOut: 0 - }; + results[type] = {docsIn: 0, docsOut: 0, locsIn: 0, locsOut: 0}; } } var indResults = {}; for (var type in resultTypes) { - indResults[type] = { - docIn: false, - locsIn: 0, - locsOut: 0 - }; + indResults[type] = {docIn: false, locsIn: 0, locsOut: 0}; } for (var type in resultTypes) { @@ -313,29 +295,19 @@ var randYesQuery = function() { var choice = Math.floor(Random.rand() * 7); if (choice == 0) - return { - $ne: "no" - }; + return {$ne: "no"}; else if (choice == 1) return "yes"; else if (choice == 2) return /^yes/; else if (choice == 3) - return { - $in: ["good", "yes", "ok"] - }; + return {$in: ["good", "yes", "ok"]}; else if (choice == 4) - return { - $exists: true - }; + return {$exists: true}; else if (choice == 5) - return { - $nin: ["bad", "no", "not ok"] - }; + return {$nin: ["bad", "no", "not ok"]}; else if (choice == 6) - return { - $not: /^no/ - }; + return {$not: /^no/}; }; var locArray = function(loc) { @@ -423,13 +395,9 @@ for (var test = 0; test < numTests; test++) { var doc; // Nest the keys differently if (Random.rand() < 0.5) - doc = { - locs: {loc: randLocTypes(multiPoint)} - }; + doc = {locs: {loc: randLocTypes(multiPoint)}}; else - doc = { - locs: randLocTypes(multiPoint, "loc") - }; + doc = {locs: randLocTypes(multiPoint, "loc")}; randQueryAdditions(doc, indResults); @@ -438,9 +406,7 @@ for (var test = 0; test < numTests; test++) { } assert.writeOK(bulk.execute()); - var indexDoc = { - "locs.loc": "2d" - }; + var indexDoc = {"locs.loc": "2d"}; randIndexAdditions(indexDoc); t.ensureIndex(indexDoc, env); assert.isnull(db.getLastError()); @@ -472,19 +438,18 @@ for (var test = 0; test < numTests; test++) { print("Min box : " + minBoxSize(env, query.radius)); assert.eq(results.center.docsIn, t.find({ - "locs.loc": {$within: {$center: [query.center, query.radius], $uniqueDocs: 1}}, - "center.docIn": randYesQuery() - }).count()); + "locs.loc": {$within: {$center: [query.center, query.radius], $uniqueDocs: 1}}, + "center.docIn": randYesQuery() + }).count()); print("Center query update..."); - var res = t.update( - { - "locs.loc": {$within: {$center: [query.center, query.radius], $uniqueDocs: true}}, - "center.docIn": randYesQuery() - }, - {$set: {centerPaddingA: padding}}, - false, - true); + var res = t.update({ + "locs.loc": {$within: {$center: [query.center, query.radius], $uniqueDocs: true}}, + "center.docIn": randYesQuery() + }, + {$set: {centerPaddingA: padding}}, + false, + true); assert.eq(results.center.docsIn, res.nModified); if (query.sphereRadius >= 0) { @@ -493,41 +458,37 @@ for (var test = 0; test < numTests; test++) { assert.eq( results.sphere.docsIn, t.find({ - "locs.loc": {$within: {$centerSphere: [query.sphereCenter, query.sphereRadius]}}, - "sphere.docIn": randYesQuery() - }).count()); + "locs.loc": {$within: {$centerSphere: [query.sphereCenter, query.sphereRadius]}}, + "sphere.docIn": randYesQuery() + }).count()); print("Center sphere query update..."); - res = t.update( - { - "locs.loc": { - $within: { - $centerSphere: [query.sphereCenter, query.sphereRadius], - $uniqueDocs: true - } - }, - "sphere.docIn": randYesQuery() + res = t.update({ + "locs.loc": { + $within: + {$centerSphere: [query.sphereCenter, query.sphereRadius], $uniqueDocs: true} }, - {$set: {spherePaddingA: padding}}, - false, - true); + "sphere.docIn": randYesQuery() + }, + {$set: {spherePaddingA: padding}}, + false, + true); assert.eq(results.sphere.docsIn, res.nModified); } // $box print("Box query..."); - assert.eq(results.box.docsIn, - t.find({ - "locs.loc": {$within: {$box: query.box, $uniqueDocs: true}}, - "box.docIn": randYesQuery() - }).count()); + assert.eq(results.box.docsIn, t.find({ + "locs.loc": {$within: {$box: query.box, $uniqueDocs: true}}, + "box.docIn": randYesQuery() + }).count()); // $polygon print("Polygon query..."); - assert.eq( - results.poly.docsIn, - t.find({"locs.loc": {$within: {$polygon: query.boxPoly}}, "poly.docIn": randYesQuery()}) - .count()); + assert.eq(results.poly.docsIn, t.find({ + "locs.loc": {$within: {$polygon: query.boxPoly}}, + "poly.docIn": randYesQuery() + }).count()); var defaultDocLimit = 100; @@ -544,8 +505,8 @@ for (var test = 0; test < numTests; test++) { assert.eq( results.sphere.docsIn, t.find({ - "locs.loc": {$nearSphere: query.sphereCenter, $maxDistance: query.sphereRadius} - }).count(true), + "locs.loc": {$nearSphere: query.sphereCenter, $maxDistance: query.sphereRadius} + }).count(true), "Near sphere query: sphere center: " + query.sphereCenter + "; radius: " + query.sphereRadius + "; docs: " + results.sphere.docsIn + "; locs: " + results.sphere.locsIn); @@ -568,12 +529,12 @@ for (var test = 0; test < numTests; test++) { var num = Math.min(2 * defaultDocLimit, 2 * results.center.docsIn); var output = db.runCommand({ - geoNear: "testAllGeo", - near: query.center, - maxDistance: query.radius, - includeLocs: true, - num: num - }).results; + geoNear: "testAllGeo", + near: query.center, + maxDistance: query.radius, + includeLocs: true, + num: num + }).results; assert.eq(Math.min(num, results.center.docsIn), output.length, diff --git a/jstests/noPassthrough/geo_mnypts_plus_fields.js b/jstests/noPassthrough/geo_mnypts_plus_fields.js index 801c7dcfc8b..eb8a03ce739 100644 --- a/jstests/noPassthrough/geo_mnypts_plus_fields.js +++ b/jstests/noPassthrough/geo_mnypts_plus_fields.js @@ -17,9 +17,7 @@ for (var fields = 1; fields < maxFields; fields++) { for (var i = 0; i < totalPts; i++) { var ii = i % 10000; - var doc = { - loc: [ii % 100, Math.floor(ii / 100)] - }; + var doc = {loc: [ii % 100, Math.floor(ii / 100)]}; // Add fields with different kinds of data for (var j = 0; j < fields; j++) { @@ -49,9 +47,7 @@ for (var fields = 1; fields < maxFields; fields++) { if (j % 3 == 0) { field = "abcdefg"; } else if (j % 3 == 1) { - field = { - $lte: new Date() - }; + field = {$lte: new Date()}; } else { field = true; } diff --git a/jstests/noPassthrough/initial_sync_cloner_dups.js b/jstests/noPassthrough/initial_sync_cloner_dups.js index dd0e05a8673..8967e94722c 100644 --- a/jstests/noPassthrough/initial_sync_cloner_dups.js +++ b/jstests/noPassthrough/initial_sync_cloner_dups.js @@ -100,10 +100,9 @@ // Removed the assertion because it was too flaky. Printing a warning instead (dan) jsTestLog("making sure we dropped some dups"); var res = secondary.adminCommand({getLog: "global"}); - var droppedDups = (contains(res.log, - function(v) { - return v.indexOf("index build dropped" /* NNN dups*/) != -1; - })); + var droppedDups = (contains(res.log, function(v) { + return v.indexOf("index build dropped" /* NNN dups*/) != -1; + })); if (!droppedDups) { jsTestLog( "Warning: Test did not trigger duplicate documents, this run will be a false negative"); diff --git a/jstests/noPassthrough/javascript_options.js b/jstests/noPassthrough/javascript_options.js index e0f1690bd5d..52cc641b274 100644 --- a/jstests/noPassthrough/javascript_options.js +++ b/jstests/noPassthrough/javascript_options.js @@ -3,9 +3,7 @@ var baseName = "jstests_nopassthrough_javascript_options"; load('jstests/libs/command_line/test_parsed_options.js'); jsTest.log("Testing \"noscripting\" command line option"); -var expectedResult = { - "parsed": {"security": {"javascriptEnabled": false}} -}; +var expectedResult = {"parsed": {"security": {"javascriptEnabled": false}}}; testGetCmdLineOptsMongod({noscripting: ""}, expectedResult); jsTest.log("Testing explicitly disabled \"noscripting\" config file option"); diff --git a/jstests/noPassthrough/js_protection.js b/jstests/noPassthrough/js_protection.js index 1299131289d..eda42395cd9 100644 --- a/jstests/noPassthrough/js_protection.js +++ b/jstests/noPassthrough/js_protection.js @@ -55,15 +55,14 @@ assert.neq(null, doc); assert.eq(0, doc.y, tojson(doc)); - res = t.update( - { - $where: function() { - return this.val === 0; - } - }, - {$set: {y: 100}}, - false, - true); + res = t.update({ + $where: function() { + return this.val === 0; + } + }, + {$set: {y: 100}}, + false, + true); assert.writeOK(res); doc = t.findOne({name: "testdoc"}); diff --git a/jstests/noPassthrough/lock_stats.js b/jstests/noPassthrough/lock_stats.js index 078a22ead2d..73a3027b33f 100644 --- a/jstests/noPassthrough/lock_stats.js +++ b/jstests/noPassthrough/lock_stats.js @@ -36,14 +36,10 @@ // The server was just started, so initial stats may be missing. if (!startStats.acquireWaitCount || !startStats.acquireWaitCount.W) { - startStats.acquireWaitCount = { - W: 0 - }; + startStats.acquireWaitCount = {W: 0}; } if (!startStats.timeAcquiringMicros || !startStats.timeAcquiringMicros.W) { - startStats.timeAcquiringMicros = { - W: 0 - }; + startStats.timeAcquiringMicros = {W: 0}; } var acquireWaitCount = endStats.acquireWaitCount.W - startStats.acquireWaitCount.W; diff --git a/jstests/noPassthrough/logging_options.js b/jstests/noPassthrough/logging_options.js index 794680fa937..238faa3c618 100644 --- a/jstests/noPassthrough/logging_options.js +++ b/jstests/noPassthrough/logging_options.js @@ -4,34 +4,24 @@ load('jstests/libs/command_line/test_parsed_options.js'); // Verbosity testing jsTest.log("Testing \"verbose\" command line option with no args"); -var expectedResult = { - "parsed": {"systemLog": {"verbosity": 1}} -}; +var expectedResult = {"parsed": {"systemLog": {"verbosity": 1}}}; testGetCmdLineOptsMongod({verbose: ""}, expectedResult); jsTest.log("Testing \"verbose\" command line option with one \"v\""); -var expectedResult = { - "parsed": {"systemLog": {"verbosity": 1}} -}; +var expectedResult = {"parsed": {"systemLog": {"verbosity": 1}}}; testGetCmdLineOptsMongod({verbose: "v"}, expectedResult); jsTest.log("Testing \"verbose\" command line option with two \"v\"s"); -var expectedResult = { - "parsed": {"systemLog": {"verbosity": 2}} -}; +var expectedResult = {"parsed": {"systemLog": {"verbosity": 2}}}; testGetCmdLineOptsMongod({verbose: "vv"}, expectedResult); jsTest.log("Testing \"v\" command line option"); -var expectedResult = { - "parsed": {"systemLog": {"verbosity": 1}} -}; +var expectedResult = {"parsed": {"systemLog": {"verbosity": 1}}}; // Currently the test converts "{ v : 1 }" to "-v" when it spawns the binary. testGetCmdLineOptsMongod({v: 1}, expectedResult); jsTest.log("Testing \"vv\" command line option"); -var expectedResult = { - "parsed": {"systemLog": {"verbosity": 2}} -}; +var expectedResult = {"parsed": {"systemLog": {"verbosity": 2}}}; // Currently the test converts "{ v : 2 }" to "-vv" when it spawns the binary. testGetCmdLineOptsMongod({v: 2}, expectedResult); diff --git a/jstests/noPassthrough/minvalid2.js b/jstests/noPassthrough/minvalid2.js index a9096805b66..2eb167444ad 100644 --- a/jstests/noPassthrough/minvalid2.js +++ b/jstests/noPassthrough/minvalid2.js @@ -55,9 +55,8 @@ printjson(lastOp); // Overwrite minvalid document to simulate an inconsistent state (as might result from a server // crash. -local.replset.minvalid.update({}, - {ts: new Timestamp(lastOp.ts.t, lastOp.ts.i + 1)}, - {upsert: true}); +local.replset.minvalid.update( + {}, {ts: new Timestamp(lastOp.ts.t, lastOp.ts.i + 1)}, {upsert: true}); printjson(local.replset.minvalid.findOne()); print("5: shut down master"); diff --git a/jstests/noPassthrough/parameters.js b/jstests/noPassthrough/parameters.js index a4fe35446b4..ddc5def5864 100644 --- a/jstests/noPassthrough/parameters.js +++ b/jstests/noPassthrough/parameters.js @@ -2,17 +2,13 @@ var dbConn = MongoRunner.runMongod(); function setAndCheckParameter(dbConn, parameterName, newValue, expectedResult) { jsTest.log("Test setting parameter: " + parameterName + " to value: " + newValue); - var getParameterCommand = { - getParameter: 1 - }; + var getParameterCommand = {getParameter: 1}; getParameterCommand[parameterName] = 1; var ret = dbConn.adminCommand(getParameterCommand); assert.eq(ret.ok, 1, tojson(ret)); oldValue = ret[parameterName]; - var setParameterCommand = { - setParameter: 1 - }; + var setParameterCommand = {setParameter: 1}; setParameterCommand[parameterName] = newValue; var ret = dbConn.adminCommand(setParameterCommand); assert.eq(ret.ok, 1, tojson(ret)); @@ -45,9 +41,7 @@ setAndCheckParameter(dbConn, "replMonitorMaxFailedChecks", -30); function ensureSetParameterFailure(dbConn, parameterName, newValue) { jsTest.log("Test setting parameter: " + parameterName + " to invalid value: " + newValue); - var setParameterCommand = { - setParameter: 1 - }; + var setParameterCommand = {setParameter: 1}; setParameterCommand[parameterName] = newValue; var ret = dbConn.adminCommand(setParameterCommand); assert.eq(ret.ok, 0, tojson(ret)); diff --git a/jstests/noPassthrough/profile_options.js b/jstests/noPassthrough/profile_options.js index 0e45391a7ef..e3f9c8bcc03 100644 --- a/jstests/noPassthrough/profile_options.js +++ b/jstests/noPassthrough/profile_options.js @@ -3,21 +3,15 @@ var baseName = "jstests_core_profile_options"; load('jstests/libs/command_line/test_parsed_options.js'); jsTest.log("Testing \"profile\" command line option with profiling off"); -var expectedResult = { - "parsed": {"operationProfiling": {"mode": "off"}} -}; +var expectedResult = {"parsed": {"operationProfiling": {"mode": "off"}}}; testGetCmdLineOptsMongod({profile: "0"}, expectedResult); jsTest.log("Testing \"profile\" command line option with profiling slow operations on"); -var expectedResult = { - "parsed": {"operationProfiling": {"mode": "slowOp"}} -}; +var expectedResult = {"parsed": {"operationProfiling": {"mode": "slowOp"}}}; testGetCmdLineOptsMongod({profile: "1"}, expectedResult); jsTest.log("Testing \"profile\" command line option with profiling all on"); -var expectedResult = { - "parsed": {"operationProfiling": {"mode": "all"}} -}; +var expectedResult = {"parsed": {"operationProfiling": {"mode": "all"}}}; testGetCmdLineOptsMongod({profile: "2"}, expectedResult); jsTest.log("Testing \"operationProfiling.mode\" config file option"); diff --git a/jstests/noPassthrough/read_committed_lookup.js b/jstests/noPassthrough/read_committed_lookup.js index e66195739ee..a8b3ff8522d 100644 --- a/jstests/noPassthrough/read_committed_lookup.js +++ b/jstests/noPassthrough/read_committed_lookup.js @@ -63,9 +63,7 @@ load("jstests/replsets/rslib.js"); // For startSetIfSupportsReadMajority. } // Seed matching data. - var majorityWriteConcernObj = { - writeConcern: {w: "majority", wtimeout: 60 * 1000} - }; + var majorityWriteConcernObj = {writeConcern: {w: "majority", wtimeout: 60 * 1000}}; var localId = db.local.insertOne({foreignKey: "x"}, majorityWriteConcernObj).insertedId; var foreignId = db.foreign.insertOne({matchedField: "x"}, majorityWriteConcernObj).insertedId; @@ -90,7 +88,9 @@ load("jstests/replsets/rslib.js"); // For startSetIfSupportsReadMajority. var expectedMatchedResult = [{ _id: localId, foreignKey: "x", - match: [{_id: foreignId, matchedField: "x"}, ], + match: [ + {_id: foreignId, matchedField: "x"}, + ], }]; var expectedUnmatchedResult = [{ _id: localId, diff --git a/jstests/noPassthrough/read_majority.js b/jstests/noPassthrough/read_majority.js index 3d84fce0911..c2b20df292a 100644 --- a/jstests/noPassthrough/read_majority.js +++ b/jstests/noPassthrough/read_majority.js @@ -28,8 +28,8 @@ load("jstests/libs/analyze_plan.js"); var t = db.readMajority; function assertNoReadMajoritySnapshotAvailable() { - var res = t.runCommand('find', - {batchSize: 2, readConcern: {level: "majority"}, maxTimeMS: 1000}); + var res = + t.runCommand('find', {batchSize: 2, readConcern: {level: "majority"}, maxTimeMS: 1000}); assert.commandFailed(res); assert.eq(res.code, ErrorCodes.ExceededTimeLimit); } diff --git a/jstests/noPassthrough/read_majority_reads.js b/jstests/noPassthrough/read_majority_reads.js index 5c169e3bed7..92a0032a2cd 100644 --- a/jstests/noPassthrough/read_majority_reads.js +++ b/jstests/noPassthrough/read_majority_reads.js @@ -86,12 +86,11 @@ }, geoNear: { run: function(coll) { - var res = coll.runCommand('geoNear', - { - readConcern: {level: 'majority'}, - near: [0, 0], - spherical: true, - }); + var res = coll.runCommand('geoNear', { + readConcern: {level: 'majority'}, + near: [0, 0], + spherical: true, + }); assert.commandWorked(res); assert.eq(res.results.length, 1, tojson(res)); return res.results[0].obj.state; @@ -101,13 +100,12 @@ }, geoSearch: { run: function(coll) { - var res = coll.runCommand('geoSearch', - { - readConcern: {level: 'majority'}, - near: [0, 0], - search: {_id: 1}, // Needed due to SERVER-23158. - maxDistance: 1, - }); + var res = coll.runCommand('geoSearch', { + readConcern: {level: 'majority'}, + near: [0, 0], + search: {_id: 1}, // Needed due to SERVER-23158. + maxDistance: 1, + }); assert.commandWorked(res); assert.eq(res.results.length, 1, tojson(res)); return res.results[0].state; diff --git a/jstests/noPassthrough/sync_write.js b/jstests/noPassthrough/sync_write.js index 04c654cff72..b2f2fa24a45 100644 --- a/jstests/noPassthrough/sync_write.js +++ b/jstests/noPassthrough/sync_write.js @@ -11,11 +11,7 @@ var dbpath = MongoRunner.dataPath + 'sync_write'; resetDbpath(dbpath); - var mongodArgs = { - dbpath: dbpath, - noCleanData: true, - journal: '' - }; + var mongodArgs = {dbpath: dbpath, noCleanData: true, journal: ''}; // Start a mongod. var conn = MongoRunner.runMongod(mongodArgs); diff --git a/jstests/noPassthrough/update_server-5552.js b/jstests/noPassthrough/update_server-5552.js index 146dd0dab31..453914d6b3d 100644 --- a/jstests/noPassthrough/update_server-5552.js +++ b/jstests/noPassthrough/update_server-5552.js @@ -16,16 +16,15 @@ assert.writeOK(bulk.execute()); join = startParallelShell( "while( db.foo.findOne( { _id : 0 } ).x == 1 ); db.foo.ensureIndex( { x : 1 } );"); -t.update( - { - $where: function() { - sleep(1); - return true; - } - }, - {$set: {x: 5}}, - false, - true); +t.update({ + $where: function() { + sleep(1); + return true; + } +}, + {$set: {x: 5}}, + false, + true); db.getLastError(); join(); diff --git a/jstests/noPassthrough/write_local.js b/jstests/noPassthrough/write_local.js index 019b8c437f7..0cfda86003f 100644 --- a/jstests/noPassthrough/write_local.js +++ b/jstests/noPassthrough/write_local.js @@ -3,9 +3,7 @@ 'use strict'; // Limit concurrent WiredTiger transactions to maximize locking issues, harmless for other SEs. - var options = { - verbose: 1 - }; + var options = {verbose: 1}; // Create a new single node replicaSet var replTest = diff --git a/jstests/noPassthrough/wt_index_option_defaults.js b/jstests/noPassthrough/wt_index_option_defaults.js index 2516cc28d24..8609666a14d 100644 --- a/jstests/noPassthrough/wt_index_option_defaults.js +++ b/jstests/noPassthrough/wt_index_option_defaults.js @@ -56,14 +56,13 @@ // Start a mongod with system-wide defaults for engine-specific index options. var conn = MongoRunner.runMongod({ dbpath: dbpath, - noCleanData: true, [engine + 'IndexConfigString']: systemWideConfigString, + noCleanData: true, + [engine + 'IndexConfigString']: systemWideConfigString, }); assert.neq(null, conn, 'mongod was unable to start up'); var testDB = conn.getDB('test'); - var cmdObj = { - create: 'coll' - }; + var cmdObj = {create: 'coll'}; // Apply collection-wide defaults for engine-specific index options if any were // specified. @@ -78,12 +77,10 @@ assert.commandWorked(testDB.coll.createIndex({a: 1}, {name: 'without_options'})); // Create an index that specifies engine-specific index options. - assert.commandWorked(testDB.coll.createIndex( - {b: 1}, - { - name: 'with_options', - storageEngine: {[engine]: {configString: indexSpecificConfigString}} - })); + assert.commandWorked(testDB.coll.createIndex({b: 1}, { + name: 'with_options', + storageEngine: {[engine]: {configString: indexSpecificConfigString}} + })); var collStats = testDB.runCommand({collStats: 'coll'}); assert.commandWorked(collStats); diff --git a/jstests/noPassthrough/wt_nojournal_repl.js b/jstests/noPassthrough/wt_nojournal_repl.js index b9c58a516db..8e25d5923f8 100644 --- a/jstests/noPassthrough/wt_nojournal_repl.js +++ b/jstests/noPassthrough/wt_nojournal_repl.js @@ -73,10 +73,9 @@ if (jsTest.options().storageEngine && jsTest.options().storageEngine !== "wiredT // Test that the restarted secondary did NOT do an initial sync by checking the log var res = secondary1.adminCommand({getLog: "global"}); - assert(!contains(res.log, - function(v) { - return v.indexOf("initial sync") != -1; - })); + assert(!contains(res.log, function(v) { + return v.indexOf("initial sync") != -1; + })); jsTestLog("check data is in both collections"); assert.eq(secondary1.getDB("test").foo.count(), 100); diff --git a/jstests/noPassthroughWithMongod/apply_ops_errors.js b/jstests/noPassthroughWithMongod/apply_ops_errors.js index 31353523810..d2f584af787 100644 --- a/jstests/noPassthroughWithMongod/apply_ops_errors.js +++ b/jstests/noPassthroughWithMongod/apply_ops_errors.js @@ -22,8 +22,11 @@ coll.ensureIndex({x: 1}, {unique: true}); coll.insert({_id: 1, x: "init"}); - var res = - db.runCommand({applyOps: [{op: "i", ns: coll.getFullName(), o: {_id: 2, x: "init"}}, ]}); + var res = db.runCommand({ + applyOps: [ + {op: "i", ns: coll.getFullName(), o: {_id: 2, x: "init"}}, + ] + }); assert.eq(1, res.applied); assert(res.code); diff --git a/jstests/noPassthroughWithMongod/bench_test_crud_commands.js b/jstests/noPassthroughWithMongod/bench_test_crud_commands.js index 14ee7d0fdb7..7bbafa4e931 100644 --- a/jstests/noPassthroughWithMongod/bench_test_crud_commands.js +++ b/jstests/noPassthroughWithMongod/bench_test_crud_commands.js @@ -7,9 +7,7 @@ assert.commandWorked(coll.getDB().createCollection(coll.getName())); function makeDocument(docSize) { - var doc = { - "fieldName": "" - }; + var doc = {"fieldName": ""}; var longString = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; while (Object.bsonsize(doc) < docSize) { if (Object.bsonsize(doc) < docSize - longString.length) { @@ -22,12 +20,7 @@ } function executeBenchRun(benchOps) { - var benchArgs = { - ops: benchOps, - parallel: 2, - seconds: 1, - host: db.getMongo().host - }; + var benchArgs = {ops: benchOps, parallel: 2, seconds: 1, host: db.getMongo().host}; if (jsTest.options().auth) { benchArgs['db'] = 'admin'; benchArgs['username'] = jsTest.options().adminUser; @@ -73,8 +66,8 @@ assert.writeOK(coll.insert({})); } - var res = executeBenchRun( - [{ns: coll.getFullName(), op: "findOne", query: {}, readCmd: readCmd}]); + var res = + executeBenchRun([{ns: coll.getFullName(), op: "findOne", query: {}, readCmd: readCmd}]); assert.gt(res.findOne, 0, tojson(res)); } diff --git a/jstests/noPassthroughWithMongod/clonecollection.js b/jstests/noPassthroughWithMongod/clonecollection.js index a3633a12e58..2f0ec45ad44 100644 --- a/jstests/noPassthroughWithMongod/clonecollection.js +++ b/jstests/noPassthroughWithMongod/clonecollection.js @@ -16,9 +16,8 @@ assert.eq(1000, t.a.find().count(), "A2"); t.a.drop(); -assert.commandWorked(t.cloneCollection("localhost:" + fromMongod.port, - "a", - {i: {$gte: 10, $lt: 20}})); +assert.commandWorked( + t.cloneCollection("localhost:" + fromMongod.port, "a", {i: {$gte: 10, $lt: 20}})); assert.eq(10, t.a.find().count(), "A3"); t.a.drop(); @@ -35,9 +34,8 @@ assert.eq(2, t.a.getIndexes().length, "expected index missing"); x = t.a.find({i: 50}).hint({i: 1}).explain("executionStats"); printjson(x); assert.eq(1, x.executionStats.nReturned, "verify 1"); -assert.eq(1, - t.a.find({i: 50}).hint({i: 1}).toArray().length, - "match length did not match expected"); +assert.eq( + 1, t.a.find({i: 50}).hint({i: 1}).toArray().length, "match length did not match expected"); // Check that capped-ness is preserved on clone f.a.drop(); diff --git a/jstests/noPassthroughWithMongod/commands_that_write_accept_wc_standalone.js b/jstests/noPassthroughWithMongod/commands_that_write_accept_wc_standalone.js index 20b6501c459..22617b681c2 100644 --- a/jstests/noPassthroughWithMongod/commands_that_write_accept_wc_standalone.js +++ b/jstests/noPassthroughWithMongod/commands_that_write_accept_wc_standalone.js @@ -82,9 +82,7 @@ }); }, reduce: function(key, values) { - return { - count: values.length - }; + return {count: values.length}; }, out: "foo" }, @@ -103,10 +101,7 @@ }); function testValidWriteConcern(cmd) { - cmd.req.writeConcern = { - w: 1, - j: true - }; + cmd.req.writeConcern = {w: 1, j: true}; jsTest.log("Testing " + tojson(cmd.req)); coll.drop(); diff --git a/jstests/noPassthroughWithMongod/create_indexes_shell_helper.js b/jstests/noPassthroughWithMongod/create_indexes_shell_helper.js index f9f9f7b9f06..bca0cd05f54 100644 --- a/jstests/noPassthroughWithMongod/create_indexes_shell_helper.js +++ b/jstests/noPassthroughWithMongod/create_indexes_shell_helper.js @@ -20,15 +20,11 @@ }, runCommand: function(db, cmd, opts) { commandsRan.push({db: db, cmd: cmd, opts: opts}); - return { - ok: 1.0 - }; + return {ok: 1.0}; }, insert: function(db, indexSpecs, opts) { insertsRan.push({db: db, indexSpecs: indexSpecs, opts: opts}); - return { - ok: 1.0 - }; + return {ok: 1.0}; }, getWriteConcern: function() { return null; diff --git a/jstests/noPassthroughWithMongod/external_sort_text_agg.js b/jstests/noPassthroughWithMongod/external_sort_text_agg.js index ecb843ae9e5..b08a7c79a44 100644 --- a/jstests/noPassthroughWithMongod/external_sort_text_agg.js +++ b/jstests/noPassthroughWithMongod/external_sort_text_agg.js @@ -8,12 +8,13 @@ for (i = 0; i < 100; i++) { } var score = t.find({$text: {$search: "asdf"}}, {score: {$meta: 'textScore'}}).next().score; -var res = t.aggregate([ - {$match: {$text: {$search: "asdf"}}}, - {$sort: {"_id": 1}}, - {$project: {string: "$text", score: {$meta: "textScore"}}} -], - {allowDiskUse: true}); +var res = t.aggregate( + [ + {$match: {$text: {$search: "asdf"}}}, + {$sort: {"_id": 1}}, + {$project: {string: "$text", score: {$meta: "textScore"}}} + ], + {allowDiskUse: true}); // we must use .next() rather than a $limit because a $limit will optimize away the external sort printjson(res.next()); assert.eq(res.next().score, score); diff --git a/jstests/noPassthroughWithMongod/ftdc_params.js b/jstests/noPassthroughWithMongod/ftdc_params.js index 5fae9e77c49..732af83f7d6 100644 --- a/jstests/noPassthroughWithMongod/ftdc_params.js +++ b/jstests/noPassthroughWithMongod/ftdc_params.js @@ -7,9 +7,7 @@ // Check the defaults are correct // function getparam(field) { - var q = { - getParameter: 1 - }; + var q = {getParameter: 1}; q[field] = 1; var ret = admin.runCommand(q); diff --git a/jstests/noPassthroughWithMongod/geo_axis_aligned.js b/jstests/noPassthroughWithMongod/geo_axis_aligned.js index 47c0369e5e0..5e08a6c1739 100644 --- a/jstests/noPassthroughWithMongod/geo_axis_aligned.js +++ b/jstests/noPassthroughWithMongod/geo_axis_aligned.js @@ -98,18 +98,17 @@ for (var b = 0; b < bits.length; b++) { assert.gte(a[k].dis, distance); } - r = t.find( - { - loc: { - $within: { - $box: [ - [center[j][0] - radius[i], center[j][1] - radius[i]], - [center[j][0] + radius[i], center[j][1] + radius[i]] - ] - } - } - }, - {_id: 1}); + r = t.find({ + loc: { + $within: { + $box: [ + [center[j][0] - radius[i], center[j][1] - radius[i]], + [center[j][0] + radius[i], center[j][1] + radius[i]] + ] + } + } + }, + {_id: 1}); assert.eq(9, r.count()); } } diff --git a/jstests/noPassthroughWithMongod/geo_polygon.js b/jstests/noPassthroughWithMongod/geo_polygon.js index 073ffdeb72d..d2b271c32d7 100644 --- a/jstests/noPassthroughWithMongod/geo_polygon.js +++ b/jstests/noPassthroughWithMongod/geo_polygon.js @@ -5,10 +5,7 @@ num = 0; var bulk = t.initializeUnorderedBulkOp(); for (x = -180; x < 180; x += .5) { for (y = -180; y < 180; y += .5) { - o = { - _id: num++, - loc: [x, y] - }; + o = {_id: num++, loc: [x, y]}; bulk.insert(o); } } @@ -27,8 +24,8 @@ for (var n = 0; n < numTests; n++) { assert.eq( num, t.find({ - loc: {"$within": {"$polygon": [[-180, -180], [-180, 180], [180, 180], [180, -180]]}} - }).count(), + loc: {"$within": {"$polygon": [[-180, -180], [-180, 180], [180, 180], [180, -180]]}} + }).count(), "Bounding Box Test"); assert.eq( @@ -44,15 +41,17 @@ for (var n = 0; n < numTests; n++) { // slope falls. assert.between( 341 - 18, - t.find({loc: {"$within": {"$polygon": [[0, 0], [0, 10], [10, 10], [10, 0], [5, 5]]}}}) - .count(), + t.find({ + loc: {"$within": {"$polygon": [[0, 0], [0, 10], [10, 10], [10, 0], [5, 5]]}} + }).count(), 341, "Square Missing Chunk Test", true); assert.between( 21 - 2, - t.find({loc: {"$within": {"$polygon": [[0, 0], [0, 2], [2, 2], [2, 0], [1, 1]]}}}) - .count(), + t.find({ + loc: {"$within": {"$polygon": [[0, 0], [0, 2], [2, 2], [2, 0], [1, 1]]}} + }).count(), 21, "Square Missing Chunk Test 2", true); diff --git a/jstests/noPassthroughWithMongod/index_check10.js b/jstests/noPassthroughWithMongod/index_check10.js index 30ed9c17eac..2816eecdb4b 100644 --- a/jstests/noPassthroughWithMongod/index_check10.js +++ b/jstests/noPassthroughWithMongod/index_check10.js @@ -69,9 +69,7 @@ function doIt() { for (var j = 0; j < Random.randInt(15); ++j) { vals.push(r()); } - spec[fields[i]] = { - $in: vals - }; + spec[fields[i]] = {$in: vals}; } } s = sort(); diff --git a/jstests/noPassthroughWithMongod/index_check9.js b/jstests/noPassthroughWithMongod/index_check9.js index a801b473a44..fe158efbdad 100644 --- a/jstests/noPassthroughWithMongod/index_check9.js +++ b/jstests/noPassthroughWithMongod/index_check9.js @@ -83,9 +83,7 @@ function doIt() { for (var j = 0; j < inLength; ++j) { vals.push(r(alphas[i])); } - spec[fields[i]] = { - $in: vals - }; + spec[fields[i]] = {$in: vals}; break; } case 2 /* equality */: { diff --git a/jstests/noPassthroughWithMongod/index_multi.js b/jstests/noPassthroughWithMongod/index_multi.js index 68004f27678..a09b20fee96 100644 --- a/jstests/noPassthroughWithMongod/index_multi.js +++ b/jstests/noPassthroughWithMongod/index_multi.js @@ -9,9 +9,7 @@ db.results.drop(); var bulk = coll.initializeUnorderedBulkOp(); print("Populate the collection with random data"); for (var i = 0; i < 1e4; i++) { - var doc = { - "_id": i - }; + var doc = {"_id": i}; for (var j = 0; j < 100; j++) { // Skip some of the fields @@ -89,9 +87,7 @@ for (var i = 0; i < 30; i++) { print("Do some sets and unsets"); bulk = coll.initializeUnorderedBulkOp(); for (i = 0; i < 1e4; i++) { - var criteria = { - _id: Random.randInt(1e5) - }; + var criteria = {_id: Random.randInt(1e5)}; var mod = {}; if (Random.rand() < .5) { mod['$set'] = {}; diff --git a/jstests/noPassthroughWithMongod/indexbg_drop.js b/jstests/noPassthroughWithMongod/indexbg_drop.js index df66d82aaeb..74722b0e631 100644 --- a/jstests/noPassthroughWithMongod/indexbg_drop.js +++ b/jstests/noPassthroughWithMongod/indexbg_drop.js @@ -39,10 +39,7 @@ var secondId = replTest.getNodeId(second); var masterDB = master.getDB(dbname); var secondDB = second.getDB(dbname); -var dc = { - dropIndexes: collection, - index: "i_1" -}; +var dc = {dropIndexes: collection, index: "i_1"}; // set up collections masterDB.dropDatabase(); diff --git a/jstests/noPassthroughWithMongod/indexbg_updates.js b/jstests/noPassthroughWithMongod/indexbg_updates.js index a660ffc6eeb..c3465f78047 100644 --- a/jstests/noPassthroughWithMongod/indexbg_updates.js +++ b/jstests/noPassthroughWithMongod/indexbg_updates.js @@ -15,10 +15,7 @@ var bulk = coll.initializeUnorderedBulkOp(); print("Populate the collection with random data"); for (var i = 0; i < numDocs; i++) { - var doc = { - "_id": i, - "field0": Random.rand() - }; + var doc = {"_id": i, "field0": Random.rand()}; bulk.insert(doc); } @@ -28,9 +25,7 @@ // field being actively indexed in the background bulk = coll.initializeUnorderedBulkOp(); for (i = 0; i < numDocs; i++) { - var criteria = { - "_id": 1000 - }; + var criteria = {"_id": 1000}; var mod = {}; if (Random.rand() < .8) { diff --git a/jstests/noPassthroughWithMongod/insertMulti.js b/jstests/noPassthroughWithMongod/insertMulti.js index e2a70307550..2d6fb3a9df4 100644 --- a/jstests/noPassthroughWithMongod/insertMulti.js +++ b/jstests/noPassthroughWithMongod/insertMulti.js @@ -4,9 +4,7 @@ "use strict"; function makeDocument(docSize) { - var doc = { - "fieldName": "" - }; + var doc = {"fieldName": ""}; var longString = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; while (Object.bsonsize(doc) < docSize) { if (Object.bsonsize(doc) < docSize - longString.length) { diff --git a/jstests/noPassthroughWithMongod/mr_writeconflict.js b/jstests/noPassthroughWithMongod/mr_writeconflict.js index baae608b59e..4afabfb0143 100644 --- a/jstests/noPassthroughWithMongod/mr_writeconflict.js +++ b/jstests/noPassthroughWithMongod/mr_writeconflict.js @@ -5,11 +5,7 @@ load('jstests/libs/parallelTester.js'); var makeDoc = function(keyLimit, valueLimit) { - return { - _id: ObjectId(), - key: Random.randInt(keyLimit), - value: Random.randInt(valueLimit) - }; + return {_id: ObjectId(), key: Random.randInt(keyLimit), value: Random.randInt(valueLimit)}; }; var main = function() { diff --git a/jstests/noPassthroughWithMongod/replReads.js b/jstests/noPassthroughWithMongod/replReads.js index 45e0a4d49a6..3010be8e80c 100644 --- a/jstests/noPassthroughWithMongod/replReads.js +++ b/jstests/noPassthroughWithMongod/replReads.js @@ -56,10 +56,7 @@ function testReadLoadBalancing(numReplicas) { connections.push(conn); } - var profileCriteria = { - op: 'query', - ns: 'test.foo' - }; + var profileCriteria = {op: 'query', ns: 'test.foo'}; for (var i = 0; i < secondaries.length; i++) { var profileCollection = secondaries[i].getDB('test').system.profile; diff --git a/jstests/noPassthroughWithMongod/rpc_protocols.js b/jstests/noPassthroughWithMongod/rpc_protocols.js index 7e33c3986d3..9650d57e421 100644 --- a/jstests/noPassthroughWithMongod/rpc_protocols.js +++ b/jstests/noPassthroughWithMongod/rpc_protocols.js @@ -4,10 +4,7 @@ // startup using the "--rpcProtocols" command line option, or at runtime using the // "setClientRPCProtocols" method on the Mongo object. -var RPC_PROTOCOLS = { - OP_QUERY: "opQueryOnly", - OP_COMMAND: "opCommandOnly" -}; +var RPC_PROTOCOLS = {OP_QUERY: "opQueryOnly", OP_COMMAND: "opCommandOnly"}; (function() { "use strict"; @@ -28,50 +25,43 @@ var RPC_PROTOCOLS = { } // Test that --rpcProtocols=opQueryOnly forces OP_QUERY commands. - runInShell( - RPC_PROTOCOLS.OP_QUERY, - function() { - assert(db.getMongo().getClientRPCProtocols() === "opQueryOnly"); - db.getSiblingDB("test").rpcProtocols.find().comment("opQueryCommandLine").itcount(); - }); + runInShell(RPC_PROTOCOLS.OP_QUERY, function() { + assert(db.getMongo().getClientRPCProtocols() === "opQueryOnly"); + db.getSiblingDB("test").rpcProtocols.find().comment("opQueryCommandLine").itcount(); + }); var profileDoc = db.system.profile.findOne({"query.comment": "opQueryCommandLine"}); assert(profileDoc !== null); assert.eq(profileDoc.protocol, "op_query"); // Test that --rpcProtocols=opCommandOnly forces OP_COMMAND commands. - runInShell( - RPC_PROTOCOLS.OP_COMMAND, - function() { - assert(db.getMongo().getClientRPCProtocols() === "opCommandOnly"); - db.getSiblingDB("test").rpcProtocols.find().comment("opCommandCommandLine").itcount(); - }); + runInShell(RPC_PROTOCOLS.OP_COMMAND, function() { + assert(db.getMongo().getClientRPCProtocols() === "opCommandOnly"); + db.getSiblingDB("test").rpcProtocols.find().comment("opCommandCommandLine").itcount(); + }); profileDoc = db.system.profile.findOne({"query.comment": "opCommandCommandLine"}); assert(profileDoc !== null); assert.eq(profileDoc.protocol, "op_command"); // Test that .setClientRPCProtocols("opQueryOnly") forces OP_QUERY commands. We start the shell // in OP_COMMAND only mode, then switch it to OP_QUERY mode at runtime. - runInShell(RPC_PROTOCOLS.OP_COMMAND, - function() { - assert(db.getMongo().getClientRPCProtocols() === "opCommandOnly"); - db.getMongo().setClientRPCProtocols("opQueryOnly"); - assert(db.getMongo().getClientRPCProtocols() === "opQueryOnly"); - db.getSiblingDB("test").rpcProtocols.find().comment("opQueryRuntime").itcount(); - }); + runInShell(RPC_PROTOCOLS.OP_COMMAND, function() { + assert(db.getMongo().getClientRPCProtocols() === "opCommandOnly"); + db.getMongo().setClientRPCProtocols("opQueryOnly"); + assert(db.getMongo().getClientRPCProtocols() === "opQueryOnly"); + db.getSiblingDB("test").rpcProtocols.find().comment("opQueryRuntime").itcount(); + }); profileDoc = db.system.profile.findOne({"query.comment": "opQueryRuntime"}); assert(profileDoc !== null); assert.eq(profileDoc.protocol, "op_query"); // Test that .setClientRPCProtocols("opCommandOnly") forces OP_COMMAND commands. We start the // shell in OP_QUERY only mode, then switch it to OP_COMMAND mode at runtime. - runInShell( - RPC_PROTOCOLS.OP_QUERY, - function() { - assert(db.getMongo().getClientRPCProtocols() === "opQueryOnly"); - db.getMongo().setClientRPCProtocols("opCommandOnly"); - assert(db.getMongo().getClientRPCProtocols() === "opCommandOnly"); - db.getSiblingDB("test").rpcProtocols.find().comment("opCommandRuntime").itcount(); - }); + runInShell(RPC_PROTOCOLS.OP_QUERY, function() { + assert(db.getMongo().getClientRPCProtocols() === "opQueryOnly"); + db.getMongo().setClientRPCProtocols("opCommandOnly"); + assert(db.getMongo().getClientRPCProtocols() === "opCommandOnly"); + db.getSiblingDB("test").rpcProtocols.find().comment("opCommandRuntime").itcount(); + }); profileDoc = db.system.profile.findOne({"query.comment": "opCommandRuntime"}); assert(profileDoc !== null); assert.eq(profileDoc.protocol, "op_command"); diff --git a/jstests/noPassthroughWithMongod/temp_namespace.js b/jstests/noPassthroughWithMongod/temp_namespace.js index a2f1aa21a80..d84dcb302f3 100644 --- a/jstests/noPassthroughWithMongod/temp_namespace.js +++ b/jstests/noPassthroughWithMongod/temp_namespace.js @@ -17,9 +17,11 @@ d.runCommand({create: testname + 'keep3'}); d[testname + 'keep4'].insert({}); function countCollectionNames(theDB, regex) { - return theDB.getCollectionNames().filter(function(z) { - return z.match(regex); - }).length; + return theDB.getCollectionNames() + .filter(function(z) { + return z.match(regex); + }) + .length; } assert.eq(countCollectionNames(d, /temp\d$/), 2); diff --git a/jstests/parallel/checkMultiThread.js b/jstests/parallel/checkMultiThread.js index a6b92689bec..c4c6ccd48f0 100644 --- a/jstests/parallel/checkMultiThread.js +++ b/jstests/parallel/checkMultiThread.js @@ -12,9 +12,7 @@ a.start(); b.start(); a.join(); b.join(); -assert.lt(a.returnData().getMilliseconds(), - start.getMilliseconds() + 15000, - "A took more than 15s"); -assert.lt(b.returnData().getMilliseconds(), - start.getMilliseconds() + 15000, - "B took more than 15s"); +assert.lt( + a.returnData().getMilliseconds(), start.getMilliseconds() + 15000, "A took more than 15s"); +assert.lt( + b.returnData().getMilliseconds(), start.getMilliseconds() + 15000, "B took more than 15s"); diff --git a/jstests/perf/v8_mapreduce.js b/jstests/perf/v8_mapreduce.js index 7ff329c5284..c2123c89403 100644 --- a/jstests/perf/v8_mapreduce.js +++ b/jstests/perf/v8_mapreduce.js @@ -13,10 +13,7 @@ if (/V8/.test(interpreterVersion()) && db.runCommand({buildinfo: 1}).javascriptE var tid = tid || 0; var threadStart = new Date(); job(tid); - return { - "threadStart": threadStart, - "threadEnd": new Date() - }; + return {"threadStart": threadStart, "threadEnd": new Date()}; }; // function timeMultipleThreads diff --git a/jstests/readonly/geo.js b/jstests/readonly/geo.js index 73e91c64eeb..13705af0408 100644 --- a/jstests/readonly/geo.js +++ b/jstests/readonly/geo.js @@ -24,10 +24,7 @@ runReadOnlyTest(function() { name: "The Counting Room", loc: {type: "Point", coordinates: [40.7209601, -73.9588041]} }, - { - name: "Kinfolk 94", - loc: {type: "Point", coordinates: [40.7217058, -73.9605489]} - } + {name: "Kinfolk 94", loc: {type: "Point", coordinates: [40.7217058, -73.9605489]}} ]; writableCollection.insertMany(locDocs); diff --git a/jstests/readonly/lib/read_only_test.js b/jstests/readonly/lib/read_only_test.js index 37802ee66d2..e3b68671966 100644 --- a/jstests/readonly/lib/read_only_test.js +++ b/jstests/readonly/lib/read_only_test.js @@ -34,11 +34,7 @@ var StandaloneFixture, ShardedFixture, runReadOnlyTest, zip2, cycleN; try { makeDirectoryReadOnly(this.dbpath); - var options = { - queryableBackupMode: "", - noCleanData: true, - dbpath: this.dbpath - }; + var options = {queryableBackupMode: "", noCleanData: true, dbpath: this.dbpath}; this.mongod = MongoRunner.runMongod(options); @@ -71,17 +67,12 @@ var StandaloneFixture, ShardedFixture, runReadOnlyTest, zip2, cycleN; jsTest.log("restarting shards..."); try { for (var i = 0; i < this.nShards; ++i) { - var opts = { - queryableBackupMode: "", - dbpath: this.paths[i] - }; + var opts = {queryableBackupMode: "", dbpath: this.paths[i]}; assert.commandWorked(this.shardingTest["d" + i].getDB("local").dropDatabase()); - this.shardingTest.restartMongod(i, - opts, - () => { - makeDirectoryReadOnly(this.paths[i]); - }); + this.shardingTest.restartMongod(i, opts, () => { + makeDirectoryReadOnly(this.paths[i]); + }); } jsTest.log("restarting mongos..."); diff --git a/jstests/repl/basic1.js b/jstests/repl/basic1.js index 515667c48e4..ff286b23721 100644 --- a/jstests/repl/basic1.js +++ b/jstests/repl/basic1.js @@ -92,9 +92,7 @@ block(); checkNumCollections("MR4"); var t = am.rpos; -var writeOption = { - writeConcern: {w: 2, wtimeout: 3000} -}; +var writeOption = {writeConcern: {w: 2, wtimeout: 3000}}; t.insert({_id: 1, a: [{n: "a", c: 1}, {n: "b", c: 1}, {n: "c", c: 1}], b: [1, 2, 3]}, writeOption); check("after pos 1 "); @@ -114,11 +112,7 @@ printjson(as.rpos.findOne()); // ).forEach( printjson ) t = am.b; -var updateOption = { - upsert: true, - multi: false, - writeConcern: {w: 2, wtimeout: 3000} -}; +var updateOption = {upsert: true, multi: false, writeConcern: {w: 2, wtimeout: 3000}}; t.update({_id: "fun"}, {$inc: {"a.b.c.x": 6743}}, updateOption); check("b 1"); @@ -142,9 +136,8 @@ assert.soon(function() { return am.lotOfIndexes.getIndexes().length == as.lotOfIndexes.getIndexes().length; }, "lots of indexes a"); -assert.eq(am.lotOfIndexes.getIndexes().length, - as.lotOfIndexes.getIndexes().length, - "lots of indexes b"); +assert.eq( + am.lotOfIndexes.getIndexes().length, as.lotOfIndexes.getIndexes().length, "lots of indexes b"); // multi-update with $inc diff --git a/jstests/repl/batch_write_command_wc_repl.js b/jstests/repl/batch_write_command_wc_repl.js index 3e28b330bf1..167182ed6ae 100644 --- a/jstests/repl/batch_write_command_wc_repl.js +++ b/jstests/repl/batch_write_command_wc_repl.js @@ -18,7 +18,10 @@ var coll = mongod.getCollection("test.batch_write_command_wc_repl"); // // Basic insert, default WC coll.remove({}); -printjson(request = {insert: coll.getName(), documents: [{a: 1}]}); +printjson(request = { + insert: coll.getName(), + documents: [{a: 1}] +}); printjson(result = coll.runCommand(request)); assert(result.ok); assert.eq(1, result.n); @@ -27,7 +30,11 @@ assert.eq(1, coll.count()); // // Basic insert, majority WC coll.remove({}); -printjson(request = {insert: coll.getName(), documents: [{a: 1}], writeConcern: {w: 'majority'}}); +printjson(request = { + insert: coll.getName(), + documents: [{a: 1}], + writeConcern: {w: 'majority'} +}); printjson(result = coll.runCommand(request)); assert(result.ok); assert.eq(1, result.n); @@ -36,7 +43,11 @@ assert.eq(1, coll.count()); // // Basic insert, immediate bad wMode error coll.remove({}); -printjson(request = {insert: coll.getName(), documents: [{a: 1}], writeConcern: {w: 'invalid'}}); +printjson(request = { + insert: coll.getName(), + documents: [{a: 1}], + writeConcern: {w: 'invalid'} +}); printjson(result = coll.runCommand(request)); assert(!result.ok); assert.eq(0, coll.count()); @@ -44,8 +55,11 @@ assert.eq(0, coll.count()); // // Basic insert, error on WC with wtimeout coll.remove({}); -printjson( - request = {insert: coll.getName(), documents: [{a: 1}], writeConcern: {w: 2, wtimeout: 1}}); +printjson(request = { + insert: coll.getName(), + documents: [{a: 1}], + writeConcern: {w: 2, wtimeout: 1} +}); printjson(result = coll.runCommand(request)); assert(result.ok); assert.eq(1, result.n); diff --git a/jstests/repl/repl13.js b/jstests/repl/repl13.js index 78fe9adfc81..c560f285cf4 100644 --- a/jstests/repl/repl13.js +++ b/jstests/repl/repl13.js @@ -61,6 +61,5 @@ assert.eq(1, sc.findOne({_id: 90000}).a); m_hash = m.getDB("d").runCommand("dbhash"); s_hash = s.getDB("d").runCommand("dbhash"); -assert.eq(m_hash.collections.c, - s_hash.collections.c, - "sad " + tojson(m_hash) + " " + tojson(s_hash)); +assert.eq( + m_hash.collections.c, s_hash.collections.c, "sad " + tojson(m_hash) + " " + tojson(s_hash)); diff --git a/jstests/repl/repl14.js b/jstests/repl/repl14.js index 5bd806ef92f..e897d9376f1 100644 --- a/jstests/repl/repl14.js +++ b/jstests/repl/repl14.js @@ -16,9 +16,7 @@ function testWithCollectionIndexIds(capped, sparse, useIds) { toInsert = {}; if (capped) { // Add a singleton array as padding, so the push later on will not change document size. - toInsert = { - p: [1] - }; + toInsert = {p: [1]}; } if (useIds) { // Insert wiith an auto generated _id. mc.insert(toInsert); @@ -35,14 +33,10 @@ function testWithCollectionIndexIds(capped, sparse, useIds) { return sc.count() > 0; }, "doc not replicated soon enough", 60 * 1000); - modifiers = { - $push: {a: 1} - }; + modifiers = {$push: {a: 1}}; if (capped) { // Delete our singleton array to balance the new singleton array we're going to create. - modifiers['$unset'] = { - p: 1 - }; + modifiers['$unset'] = {p: 1}; } assert.writeOK(mc.update({}, modifiers)); diff --git a/jstests/replsets/apply_batch_only_goes_forward.js b/jstests/replsets/apply_batch_only_goes_forward.js index 4744fcf4342..a461e9fad12 100644 --- a/jstests/replsets/apply_batch_only_goes_forward.js +++ b/jstests/replsets/apply_batch_only_goes_forward.js @@ -35,10 +35,7 @@ var sLocal = slave.getDB("local"); var sMinvalid = sLocal["replset.minvalid"]; var stepDownSecs = 30; - var stepDownCmd = { - replSetStepDown: stepDownSecs, - force: true - }; + var stepDownCmd = {replSetStepDown: stepDownSecs, force: true}; // Write op assert.writeOK(mTest.foo.save({}, {writeConcern: {w: 3}})); @@ -50,9 +47,11 @@ var farFutureTS = new Timestamp( Math.floor(new Date().getTime() / 1000) + (60 * 60 * 24 * 5 /* in five days*/), 0); var rsgs = assert.commandWorked(mLocal.adminCommand("replSetGetStatus")); - var primaryOpTime = rsgs.members.filter(function(member) { - return member.self; - })[0].optime; + var primaryOpTime = rsgs.members + .filter(function(member) { + return member.self; + })[0] + .optime; jsTest.log("future TS: " + tojson(farFutureTS) + ", date:" + tsToDate(farFutureTS)); // We do an update in case there is a minvalid document on the primary already. // If the doc doesn't exist then upsert:true will create it, and the writeConcern ensures diff --git a/jstests/replsets/apply_ops_lastop.js b/jstests/replsets/apply_ops_lastop.js index 1e7df9a9035..e3ff0f19554 100644 --- a/jstests/replsets/apply_ops_lastop.js +++ b/jstests/replsets/apply_ops_lastop.js @@ -27,15 +27,12 @@ var insertApplyOps = [{op: "i", ns: 'foo.bar', o: {_id: 1, a: "b"}}]; var deleteApplyOps = [{op: "d", ns: 'foo.bar', o: {_id: 1, a: "b"}}]; var badPreCondition = [{ns: 'foo.bar', q: {_id: 10, a: "aaa"}, res: {a: "aaa"}}]; - var majorityWriteConcern = { - w: 'majority', - wtimeout: 30000 - }; + var majorityWriteConcern = {w: 'majority', wtimeout: 30000}; // Set up some data assert.writeOK(coll.insert({x: 1})); // creating the collection so applyOps works - assert.commandWorked(m1.getDB('foo').runCommand( - {applyOps: insertApplyOps, writeConcern: majorityWriteConcern})); + assert.commandWorked( + m1.getDB('foo').runCommand({applyOps: insertApplyOps, writeConcern: majorityWriteConcern})); var insertOp = m1.getDB('foo').getLastErrorObj('majority', 30000).lastOp; // No-op applyOps diff --git a/jstests/replsets/apply_ops_wc.js b/jstests/replsets/apply_ops_wc.js index 0b8a49e19bd..b0c4fed59c4 100644 --- a/jstests/replsets/apply_ops_wc.js +++ b/jstests/replsets/apply_ops_wc.js @@ -71,7 +71,10 @@ var secondaries = replTest.getSecondaries(); - var majorityWriteConcerns = [{w: 2, wtimeout: 30000}, {w: 'majority', wtimeout: 30000}, ]; + var majorityWriteConcerns = [ + {w: 2, wtimeout: 30000}, + {w: 'majority', wtimeout: 30000}, + ]; function testMajorityWriteConcerns(wc) { jsTest.log("Testing " + tojson(wc)); diff --git a/jstests/replsets/auth1.js b/jstests/replsets/auth1.js index d41ef9ba5ef..13c5f1da260 100644 --- a/jstests/replsets/auth1.js +++ b/jstests/replsets/auth1.js @@ -32,9 +32,8 @@ m = runMongoProgram( "mongod", "--keyFile", key1_644, "--port", port[0], "--dbpath", MongoRunner.dataPath + name); print("should fail with wrong permissions"); -assert.eq(m, - _isWindows() ? 100 : 1, - "mongod should exit w/ 1 (EXIT_FAILURE): permissions too open"); +assert.eq( + m, _isWindows() ? 100 : 1, "mongod should exit w/ 1 (EXIT_FAILURE): permissions too open"); MongoRunner.stopMongod(port[0]); print("add a user to server0: foo"); @@ -74,9 +73,14 @@ assert.eq(r.x, 1); slave.setSlaveOk(); function doQueryOn(p) { - var error = assert.throws(function() { - r = p.getDB("test").foo.findOne(); - }, [], "find did not throw, returned: " + tojson(r)).toString(); + var error = assert + .throws( + function() { + r = p.getDB("test").foo.findOne(); + }, + [], + "find did not throw, returned: " + tojson(r)) + .toString(); printjson(error); assert.gt(error.indexOf("not authorized"), -1, "error was non-auth"); } diff --git a/jstests/replsets/auth2.js b/jstests/replsets/auth2.js index f7b8d8ab468..2300b03bf9c 100644 --- a/jstests/replsets/auth2.js +++ b/jstests/replsets/auth2.js @@ -44,8 +44,8 @@ rs.initiate({ var master = rs.getPrimary(); print("add an admin user"); -master.getDB("admin") - .createUser({user: "foo", pwd: "bar", roles: jsTest.adminUserRoles}, {w: 3, wtimeout: 30000}); +master.getDB("admin").createUser({user: "foo", pwd: "bar", roles: jsTest.adminUserRoles}, + {w: 3, wtimeout: 30000}); var m = rs.nodes[0]; print("starting 1 and 2 with key file"); diff --git a/jstests/replsets/auth3.js b/jstests/replsets/auth3.js index 3ac812bcfa1..bebee24be1b 100644 --- a/jstests/replsets/auth3.js +++ b/jstests/replsets/auth3.js @@ -36,11 +36,9 @@ jsTest.log("make common point"); safeInsert(); - authutil.asCluster(rs.nodes, - keyfile, - function() { - rs.awaitReplication(); - }); + authutil.asCluster(rs.nodes, keyfile, function() { + rs.awaitReplication(); + }); jsTest.log("write stuff to 0&2"); rs.stop(1); @@ -63,10 +61,8 @@ jsTest.log("doing rollback!"); - authutil.asCluster(rs.nodes, - keyfile, - function() { - rs.awaitSecondaryNodes(); - }); + authutil.asCluster(rs.nodes, keyfile, function() { + rs.awaitSecondaryNodes(); + }); }()); diff --git a/jstests/replsets/batch_write_command_wc.js b/jstests/replsets/batch_write_command_wc.js index d6f83c08e3a..b86fd8c80a8 100644 --- a/jstests/replsets/batch_write_command_wc.js +++ b/jstests/replsets/batch_write_command_wc.js @@ -22,7 +22,10 @@ var coll = mongod.getCollection("test.batch_write_command_wc"); // // Basic insert, default WC coll.remove({}); -printjson(request = {insert: coll.getName(), documents: [{a: 1}]}); +printjson(request = { + insert: coll.getName(), + documents: [{a: 1}] +}); printjson(result = coll.runCommand(request)); assert(result.ok); assert.eq(1, result.n); @@ -31,7 +34,11 @@ assert.eq(1, coll.count()); // // Basic insert, majority WC coll.remove({}); -printjson(request = {insert: coll.getName(), documents: [{a: 1}], writeConcern: {w: 'majority'}}); +printjson(request = { + insert: coll.getName(), + documents: [{a: 1}], + writeConcern: {w: 'majority'} +}); printjson(result = coll.runCommand(request)); assert(result.ok); assert.eq(1, result.n); @@ -40,7 +47,11 @@ assert.eq(1, coll.count()); // // Basic insert, w:2 WC coll.remove({}); -printjson(request = {insert: coll.getName(), documents: [{a: 1}], writeConcern: {w: 2}}); +printjson(request = { + insert: coll.getName(), + documents: [{a: 1}], + writeConcern: {w: 2} +}); printjson(result = coll.runCommand(request)); assert(result.ok); assert.eq(1, result.n); @@ -49,7 +60,11 @@ assert.eq(1, coll.count()); // // Basic insert, immediate nojournal error coll.remove({}); -printjson(request = {insert: coll.getName(), documents: [{a: 1}], writeConcern: {j: true}}); +printjson(request = { + insert: coll.getName(), + documents: [{a: 1}], + writeConcern: {j: true} +}); printjson(result = coll.runCommand(request)); assert(!result.ok); assert.eq(0, coll.count()); @@ -57,8 +72,11 @@ assert.eq(0, coll.count()); // // Basic insert, timeout wc error coll.remove({}); -printjson( - request = {insert: coll.getName(), documents: [{a: 1}], writeConcern: {w: 3, wtimeout: 1}}); +printjson(request = { + insert: coll.getName(), + documents: [{a: 1}], + writeConcern: {w: 3, wtimeout: 1} +}); printjson(result = coll.runCommand(request)); assert(result.ok); assert.eq(1, result.n); @@ -69,7 +87,11 @@ assert.eq(1, coll.count()); // // Basic insert, wmode wc error coll.remove({}); -printjson(request = {insert: coll.getName(), documents: [{a: 1}], writeConcern: {w: 'invalid'}}); +printjson(request = { + insert: coll.getName(), + documents: [{a: 1}], + writeConcern: {w: 'invalid'} +}); printjson(result = coll.runCommand(request)); assert(result.ok); assert.eq(1, result.n); diff --git a/jstests/replsets/capped_id.js b/jstests/replsets/capped_id.js index 8708f5752f8..ee05e810d59 100644 --- a/jstests/replsets/capped_id.js +++ b/jstests/replsets/capped_id.js @@ -40,9 +40,12 @@ var slave1db = slave1.getDB(dbname); var slave2db = slave2.getDB(dbname); function countIdIndexes(theDB, coll) { - return theDB[coll].getIndexes().filter(function(idx) { - return friendlyEqual(idx.key, {_id: 1}); - }).length; + return theDB[coll] + .getIndexes() + .filter(function(idx) { + return friendlyEqual(idx.key, {_id: 1}); + }) + .length; } var numtests = 4; diff --git a/jstests/replsets/chaining_removal.js b/jstests/replsets/chaining_removal.js index dbc80148745..929e452844f 100644 --- a/jstests/replsets/chaining_removal.js +++ b/jstests/replsets/chaining_removal.js @@ -49,9 +49,7 @@ // write that should reach all nodes var timeout = 60 * 1000; - var options = { - writeConcern: {w: numNodes, wtimeout: timeout} - }; + var options = {writeConcern: {w: numNodes, wtimeout: timeout}}; assert.writeOK(primary.getDB(name).foo.insert({x: 1}, options)); var config = primary.getDB("local").system.replset.findOne(); diff --git a/jstests/replsets/commands_that_write_accept_wc.js b/jstests/replsets/commands_that_write_accept_wc.js index 9f35d5c6549..83a341767c2 100644 --- a/jstests/replsets/commands_that_write_accept_wc.js +++ b/jstests/replsets/commands_that_write_accept_wc.js @@ -99,9 +99,7 @@ load('jstests/libs/write_concern_util.js'); }); }, reduce: function(key, values) { - return { - count: values.length - }; + return {count: values.length}; }, out: "foo" }, @@ -120,10 +118,7 @@ load('jstests/libs/write_concern_util.js'); }); function testValidWriteConcern(cmd) { - cmd.req.writeConcern = { - w: 'majority', - wtimeout: 25000 - }; + cmd.req.writeConcern = {w: 'majority', wtimeout: 25000}; jsTest.log("Testing " + tojson(cmd.req)); dropTestCollection(); @@ -136,9 +131,7 @@ load('jstests/libs/write_concern_util.js'); } function testInvalidWriteConcern(cmd) { - cmd.req.writeConcern = { - w: 'invalid' - }; + cmd.req.writeConcern = {w: 'invalid'}; jsTest.log("Testing " + tojson(cmd.req)); dropTestCollection(); diff --git a/jstests/replsets/config_server_checks.js b/jstests/replsets/config_server_checks.js index 041b3a29699..f5dfab883cf 100644 --- a/jstests/replsets/config_server_checks.js +++ b/jstests/replsets/config_server_checks.js @@ -89,11 +89,8 @@ function expectState(rst, state) { // fail to // start up and won't automatically add "configsvr" to the replset config (SERVER-21236). jsTestLog("set initiated without configsvr, restarted adding --configsvr cmd line"); - var rst = new ReplSetTest({ - name: "configrs7", - nodes: 1, - nodeOptions: {journal: "", storageEngine: "wiredTiger"} - }); + var rst = new ReplSetTest( + {name: "configrs7", nodes: 1, nodeOptions: {journal: "", storageEngine: "wiredTiger"}}); rst.startSet(); var conf = rst.getReplSetConfig(); diff --git a/jstests/replsets/disallow_adding_initialized_node1.js b/jstests/replsets/disallow_adding_initialized_node1.js index 8d4491975b6..f2a6b3053fb 100644 --- a/jstests/replsets/disallow_adding_initialized_node1.js +++ b/jstests/replsets/disallow_adding_initialized_node1.js @@ -7,11 +7,21 @@ 'use strict'; var name = 'disallow_adding_initialized_node1'; - var replSetA = new ReplSetTest({name: name, nodes: [{rsConfig: {_id: 10}}, ]}); + var replSetA = new ReplSetTest({ + name: name, + nodes: [ + {rsConfig: {_id: 10}}, + ] + }); replSetA.startSet({dbpath: "$set-A-$node"}); replSetA.initiate(); - var replSetB = new ReplSetTest({name: name, nodes: [{rsConfig: {_id: 20}}, ]}); + var replSetB = new ReplSetTest({ + name: name, + nodes: [ + {rsConfig: {_id: 20}}, + ] + }); replSetB.startSet({dbpath: "$set-B-$node"}); replSetB.initiate(); diff --git a/jstests/replsets/disallow_adding_initialized_node2.js b/jstests/replsets/disallow_adding_initialized_node2.js index c4125f7c069..5778a3c3e8b 100644 --- a/jstests/replsets/disallow_adding_initialized_node2.js +++ b/jstests/replsets/disallow_adding_initialized_node2.js @@ -12,12 +12,22 @@ 'use strict'; var name = 'disallow_adding_initialized_node2'; - var replSetA = new ReplSetTest( - {name: name, nodes: [{rsConfig: {_id: 10}}, {rsConfig: {_id: 11, arbiterOnly: true}}, ]}); + var replSetA = new ReplSetTest({ + name: name, + nodes: [ + {rsConfig: {_id: 10}}, + {rsConfig: {_id: 11, arbiterOnly: true}}, + ] + }); replSetA.startSet({dbpath: "$set-A-$node"}); replSetA.initiate(); - var replSetB = new ReplSetTest({name: name, nodes: [{rsConfig: {_id: 20}}, ]}); + var replSetB = new ReplSetTest({ + name: name, + nodes: [ + {rsConfig: {_id: 20}}, + ] + }); replSetB.startSet({dbpath: "$set-B-$node"}); replSetB.initiate(); diff --git a/jstests/replsets/initial_sync1.js b/jstests/replsets/initial_sync1.js index 3977445743e..ceb614b68a6 100644 --- a/jstests/replsets/initial_sync1.js +++ b/jstests/replsets/initial_sync1.js @@ -77,9 +77,8 @@ wait(function() { return config2.version == config.version && (config3 && config3.version == config.version); }); -replTest.waitForState(slave2, - [ReplSetTest.State.SECONDARY, ReplSetTest.State.RECOVERING], - 60 * 1000); +replTest.waitForState( + slave2, [ReplSetTest.State.SECONDARY, ReplSetTest.State.RECOVERING], 60 * 1000); print("7. Kill the secondary in the middle of syncing"); replTest.stop(slave1); diff --git a/jstests/replsets/initial_sync_update_missing_doc2.js b/jstests/replsets/initial_sync_update_missing_doc2.js index 559fda41534..f8333baa41a 100644 --- a/jstests/replsets/initial_sync_update_missing_doc2.js +++ b/jstests/replsets/initial_sync_update_missing_doc2.js @@ -60,10 +60,7 @@ checkLog(secondary, 'initial sync - initialSyncHangBeforeGettingMissingDocument fail point enabled'); - var doc = { - _id: 0, - x: 3 - }; + var doc = {_id: 0, x: 3}; // Re-insert deleted document. assert.writeOK(coll.insert(doc, {writeConcern: {w: 1}})); diff --git a/jstests/replsets/localhostAuthBypass.js b/jstests/replsets/localhostAuthBypass.js index 2b2332d258a..22a512f19d0 100644 --- a/jstests/replsets/localhostAuthBypass.js +++ b/jstests/replsets/localhostAuthBypass.js @@ -68,17 +68,13 @@ var assertCannotRunCommands = function(mongo, isPrimary) { {param: "userCacheInvalidationIntervalSecs", val: 300} ]; params.forEach(function(p) { - var cmd = { - setParameter: 1 - }; + var cmd = {setParameter: 1}; cmd[p.param] = p.val; assert.commandFailedWithCode( mongo.getDB("admin").runCommand(cmd), authorizeErrorCode, "setParameter: " + p.param); }); params.forEach(function(p) { - var cmd = { - getParameter: 1 - }; + var cmd = {getParameter: 1}; cmd[p.param] = 1; assert.commandFailedWithCode( mongo.getDB("admin").runCommand(cmd), authorizeErrorCode, "getParameter: " + p.param); @@ -221,8 +217,8 @@ var runNonlocalTest = function(ipAddr) { }); assert.throws(function() { - mongo.getDB("admin") - .createUser({user: username, pwd: password, roles: jsTest.adminUserRoles}); + mongo.getDB("admin").createUser( + {user: username, pwd: password, roles: jsTest.adminUserRoles}); }); shutdown(rs); diff --git a/jstests/replsets/oplog_format.js b/jstests/replsets/oplog_format.js index e597197fed0..a2c37d294a5 100644 --- a/jstests/replsets/oplog_format.js +++ b/jstests/replsets/oplog_format.js @@ -169,8 +169,8 @@ assertLastOplog({$set: {"a.b": [{c: 1}, {c: 2}]}}, {_id: 1}, msg); var msg = "bad array $push $slice $sort reversed first two"; coll.save({_id: 1, a: {b: [{c: 1}, {c: 2}]}}); -res = assert.writeOK(coll.update( - {_id: {$gt: 0}}, {$push: {"a.b": {$each: [{c: -1}], $slice: -2, $sort: {c: -1}}}})); +res = assert.writeOK( + coll.update({_id: {$gt: 0}}, {$push: {"a.b": {$each: [{c: -1}], $slice: -2, $sort: {c: -1}}}})); assert.eq(res.nModified, 1, "update failed for '" + msg + "': " + res.toString()); assert.docEq({_id: 1, a: {b: [{c: 1}, {c: -1}]}}, coll.findOne({}), msg); assertLastOplog({$set: {"a.b": [{c: 1}, {c: -1}]}}, {_id: 1}, msg); diff --git a/jstests/replsets/optime.js b/jstests/replsets/optime.js index a716ca3dbca..5403ab35bcd 100644 --- a/jstests/replsets/optime.js +++ b/jstests/replsets/optime.js @@ -42,9 +42,7 @@ var initialInfo = master.getDB('admin').serverStatus({oplog: true}).oplog; // Do an insert to increment optime, but without rolling the oplog // latestOptime should be updated, but earliestOptime should be unchanged -var options = { - writeConcern: {w: replTest.nodes.length} -}; +var options = {writeConcern: {w: replTest.nodes.length}}; assert.writeOK(master.getDB('test').foo.insert({a: 1}, options)); assert(optimesAreEqual(replTest)); diff --git a/jstests/replsets/pipelineout.js b/jstests/replsets/pipelineout.js index bb86f98c4e9..91e07d9a457 100644 --- a/jstests/replsets/pipelineout.js +++ b/jstests/replsets/pipelineout.js @@ -12,21 +12,21 @@ var secondary = replTest.liveNodes.slaves[0].getDB(name); // populate the collection for (i = 0; i < 5; i++) { - primary.in.insert({x: i}); + primary.in .insert({x: i}); } replTest.awaitReplication(); // make sure $out cannot be run on a secondary assert.throws(function() { - secondary.in.aggregate({$out: "out"}).itcount; + secondary.in .aggregate({$out: "out"}).itcount; }); // even if slaveOk secondary.setSlaveOk(); assert.throws(function() { - secondary.in.aggregate({$out: "out"}).itcount; + secondary.in .aggregate({$out: "out"}).itcount; }); // run one and check for proper replication -primary.in.aggregate({$out: "out"}).itcount; +primary.in .aggregate({$out: "out"}).itcount; replTest.awaitReplication(); assert.eq(primary.out.find().sort({x: 1}).toArray(), secondary.out.find().sort({x: 1}).toArray()); diff --git a/jstests/replsets/priority_takeover_one_node_higher_priority.js b/jstests/replsets/priority_takeover_one_node_higher_priority.js index e718ef131f9..8c909c643c3 100644 --- a/jstests/replsets/priority_takeover_one_node_higher_priority.js +++ b/jstests/replsets/priority_takeover_one_node_higher_priority.js @@ -8,8 +8,14 @@ load('jstests/replsets/rslib.js'); var name = 'priority_takeover_one_node_higher_priority'; - var replSet = new ReplSetTest( - {name: name, nodes: [{rsConfig: {priority: 3}}, {}, {rsConfig: {arbiterOnly: true}}, ]}); + var replSet = new ReplSetTest({ + name: name, + nodes: [ + {rsConfig: {priority: 3}}, + {}, + {rsConfig: {arbiterOnly: true}}, + ] + }); replSet.startSet(); replSet.initiate(); diff --git a/jstests/replsets/priority_takeover_two_nodes_equal_priority.js b/jstests/replsets/priority_takeover_two_nodes_equal_priority.js index 42134f9430e..b6e8cc25b77 100644 --- a/jstests/replsets/priority_takeover_two_nodes_equal_priority.js +++ b/jstests/replsets/priority_takeover_two_nodes_equal_priority.js @@ -8,8 +8,14 @@ load('jstests/replsets/rslib.js'); 'use strict'; var name = 'priority_takeover_two_nodes_equal_priority'; - var replSet = new ReplSetTest( - {name: name, nodes: [{rsConfig: {priority: 3}}, {rsConfig: {priority: 3}}, {}, ]}); + var replSet = new ReplSetTest({ + name: name, + nodes: [ + {rsConfig: {priority: 3}}, + {rsConfig: {priority: 3}}, + {}, + ] + }); replSet.startSet(); replSet.initiate(); diff --git a/jstests/replsets/read_committed.js b/jstests/replsets/read_committed.js index be051ffbee8..bed22c08248 100644 --- a/jstests/replsets/read_committed.js +++ b/jstests/replsets/read_committed.js @@ -11,9 +11,7 @@ load("jstests/replsets/rslib.js"); // For startSetIfSupportsReadMajority. (function() { "use strict"; - const majorityWriteConcern = { - writeConcern: {w: "majority", wtimeout: 60 * 1000} - }; + const majorityWriteConcern = {writeConcern: {w: "majority", wtimeout: 60 * 1000}}; // Each test case includes a 'prepareCollection' method that sets up the initial state starting // with an empty collection, a 'write' method that does some write, and two arrays, @@ -105,13 +103,12 @@ load("jstests/replsets/rslib.js"); // For startSetIfSupportsReadMajority. function readLatestOplogEntry(readConcernLevel) { var oplog = primary.getDB('local').oplog.rs; - var res = oplog.runCommand('find', - { - "readConcern": {"level": readConcernLevel}, - "maxTimeMS": 3000, - sort: {$natural: -1}, - limit: 1, - }); + var res = oplog.runCommand('find', { + "readConcern": {"level": readConcernLevel}, + "maxTimeMS": 3000, + sort: {$natural: -1}, + limit: 1, + }); assert.commandWorked(res); return new DBCommandCursor(coll.getMongo(), res).toArray()[0]; } diff --git a/jstests/replsets/read_committed_with_catalog_changes.js b/jstests/replsets/read_committed_with_catalog_changes.js index 14eec54cab4..03b9808f9a0 100644 --- a/jstests/replsets/read_committed_with_catalog_changes.js +++ b/jstests/replsets/read_committed_with_catalog_changes.js @@ -215,8 +215,8 @@ load("jstests/replsets/rslib.js"); // For startSetIfSupportsReadMajority. } function assertReadsSucceed(coll, timeoutMs = 10000) { - var res = coll.runCommand('find', - {"readConcern": {"level": "majority"}, "maxTimeMS": timeoutMs}); + var res = + coll.runCommand('find', {"readConcern": {"level": "majority"}, "maxTimeMS": timeoutMs}); assert.commandWorked(res, 'reading from ' + coll.getFullName()); // Exhaust the cursor to avoid leaking cursors on the server. new DBCommandCursor(coll.getMongo(), res).itcount(); diff --git a/jstests/replsets/reconfig.js b/jstests/replsets/reconfig.js index 1351aa1d54b..312a3cb6243 100644 --- a/jstests/replsets/reconfig.js +++ b/jstests/replsets/reconfig.js @@ -23,11 +23,7 @@ jsTestLog("Invalid reconfig"); config.version++; - var badMember = { - _id: numNodes, - host: "localhost:12345", - priority: "High" - }; + var badMember = {_id: numNodes, host: "localhost:12345", priority: "High"}; config.members.push(badMember); var invalidConfigCode = 93; assert.commandFailedWithCode(primary.adminCommand({replSetReconfig: config}), diff --git a/jstests/replsets/reconfig_tags.js b/jstests/replsets/reconfig_tags.js index 3c4d0e2616d..86a2419f4e9 100644 --- a/jstests/replsets/reconfig_tags.js +++ b/jstests/replsets/reconfig_tags.js @@ -12,15 +12,9 @@ var rsConfig = primary.getDB("local").system.replset.findOne(); jsTest.log('got rsconf ' + tojson(rsConfig)); rsConfig.members.forEach(function(member) { if (member.host == primary.host) { - member.tags = { - dc: 'ny', - tag: 'one' - }; + member.tags = {dc: 'ny', tag: 'one'}; } else { - member.tags = { - dc: 'ny', - tag: 'two' - }; + member.tags = {dc: 'ny', tag: 'two'}; } }); diff --git a/jstests/replsets/remove1.js b/jstests/replsets/remove1.js index cde4974677a..f587275570a 100644 --- a/jstests/replsets/remove1.js +++ b/jstests/replsets/remove1.js @@ -55,9 +55,8 @@ assert.soon(function() { }); // Now we should successfully reconnect to the secondary. -assert.eq(secondary.getDB("admin").runCommand({ping: 1}).ok, - 1, - "we aren't connected to the secondary"); +assert.eq( + secondary.getDB("admin").runCommand({ping: 1}).ok, 1, "we aren't connected to the secondary"); reconnect(master); diff --git a/jstests/replsets/repl_options.js b/jstests/replsets/repl_options.js index 66a07787889..a0af2fa2573 100644 --- a/jstests/replsets/repl_options.js +++ b/jstests/replsets/repl_options.js @@ -3,9 +3,7 @@ var baseName = "jstests_repl_repl_options"; load('jstests/libs/command_line/test_parsed_options.js'); jsTest.log("Testing \"replSet\" command line option"); -var expectedResult = { - "parsed": {"replication": {"replSet": "mycmdlinename"}} -}; +var expectedResult = {"parsed": {"replication": {"replSet": "mycmdlinename"}}}; testGetCmdLineOptsMongod({replSet: "mycmdlinename"}, expectedResult); jsTest.log("Testing \"replication.replSetName\" config file option"); diff --git a/jstests/replsets/replset2.js b/jstests/replsets/replset2.js index b50a939242d..d578fe0d4b4 100644 --- a/jstests/replsets/replset2.js +++ b/jstests/replsets/replset2.js @@ -66,9 +66,7 @@ doTest = function(signal) { // Test write concern with a simple insert print("replset2.js **** Try inserting a single record ****"); master.getDB(testDB).dropDatabase(); - var options = { - writeConcern: {w: 3, wtimeout: 10000} - }; + var options = {writeConcern: {w: 3, wtimeout: 10000}}; assert.writeOK(master.getDB(testDB).foo.insert({n: 1}, options)); m1 = master.getDB(testDB).foo.findOne({n: 1}); diff --git a/jstests/replsets/replset5.js b/jstests/replsets/replset5.js index c0aee6e1154..65f2b66212e 100644 --- a/jstests/replsets/replset5.js +++ b/jstests/replsets/replset5.js @@ -11,10 +11,7 @@ load("jstests/replsets/rslib.js"); // Initiate set with default for write concern var config = replTest.getReplSetConfig(); config.settings = {}; - config.settings.getLastErrorDefaults = { - 'w': 3, - 'wtimeout': 20000 - }; + config.settings.getLastErrorDefaults = {'w': 3, 'wtimeout': 20000}; config.settings.heartbeatTimeoutSecs = 15; // Prevent node 2 from becoming primary, as we will attempt to set it to hidden later. config.members[2].priority = 0; diff --git a/jstests/replsets/replset7.js b/jstests/replsets/replset7.js index 8b13f2ed7e2..94dff59b33f 100644 --- a/jstests/replsets/replset7.js +++ b/jstests/replsets/replset7.js @@ -45,7 +45,10 @@ rt.awaitSecondaryNodes(); // Do we have an index? assert.eq(1, - slave.getDB('d')['c'].getIndexes().filter(function(doc) { - return (doc.v === 1 && JSON.stringify(doc.key) === JSON.stringify({x: 1}) && - doc.ns === 'd.c' && doc.name === 'x_1'); - }).length); + slave.getDB('d')['c'] + .getIndexes() + .filter(function(doc) { + return (doc.v === 1 && JSON.stringify(doc.key) === JSON.stringify({x: 1}) && + doc.ns === 'd.c' && doc.name === 'x_1'); + }) + .length); diff --git a/jstests/replsets/rollback5.js b/jstests/replsets/rollback5.js index e63b7ab34ea..42649dc5162 100644 --- a/jstests/replsets/rollback5.js +++ b/jstests/replsets/rollback5.js @@ -44,10 +44,7 @@ assert.soon(function() { return res.myState == 7; }, "Arbiter failed to initialize."); -var options = { - writeConcern: {w: 2, wtimeout: 60000}, - upsert: true -}; +var options = {writeConcern: {w: 2, wtimeout: 60000}, upsert: true}; assert.writeOK(A.foo.update({key: 'value1'}, {$set: {req: 'req'}}, options)); replTest.stop(AID); diff --git a/jstests/replsets/rollback_auth.js b/jstests/replsets/rollback_auth.js index 0c0b35b91ed..85f4a0c4991 100644 --- a/jstests/replsets/rollback_auth.js +++ b/jstests/replsets/rollback_auth.js @@ -125,15 +125,14 @@ // Modify the the user and role in a way that will be rolled back. b.grantPrivilegesToRole( 'myRole', - [{resource: {db: 'test', collection: 'foo'}, actions: ['collStats']}], - {}); // Default write concern will wait for majority, which will time out. - b.createRole( - { - role: 'temporaryRole', - roles: [], - privileges: [{resource: {db: 'test', collection: 'bar'}, actions: ['collStats']}] - }, + [{resource: {db: 'test', collection: 'foo'}, actions: ['collStats']}], {}); // Default write concern will wait for majority, which will time out. + b.createRole({ + role: 'temporaryRole', + roles: [], + privileges: [{resource: {db: 'test', collection: 'bar'}, actions: ['collStats']}] + }, + {}); // Default write concern will wait for majority, which will time out. b.grantRolesToUser('spencer', ['temporaryRole'], {}); // Default write concern will wait for majority, which will time out. @@ -172,13 +171,12 @@ a.grantPrivilegesToRole( 'myRole', [{resource: {db: 'test', collection: 'baz'}, actions: ['collStats']}], {}); - a.createRole( - { - role: 'persistentRole', - roles: [], - privileges: [{resource: {db: 'test', collection: 'foobar'}, actions: ['collStats']}] - }, - {}); + a.createRole({ + role: 'persistentRole', + roles: [], + privileges: [{resource: {db: 'test', collection: 'foobar'}, actions: ['collStats']}] + }, + {}); a.grantRolesToUser('spencer', ['persistentRole'], {}); A.logout(); a.auth('spencer', 'pwd'); @@ -191,11 +189,9 @@ // bring B back in contact with A // as A is primary, B will roll back and then catch up replTest.restart(1); - authutil.asCluster(replTest.nodes, - 'jstests/libs/key1', - function() { - replTest.awaitReplication(); - }); + authutil.asCluster(replTest.nodes, 'jstests/libs/key1', function() { + replTest.awaitReplication(); + }); assert.soon(function() { return b.auth('spencer', 'pwd'); }); diff --git a/jstests/replsets/rollback_cmd_unrollbackable.js b/jstests/replsets/rollback_cmd_unrollbackable.js index 801d4c285a7..cf176ab312d 100644 --- a/jstests/replsets/rollback_cmd_unrollbackable.js +++ b/jstests/replsets/rollback_cmd_unrollbackable.js @@ -30,10 +30,7 @@ replTest.waitForState(replTest.nodes[0], ReplSetTest.State.PRIMARY, 60 * 1000); var master = replTest.getPrimary(); assert(master === conns[0], "conns[0] assumed to be master"); assert(a_conn.host === master.host, "a_conn assumed to be master"); -var options = { - writeConcern: {w: 2, wtimeout: 60000}, - upsert: true -}; +var options = {writeConcern: {w: 2, wtimeout: 60000}, upsert: true}; assert.writeOK(a_conn.getDB(name).foo.insert({x: 1}, options)); // shut down master diff --git a/jstests/replsets/rollback_collMod_PowerOf2Sizes.js b/jstests/replsets/rollback_collMod_PowerOf2Sizes.js index deab19b2f09..24177ebe6b7 100644 --- a/jstests/replsets/rollback_collMod_PowerOf2Sizes.js +++ b/jstests/replsets/rollback_collMod_PowerOf2Sizes.js @@ -43,10 +43,7 @@ }; assert.commandWorked(a_conn.getDB(name).createCollection('foo', originalCollectionOptions)); - var options = { - writeConcern: {w: 2, wtimeout: 60000}, - upsert: true - }; + var options = {writeConcern: {w: 2, wtimeout: 60000}, upsert: true}; assert.writeOK(a_conn.getDB(name).foo.insert({x: 1}, options)); assert.eq(getOptions(a_conn), originalCollectionOptions); @@ -64,9 +61,8 @@ validationLevel: "moderate", validationAction: "warn" })); - assert.eq( - getOptions(a_conn), - {flags: 2, validator: {a: 1}, validationLevel: "moderate", validationAction: "warn"}); + assert.eq(getOptions(a_conn), + {flags: 2, validator: {a: 1}, validationLevel: "moderate", validationAction: "warn"}); // Shut down A and fail over to B. replTest.stop(AID); @@ -76,10 +72,7 @@ b_conn = master; // Do a write on B so that A will have to roll back. - options = { - writeConcern: {w: 1, wtimeout: 60000}, - upsert: true - }; + options = {writeConcern: {w: 1, wtimeout: 60000}, upsert: true}; assert.writeOK(b_conn.getDB(name).foo.insert({x: 2}, options)); // Restart A, which should rollback the collMod before becoming primary. diff --git a/jstests/replsets/rollback_collMod_fatal.js b/jstests/replsets/rollback_collMod_fatal.js index c907213f05d..0fcec31f6fc 100644 --- a/jstests/replsets/rollback_collMod_fatal.js +++ b/jstests/replsets/rollback_collMod_fatal.js @@ -31,10 +31,7 @@ replTest.waitForState(replTest.nodes[0], ReplSetTest.State.PRIMARY, 60 * 1000); var master = replTest.getPrimary(); assert(master === conns[0], "conns[0] assumed to be master"); assert(a_conn.host === master.host, "a_conn assumed to be master"); -var options = { - writeConcern: {w: 2, wtimeout: 60000}, - upsert: true -}; +var options = {writeConcern: {w: 2, wtimeout: 60000}, upsert: true}; a_conn.getDB(name).foo.ensureIndex({x: 1}, {expireAfterSeconds: 3600}); assert.writeOK(a_conn.getDB(name).foo.insert({x: 1}, options)); diff --git a/jstests/replsets/rollback_different_h.js b/jstests/replsets/rollback_different_h.js index 4b9aede1bbc..1d753ea46c6 100644 --- a/jstests/replsets/rollback_different_h.js +++ b/jstests/replsets/rollback_different_h.js @@ -42,10 +42,7 @@ replTest.waitForState(replTest.nodes[0], ReplSetTest.State.PRIMARY, 60 * 1000); var master = replTest.getPrimary(); assert(master === conns[0], "conns[0] assumed to be master"); assert(a_conn.host === master.host, "a_conn assumed to be master"); -var options = { - writeConcern: {w: 2, wtimeout: 60000}, - upsert: true -}; +var options = {writeConcern: {w: 2, wtimeout: 60000}, upsert: true}; assert.writeOK(a_conn.getDB(name).foo.insert({x: 1}, options)); // shut down master diff --git a/jstests/replsets/rollback_dropdb.js b/jstests/replsets/rollback_dropdb.js index c11b14ab06e..818d74b2ad2 100644 --- a/jstests/replsets/rollback_dropdb.js +++ b/jstests/replsets/rollback_dropdb.js @@ -31,10 +31,7 @@ replTest.waitForState(replTest.nodes[0], ReplSetTest.State.PRIMARY, 60 * 1000); var master = replTest.getPrimary(); assert(master === conns[0], "conns[0] assumed to be master"); assert(a_conn.host === master.host, "a_conn assumed to be master"); -var options = { - writeConcern: {w: 2, wtimeout: 60000}, - upsert: true -}; +var options = {writeConcern: {w: 2, wtimeout: 60000}, upsert: true}; assert.writeOK(a_conn.getDB(name).foo.insert({x: 1}, options)); // shut down master diff --git a/jstests/replsets/rollback_empty_ns.js b/jstests/replsets/rollback_empty_ns.js index f6a07319eb4..44be3b0bbb4 100644 --- a/jstests/replsets/rollback_empty_ns.js +++ b/jstests/replsets/rollback_empty_ns.js @@ -42,10 +42,7 @@ replTest.waitForState(replTest.nodes[0], ReplSetTest.State.PRIMARY, 60 * 1000); var master = replTest.getPrimary(); assert(master === conns[0], "conns[0] assumed to be master"); assert(a_conn.host === master.host, "a_conn assumed to be master"); -var options = { - writeConcern: {w: 2, wtimeout: 60000}, - upsert: true -}; +var options = {writeConcern: {w: 2, wtimeout: 60000}, upsert: true}; assert.writeOK(a_conn.getDB(name).foo.insert({x: 1}, options)); // shut down master diff --git a/jstests/replsets/rollback_empty_o.js b/jstests/replsets/rollback_empty_o.js index f3468fcde5e..ebce959f704 100644 --- a/jstests/replsets/rollback_empty_o.js +++ b/jstests/replsets/rollback_empty_o.js @@ -42,10 +42,7 @@ replTest.waitForState(replTest.nodes[0], ReplSetTest.State.PRIMARY, 60 * 1000); var master = replTest.getPrimary(); assert(master === conns[0], "conns[0] assumed to be master"); assert(a_conn.host === master.host, "a_conn assumed to be master"); -var options = { - writeConcern: {w: 2, wtimeout: 60000}, - upsert: true -}; +var options = {writeConcern: {w: 2, wtimeout: 60000}, upsert: true}; assert.writeOK(a_conn.getDB(name).foo.insert({x: 1}, options)); // shut down master diff --git a/jstests/replsets/rollback_empty_o2.js b/jstests/replsets/rollback_empty_o2.js index 56eb8512575..bf13aac67ad 100644 --- a/jstests/replsets/rollback_empty_o2.js +++ b/jstests/replsets/rollback_empty_o2.js @@ -42,10 +42,7 @@ replTest.waitForState(replTest.nodes[0], ReplSetTest.State.PRIMARY, 60 * 1000); var master = replTest.getPrimary(); assert(master === conns[0], "conns[0] assumed to be master"); assert(a_conn.host === master.host, "a_conn assumed to be master"); -var options = { - writeConcern: {w: 2, wtimeout: 60000}, - upsert: true -}; +var options = {writeConcern: {w: 2, wtimeout: 60000}, upsert: true}; assert.writeOK(a_conn.getDB(name).foo.insert({x: 1}, options)); // shut down master diff --git a/jstests/replsets/rollback_fake_cmd.js b/jstests/replsets/rollback_fake_cmd.js index 175359121f8..f6ce306ba08 100644 --- a/jstests/replsets/rollback_fake_cmd.js +++ b/jstests/replsets/rollback_fake_cmd.js @@ -42,10 +42,7 @@ replTest.waitForState(replTest.nodes[0], ReplSetTest.State.PRIMARY, 60 * 1000); var master = replTest.getPrimary(); assert(master === conns[0], "conns[0] assumed to be master"); assert(a_conn.host === master.host, "a_conn assumed to be master"); -var options = { - writeConcern: {w: 2, wtimeout: 60000}, - upsert: true -}; +var options = {writeConcern: {w: 2, wtimeout: 60000}, upsert: true}; assert.writeOK(a_conn.getDB(name).foo.insert({x: 1}, options)); // shut down master diff --git a/jstests/replsets/rollback_index.js b/jstests/replsets/rollback_index.js index 6fb3044b740..ca03075ad2b 100644 --- a/jstests/replsets/rollback_index.js +++ b/jstests/replsets/rollback_index.js @@ -44,10 +44,7 @@ replTest.waitForState(replTest.nodes[0], ReplSetTest.State.PRIMARY, 60 * 1000); var master = replTest.getPrimary(); assert(master === conns[0], "conns[0] assumed to be master"); assert(a_conn.host === master.host, "a_conn assumed to be master"); -var options = { - writeConcern: {w: 2, wtimeout: 60000}, - upsert: true -}; +var options = {writeConcern: {w: 2, wtimeout: 60000}, upsert: true}; assert.writeOK(a_conn.getDB(name).foo.insert({x: 1}, options)); // shut down master @@ -97,9 +94,9 @@ assert.writeOK(a_conn.getDB(name).foo.insert({x: 1}, options)); assert.eq(3, b_conn.getDB(name).foo.count(), 'Collection on B does not have the same number of documents as A'); -assert.eq(a_conn.getDB(name).foo.getIndexes().length, - b_conn.getDB(name).foo.getIndexes().length, - 'Unique index not dropped during rollback: ' + - tojson(b_conn.getDB(name).foo.getIndexes())); +assert.eq( + a_conn.getDB(name).foo.getIndexes().length, + b_conn.getDB(name).foo.getIndexes().length, + 'Unique index not dropped during rollback: ' + tojson(b_conn.getDB(name).foo.getIndexes())); replTest.stopSet(); diff --git a/jstests/replsets/rollback_too_new.js b/jstests/replsets/rollback_too_new.js index e0a88e12f31..2e8e4d3693d 100644 --- a/jstests/replsets/rollback_too_new.js +++ b/jstests/replsets/rollback_too_new.js @@ -28,17 +28,13 @@ // get master and do an initial write var master = replTest.getPrimary(); - var options = { - writeConcern: {w: 2, wtimeout: 60000} - }; + var options = {writeConcern: {w: 2, wtimeout: 60000}}; assert.writeOK(master.getDB(name).foo.insert({x: 1}, options)); // add an oplog entry from the distant future as the most recent entry on node C var future_oplog_entry = conns[2].getDB("local").oplog.rs.find().sort({$natural: -1})[0]; future_oplog_entry["ts"] = new Timestamp(future_oplog_entry["ts"].getTime() + 200000, 1); - options = { - writeConcern: {w: 1, wtimeout: 60000} - }; + options = {writeConcern: {w: 1, wtimeout: 60000}}; assert.writeOK(conns[2].getDB("local").oplog.rs.insert(future_oplog_entry, options)); replTest.stop(CID); diff --git a/jstests/replsets/server_status_metrics.js b/jstests/replsets/server_status_metrics.js index fb7f92fe55f..05a3b4bccc0 100644 --- a/jstests/replsets/server_status_metrics.js +++ b/jstests/replsets/server_status_metrics.js @@ -56,11 +56,7 @@ assert.writeOK(bulk.execute({w: 2})); testSecondaryMetrics(secondary, 1000, secondaryBaseOplogInserts); -var options = { - writeConcern: {w: 2}, - multi: true, - upsert: true -}; +var options = {writeConcern: {w: 2}, multi: true, upsert: true}; assert.writeOK(testDB.a.update({}, {$set: {d: new Date()}}, options)); testSecondaryMetrics(secondary, 2000, secondaryBaseOplogInserts); diff --git a/jstests/replsets/stepdown3.js b/jstests/replsets/stepdown3.js index d0da019f7a1..968877a2069 100644 --- a/jstests/replsets/stepdown3.js +++ b/jstests/replsets/stepdown3.js @@ -19,9 +19,7 @@ // do another write, because the first one might be longer than 10 seconds ago // on the secondary (due to starting up), and we need to be within 10 seconds // to step down. - var options = { - writeConcern: {w: 2, wtimeout: 30000} - }; + var options = {writeConcern: {w: 2, wtimeout: 30000}}; assert.writeOK(master.getDB("test").foo.insert({x: 2}, options)); // lock secondary, to pause replication print("\nlock secondary"); diff --git a/jstests/replsets/stepdown_catch_up_opt.js b/jstests/replsets/stepdown_catch_up_opt.js index 304927a7838..48bd11adde1 100644 --- a/jstests/replsets/stepdown_catch_up_opt.js +++ b/jstests/replsets/stepdown_catch_up_opt.js @@ -26,10 +26,10 @@ var stringNotIntCode = 14; // Expect a failure with a string argument. - assert.commandFailedWithCode(primary.getDB('admin').runCommand( - {replSetStepDown: 10, secondaryCatchUpPeriodSecs: 'STR'}), - stringNotIntCode, - 'Expected string argument to secondaryCatchupPeriodSecs to fail.'); + assert.commandFailedWithCode( + primary.getDB('admin').runCommand({replSetStepDown: 10, secondaryCatchUpPeriodSecs: 'STR'}), + stringNotIntCode, + 'Expected string argument to secondaryCatchupPeriodSecs to fail.'); // Expect a failure with a longer secondaryCatchupPeriodSecs than the stepdown period. assert.commandFailedWithCode( @@ -44,8 +44,8 @@ 'Failed to configure rsSyncApplyStop failpoint.'); function disableFailPoint() { - assert.commandWorked(secondary.getDB('admin') - .runCommand({configureFailPoint: 'rsSyncApplyStop', mode: 'off'}), + assert.commandWorked(secondary.getDB('admin').runCommand( + {configureFailPoint: 'rsSyncApplyStop', mode: 'off'}), 'Failed to disable rsSyncApplyStop failpoint.'); } @@ -60,8 +60,7 @@ jsTestLog('Try to step down.'); var startTime = new Date(); assert.commandFailedWithCode( - primary.getDB('admin') - .runCommand({replSetStepDown: 10, secondaryCatchUpPeriodSecs: 1}), + primary.getDB('admin').runCommand({replSetStepDown: 10, secondaryCatchUpPeriodSecs: 1}), noCaughtUpSecondariesCode, 'Expected replSetStepDown to fail, since no secondaries should be caught up.'); var endTime = new Date(); diff --git a/jstests/replsets/stepdown_killop.js b/jstests/replsets/stepdown_killop.js index c5fc593239b..9185517e6c7 100644 --- a/jstests/replsets/stepdown_killop.js +++ b/jstests/replsets/stepdown_killop.js @@ -38,11 +38,11 @@ // do a write then ask the PRIMARY to stepdown jsTestLog("Initiating stepdown"); - assert.writeOK(primary.getDB(name) - .foo.insert({myDoc: true, x: 1}, {writeConcern: {w: 1, wtimeout: 60000}})); + assert.writeOK(primary.getDB(name).foo.insert({myDoc: true, x: 1}, + {writeConcern: {w: 1, wtimeout: 60000}})); var stepDownCmd = function() { - var res = db.getSiblingDB('admin') - .runCommand({replSetStepDown: 60, secondaryCatchUpPeriodSecs: 60}); + var res = db.getSiblingDB('admin').runCommand( + {replSetStepDown: 60, secondaryCatchUpPeriodSecs: 60}); assert.commandFailedWithCode(res, 11601 /*interrupted*/); }; var stepDowner = startParallelShell(stepDownCmd, primary.port); diff --git a/jstests/replsets/stepdown_long_wait_time.js b/jstests/replsets/stepdown_long_wait_time.js index 60e0fdb4247..8ef398224f2 100644 --- a/jstests/replsets/stepdown_long_wait_time.js +++ b/jstests/replsets/stepdown_long_wait_time.js @@ -32,9 +32,7 @@ 'Failed to configure rsSyncApplyStop failpoint.'); jsTestLog("do a write then ask the PRIMARY to stepdown"); - var options = { - writeConcern: {w: 1, wtimeout: 60000} - }; + var options = {writeConcern: {w: 1, wtimeout: 60000}}; assert.writeOK(primary.getDB(name).foo.insert({x: 1}, options)); var stepDownSecs = 60; var secondaryCatchUpPeriodSecs = 60; diff --git a/jstests/replsets/sync2.js b/jstests/replsets/sync2.js index 481f59a13d9..8624d913538 100644 --- a/jstests/replsets/sync2.js +++ b/jstests/replsets/sync2.js @@ -35,9 +35,7 @@ assert.soon(function() { replTest.awaitReplication(); jsTestLog("Checking that ops still replicate correctly"); -var option = { - writeConcern: {w: 5, wtimeout: 30000} -}; +var option = {writeConcern: {w: 5, wtimeout: 30000}}; // In PV0, this write can fail as a result of a bad spanning tree. If 2 was syncing from 4 prior to // bridging, it will not change sync sources and receive the write in time. This was not a problem // in 3.0 because the old version of mongobridge caused all the nodes to restart during diff --git a/jstests/replsets/tags.js b/jstests/replsets/tags.js index 55a0c4e2927..a079c4c9bb9 100644 --- a/jstests/replsets/tags.js +++ b/jstests/replsets/tags.js @@ -98,9 +98,7 @@ jsTestLog('Node ' + nodeId + ' (' + replTest.nodes[nodeId].host + ') should be primary.'); replTest.waitForState(replTest.nodes[nodeId], ReplSetTest.State.PRIMARY, 60 * 1000); primary = replTest.getPrimary(); - var writeConcern = { - writeConcern: {w: expectedWritableNodes, wtimeout: 30 * 1000} - }; + var writeConcern = {writeConcern: {w: expectedWritableNodes, wtimeout: 30 * 1000}}; assert.writeOK(primary.getDB('foo').bar.insert({x: 100}, writeConcern)); return primary; }; @@ -125,9 +123,7 @@ jsTestLog('partitions: nodes with each set of brackets [N1, N2, N3] form a complete network.'); jsTestLog('partitions: [0-1-2] [3] [4] (only nodes 0 and 1 can replicate from primary node 2'); - var doc = { - x: 1 - }; + var doc = {x: 1}; // This timeout should be shorter in duration than the server parameter maxSyncSourceLagSecs. // Some writes are expected to block for this 'timeout' duration before failing. @@ -140,9 +136,7 @@ primary = ensurePrimary(2, 3); jsTestLog('Non-existent write concern should be rejected.'); - options = { - writeConcern: {w: 'blahblah', wtimeout: timeout} - }; + options = {writeConcern: {w: 'blahblah', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); var result = assert.writeError(primary.getDB('foo').bar.insert(doc, options)); assert.neq(null, result.getWriteConcernError()); @@ -151,9 +145,7 @@ tojson(result.getWriteConcernError())); jsTestLog('Write concern "3 or 4" should fail - 3 and 4 are not connected to the primary.'); - var options = { - writeConcern: {w: '3 or 4', wtimeout: timeout} - }; + var options = {writeConcern: {w: '3 or 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); result = primary.getDB('foo').bar.insert(doc, options); assert.neq(null, result.getWriteConcernError()); @@ -166,16 +158,12 @@ jsTestLog('Write concern "3 or 4" should work - 4 is now connected to the primary ' + primary.host + ' via node 1 ' + replTest.nodes[1].host); - options = { - writeConcern: {w: '3 or 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 or 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "3 and 4" should fail - 3 is not connected to the primary.'); - options = { - writeConcern: {w: '3 and 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 and 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); result = assert.writeError(primary.getDB('foo').bar.insert(doc, options)); assert.neq(null, result.getWriteConcernError()); @@ -190,31 +178,23 @@ jsTestLog('31003 should sync from 31004 (31024)'); jsTestLog('Write concern "3 and 4" should work - ' + 'nodes 3 and 4 are connected to primary via node 1.'); - options = { - writeConcern: {w: '3 and 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 and 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "2" - writes to primary only.'); - options = { - writeConcern: {w: '2', wtimeout: 0} - }; + options = {writeConcern: {w: '2', wtimeout: 0}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "1 and 2"'); - options = { - writeConcern: {w: '1 and 2', wtimeout: 0} - }; + options = {writeConcern: {w: '1 and 2', wtimeout: 0}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "2 dc and 3 server"'); primary = ensurePrimary(2, 5); - options = { - writeConcern: {w: '2 dc and 3 server', wtimeout: timeout} - }; + options = {writeConcern: {w: '2 dc and 3 server', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); @@ -239,17 +219,13 @@ primary = ensurePrimary(1, 4); jsTestLog('Write concern "3 and 4" should still work with new primary node 1 ' + primary.host); - options = { - writeConcern: {w: '3 and 4', wtimeout: timeout} - }; + options = {writeConcern: {w: '3 and 4', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); assert.writeOK(primary.getDB('foo').bar.insert(doc, options)); jsTestLog('Write concern "2" should fail because node 2 ' + replTest.nodes[2].host + ' is down.'); - options = { - writeConcern: {w: '2', wtimeout: timeout} - }; + options = {writeConcern: {w: '2', wtimeout: timeout}}; assert.writeOK(primary.getDB('foo').bar.insert(doc)); result = assert.writeError(primary.getDB('foo').bar.insert(doc, options)); assert.neq(null, result.getWriteConcernError()); diff --git a/jstests/replsets/two_initsync.js b/jstests/replsets/two_initsync.js index 1f2b526d61e..a9d47eb3ff1 100644 --- a/jstests/replsets/two_initsync.js +++ b/jstests/replsets/two_initsync.js @@ -56,10 +56,8 @@ doTest = function(signal) { var a = replTest.getPrimary().getDB("two"); for (var i = 0; i < 20000; i++) - a.coll.insert({ - i: i, - s: "a b" - }); + a.coll.insert( + {i: i, s: "a b"}); // Start a second node var second = replTest.add(); diff --git a/jstests/replsets/user_management_wc.js b/jstests/replsets/user_management_wc.js index 691a2520544..3aa186df277 100644 --- a/jstests/replsets/user_management_wc.js +++ b/jstests/replsets/user_management_wc.js @@ -132,10 +132,7 @@ load('jstests/multiVersion/libs/auth_helpers.js'); } function testValidWriteConcern(cmd) { - cmd.req.writeConcern = { - w: 'majority', - wtimeout: 25000 - }; + cmd.req.writeConcern = {w: 'majority', wtimeout: 25000}; jsTest.log("Testing " + tojson(cmd.req)); dropUsersAndRoles(); @@ -148,9 +145,7 @@ load('jstests/multiVersion/libs/auth_helpers.js'); } function testInvalidWriteConcern(cmd) { - cmd.req.writeConcern = { - w: 15 - }; + cmd.req.writeConcern = {w: 15}; jsTest.log("Testing " + tojson(cmd.req)); dropUsersAndRoles(); diff --git a/jstests/serial_run/election_timing.js b/jstests/serial_run/election_timing.js index 2fe83be02ed..16a3bf4e519 100644 --- a/jstests/serial_run/election_timing.js +++ b/jstests/serial_run/election_timing.js @@ -130,8 +130,8 @@ }); var resAvg = Array.avg(allResults); - var resMin = Math.min(... allResults); - var resMax = Math.max(... allResults); + var resMin = Math.min(...allResults); + var resMax = Math.max(...allResults); var resStdDev = Array.stdDev(allResults); jsTestLog("Results: " + tc.name + " Average over " + allResults.length + " runs: " + diff --git a/jstests/sharding/SERVER-7379.js b/jstests/sharding/SERVER-7379.js index bdf311cbf6e..a98161f101e 100644 --- a/jstests/sharding/SERVER-7379.js +++ b/jstests/sharding/SERVER-7379.js @@ -7,11 +7,7 @@ st.adminCommand( var db = st.s.getDB('test'); var offerChange = db.getCollection('offerChange'); -var testDoc = { - "_id": 123, - "categoryId": 9881, - "store": "NEW" -}; +var testDoc = {"_id": 123, "categoryId": 9881, "store": "NEW"}; offerChange.remove({}, false); offerChange.insert(testDoc); diff --git a/jstests/sharding/addshard2.js b/jstests/sharding/addshard2.js index 7af23a4ab5b..6579d89686d 100644 --- a/jstests/sharding/addshard2.js +++ b/jstests/sharding/addshard2.js @@ -55,13 +55,15 @@ assert.eq("add_shard2_rs1", shard._id, "t2 name"); // step 3. replica set w/ name given - assert(s.admin.runCommand({ - "addshard": "add_shard2_rs2/" + getHostName() + ":" + master2.port, - "name": "myshard" - }).ok, + assert(s.admin + .runCommand({ + "addshard": "add_shard2_rs2/" + getHostName() + ":" + master2.port, + "name": "myshard" + }) + .ok, "failed to add shard in step 4"); - shard = s.getDB("config") - .shards.findOne({"_id": {"$nin": ["shard0000", "bar", "add_shard2_rs1"]}}); + shard = + s.getDB("config").shards.findOne({"_id": {"$nin": ["shard0000", "bar", "add_shard2_rs1"]}}); assert(shard, "shard wasn't found"); assert.eq("myshard", shard._id, "t3 name"); @@ -77,15 +79,18 @@ // step 5. replica set w/ a wrong host var portWithoutHostRunning = allocatePort(); - assert(!s.admin.runCommand( - {addshard: "add_shard2_rs2/NonExistingHost:" + portWithoutHostRunning}).ok, - "accepted bad hostname in step 5"); + assert( + !s.admin.runCommand({addshard: "add_shard2_rs2/NonExistingHost:" + portWithoutHostRunning}) + .ok, + "accepted bad hostname in step 5"); // step 6. replica set w/ mixed wrong/right hosts - assert(!s.admin.runCommand({ - addshard: "add_shard2_rs2/" + getHostName() + ":" + master2.port + ",foo:" + - portWithoutHostRunning - }).ok, + assert(!s.admin + .runCommand({ + addshard: "add_shard2_rs2/" + getHostName() + ":" + master2.port + ",foo:" + + portWithoutHostRunning + }) + .ok, "accepted bad hostname in step 6"); // Cannot add invalid stand alone host. diff --git a/jstests/sharding/auth.js b/jstests/sharding/auth.js index ea3ed974cc5..f3fe71a5950 100644 --- a/jstests/sharding/auth.js +++ b/jstests/sharding/auth.js @@ -3,23 +3,11 @@ (function() { 'use strict'; - var adminUser = { - db: "admin", - username: "foo", - password: "bar" - }; - - var testUser = { - db: "test", - username: "bar", - password: "baz" - }; - - var testUserReadOnly = { - db: "test", - username: "sad", - password: "bat" - }; + var adminUser = {db: "admin", username: "foo", password: "bar"}; + + var testUser = {db: "test", username: "bar", password: "baz"}; + + var testUserReadOnly = {db: "test", username: "sad", password: "bat"}; function login(userObj, thingToUse) { if (!thingToUse) { @@ -58,9 +46,11 @@ } print("Configuration: Add user " + tojson(adminUser)); - s.getDB(adminUser.db) - .createUser( - {user: adminUser.username, pwd: adminUser.password, roles: jsTest.adminUserRoles}); + s.getDB(adminUser.db).createUser({ + user: adminUser.username, + pwd: adminUser.password, + roles: jsTest.adminUserRoles + }); login(adminUser); // Set the chunk size, disable the secondary throttle (so the test doesn't run so slow) @@ -80,11 +70,9 @@ d1.initiate(); print("d1 initiated"); - var shardName = authutil.asCluster(d1.nodes, - "jstests/libs/key2", - function() { - return getShardName(d1); - }); + var shardName = authutil.asCluster(d1.nodes, "jstests/libs/key2", function() { + return getShardName(d1); + }); print("adding shard w/out auth " + shardName); logout(adminUser); @@ -124,15 +112,16 @@ d1.waitForState(d1.getSecondaries(), ReplSetTest.State.SECONDARY, 5 * 60 * 1000); - s.getDB(testUser.db) - .createUser( - {user: testUser.username, pwd: testUser.password, roles: jsTest.basicUserRoles}); - s.getDB(testUserReadOnly.db) - .createUser({ - user: testUserReadOnly.username, - pwd: testUserReadOnly.password, - roles: jsTest.readOnlyUserRoles - }); + s.getDB(testUser.db).createUser({ + user: testUser.username, + pwd: testUser.password, + roles: jsTest.basicUserRoles + }); + s.getDB(testUserReadOnly.db).createUser({ + user: testUserReadOnly.username, + pwd: testUserReadOnly.password, + roles: jsTest.readOnlyUserRoles + }); logout(adminUser); @@ -162,11 +151,9 @@ d2.initiate(); d2.awaitSecondaryNodes(); - shardName = authutil.asCluster(d2.nodes, - "jstests/libs/key1", - function() { - return getShardName(d2); - }); + shardName = authutil.asCluster(d2.nodes, "jstests/libs/key1", function() { + return getShardName(d2); + }); print("adding shard " + shardName); login(adminUser); @@ -254,16 +241,12 @@ d1.waitForState(d1.getSecondaries(), ReplSetTest.State.SECONDARY, 5 * 60 * 1000); d2.waitForState(d2.getSecondaries(), ReplSetTest.State.SECONDARY, 5 * 60 * 1000); - authutil.asCluster(d1.nodes, - "jstests/libs/key1", - function() { - d1.awaitReplication(120000); - }); - authutil.asCluster(d2.nodes, - "jstests/libs/key1", - function() { - d2.awaitReplication(120000); - }); + authutil.asCluster(d1.nodes, "jstests/libs/key1", function() { + d1.awaitReplication(120000); + }); + authutil.asCluster(d2.nodes, "jstests/libs/key1", function() { + d2.awaitReplication(120000); + }); // add admin on shard itself, hack to prevent localhost auth bypass d1.getPrimary() diff --git a/jstests/sharding/authCommands.js b/jstests/sharding/authCommands.js index 03e77848974..deb6512a6b0 100644 --- a/jstests/sharding/authCommands.js +++ b/jstests/sharding/authCommands.js @@ -3,10 +3,7 @@ */ var doTest = function() { - var rsOpts = { - oplogSize: 10, - useHostname: false - }; + var rsOpts = {oplogSize: 10, useHostname: false}; var st = new ShardingTest({ keyFile: 'jstests/libs/key1', shards: 2, @@ -132,12 +129,10 @@ var doTest = function() { assert.eq(100, res.results.length); assert.eq(45, res.results[0].value); - res = checkCommandSucceeded( - testDB, - { - aggregate: 'foo', - pipeline: [{$project: {j: 1}}, {$group: {_id: 'j', sum: {$sum: '$j'}}}] - }); + res = checkCommandSucceeded(testDB, { + aggregate: 'foo', + pipeline: [{$project: {j: 1}}, {$group: {_id: 'j', sum: {$sum: '$j'}}}] + }); assert.eq(4500, res.result[0].sum); } else { print("Checking read operations, should fail"); @@ -148,12 +143,10 @@ var doTest = function() { checkCommandFailed(testDB, {collstats: 'foo'}); checkCommandFailed(testDB, {mapreduce: 'foo', map: map, reduce: reduce, out: {inline: 1}}); - checkCommandFailed( - testDB, - { - aggregate: 'foo', - pipeline: [{$project: {j: 1}}, {$group: {_id: 'j', sum: {$sum: '$j'}}}] - }); + checkCommandFailed(testDB, { + aggregate: 'foo', + pipeline: [{$project: {j: 1}}, {$group: {_id: 'j', sum: {$sum: '$j'}}}] + }); } }; @@ -233,10 +226,7 @@ var doTest = function() { checkCommandSucceeded(adminDB, {isdbgrid: 1}); checkCommandSucceeded(adminDB, {ismaster: 1}); checkCommandFailed(adminDB, {split: 'test.foo', find: {i: 1, j: 1}}); - chunkKey = { - i: {$minKey: 1}, - j: {$minKey: 1} - }; + chunkKey = {i: {$minKey: 1}, j: {$minKey: 1}}; checkCommandFailed( adminDB, {moveChunk: 'test.foo', find: chunkKey, to: st.rs1.name, _waitForDelete: true}); diff --git a/jstests/sharding/auth_add_shard.js b/jstests/sharding/auth_add_shard.js index 4f0fec6de83..b24afd0172c 100644 --- a/jstests/sharding/auth_add_shard.js +++ b/jstests/sharding/auth_add_shard.js @@ -11,11 +11,7 @@ } // admin user object - var adminUser = { - db: "admin", - username: "foo", - password: "bar" - }; + var adminUser = {db: "admin", username: "foo", password: "bar"}; // set up a 2 shard cluster with keyfile var st = new ShardingTest( @@ -28,9 +24,11 @@ // add the admin user print("adding user"); - mongos.getDB(adminUser.db) - .createUser( - {user: adminUser.username, pwd: adminUser.password, roles: jsTest.adminUserRoles}); + mongos.getDB(adminUser.db).createUser({ + user: adminUser.username, + pwd: adminUser.password, + roles: jsTest.adminUserRoles + }); // login as admin user login(adminUser); diff --git a/jstests/sharding/auth_no_config_primary.js b/jstests/sharding/auth_no_config_primary.js index a4be8806f66..3bb1ea1cf4c 100644 --- a/jstests/sharding/auth_no_config_primary.js +++ b/jstests/sharding/auth_no_config_primary.js @@ -33,8 +33,8 @@ assert.eq('world', res.hello); // Test authenticate through new mongos. - var otherMongos = MongoRunner.runMongos( - {keyFile: "jstests/libs/key1", configdb: st.s.savedOptions.configdb}); + var otherMongos = + MongoRunner.runMongos({keyFile: "jstests/libs/key1", configdb: st.s.savedOptions.configdb}); assert.commandFailedWithCode(otherMongos.getDB('test').runCommand({find: 'user'}), ErrorCodes.Unauthorized); diff --git a/jstests/sharding/auth_slaveok_routing.js b/jstests/sharding/auth_slaveok_routing.js index a01314fe405..c950730c799 100644 --- a/jstests/sharding/auth_slaveok_routing.js +++ b/jstests/sharding/auth_slaveok_routing.js @@ -30,9 +30,7 @@ function doesRouteToSec(coll, query) { return cmdRes.secondary; } -var rsOpts = { - oplogSize: 50 -}; +var rsOpts = {oplogSize: 50}; var st = new ShardingTest( {keyFile: 'jstests/libs/key1', shards: 1, rs: rsOpts, other: {nopreallocj: 1}}); diff --git a/jstests/sharding/authmr.js b/jstests/sharding/authmr.js index 6484c729474..67f87fc59b4 100644 --- a/jstests/sharding/authmr.js +++ b/jstests/sharding/authmr.js @@ -10,12 +10,8 @@ var adminUser = { user: "admin", pwd: "a", - roles: [ - "readWriteAnyDatabase", - "dbAdminAnyDatabase", - "userAdminAnyDatabase", - "clusterAdmin" - ] + roles: + ["readWriteAnyDatabase", "dbAdminAnyDatabase", "userAdminAnyDatabase", "clusterAdmin"] }; var test1User = { diff --git a/jstests/sharding/authwhere.js b/jstests/sharding/authwhere.js index df27078784b..f9af413f470 100644 --- a/jstests/sharding/authwhere.js +++ b/jstests/sharding/authwhere.js @@ -10,12 +10,8 @@ var adminUser = { user: "admin", pwd: "a", - roles: [ - "readWriteAnyDatabase", - "dbAdminAnyDatabase", - "userAdminAnyDatabase", - "clusterAdmin" - ] + roles: + ["readWriteAnyDatabase", "dbAdminAnyDatabase", "userAdminAnyDatabase", "clusterAdmin"] }; var test1Reader = { diff --git a/jstests/sharding/auto2.js b/jstests/sharding/auto2.js index 3d21559f8d6..3c8eb168d7b 100644 --- a/jstests/sharding/auto2.js +++ b/jstests/sharding/auto2.js @@ -16,15 +16,14 @@ var i = 0; for (var j = 0; j < 30; j++) { - print("j:" + j + " : " + - Date.timeFunc(function() { - var bulk = coll.initializeUnorderedBulkOp(); - for (var k = 0; k < 100; k++) { - bulk.insert({num: i, s: bigString}); - i++; - } - assert.writeOK(bulk.execute()); - })); + print("j:" + j + " : " + Date.timeFunc(function() { + var bulk = coll.initializeUnorderedBulkOp(); + for (var k = 0; k < 100; k++) { + bulk.insert({num: i, s: bigString}); + i++; + } + assert.writeOK(bulk.execute()); + })); } s.startBalancer(); @@ -92,8 +91,8 @@ print("checkpoint C"); assert(Array.unique(s.config.chunks.find().toArray().map(function(z) { - return z.shard; - })).length == 2, + return z.shard; + })).length == 2, "should be using both servers"); for (i = 0; i < 100; i++) { diff --git a/jstests/sharding/balance_repl.js b/jstests/sharding/balance_repl.js index 433e8167829..39c28b46448 100644 --- a/jstests/sharding/balance_repl.js +++ b/jstests/sharding/balance_repl.js @@ -12,10 +12,16 @@ other: { chunkSize: 1, rs0: { - nodes: [{rsConfig: {votes: 1}}, {rsConfig: {priority: 0, votes: 0}}, ], + nodes: [ + {rsConfig: {votes: 1}}, + {rsConfig: {priority: 0, votes: 0}}, + ], }, rs1: { - nodes: [{rsConfig: {votes: 1}}, {rsConfig: {priority: 0, votes: 0}}, ], + nodes: [ + {rsConfig: {votes: 1}}, + {rsConfig: {priority: 0, votes: 0}}, + ], } } }); diff --git a/jstests/sharding/batch_write_command_sharded.js b/jstests/sharding/batch_write_command_sharded.js index 9c0dc61d21d..884d5bb85bb 100644 --- a/jstests/sharding/batch_write_command_sharded.js +++ b/jstests/sharding/batch_write_command_sharded.js @@ -65,10 +65,7 @@ assert.commandWorked(coll.getMongo().getDB("admin").runCommand({setParameter: 1, logLevel: 4})); coll.remove({}); - request = { - insert: coll.getName(), - documents: documents - }; + request = {insert: coll.getName(), documents: documents}; printjson(result = coll.runCommand(request)); assert(result.ok); assert.eq(1000, result.n); diff --git a/jstests/sharding/cleanup_orphaned_cmd_during_movechunk_hashed.js b/jstests/sharding/cleanup_orphaned_cmd_during_movechunk_hashed.js index 242c1f28c09..e928eaebcf2 100644 --- a/jstests/sharding/cleanup_orphaned_cmd_during_movechunk_hashed.js +++ b/jstests/sharding/cleanup_orphaned_cmd_during_movechunk_hashed.js @@ -31,11 +31,7 @@ load('./jstests/libs/cleanup_orphaned_util.js'); var found = false; for (var i = 0; i < 10000; i++) { - var doc = - { - key: ObjectId() - }, - hash = mongos.adminCommand({_hashBSONElement: doc.key}).out; + var doc = {key: ObjectId()}, hash = mongos.adminCommand({_hashBSONElement: doc.key}).out; print('doc.key ' + doc.key + ' hashes to ' + hash); diff --git a/jstests/sharding/cleanup_orphaned_cmd_prereload.js b/jstests/sharding/cleanup_orphaned_cmd_prereload.js index 7155baea970..05fbd8b741a 100644 --- a/jstests/sharding/cleanup_orphaned_cmd_prereload.js +++ b/jstests/sharding/cleanup_orphaned_cmd_prereload.js @@ -18,12 +18,14 @@ jsTest.log("Moving some chunks to shard1..."); assert(admin.runCommand({split: coll + "", middle: {_id: 0}}).ok); assert(admin.runCommand({split: coll + "", middle: {_id: 1}}).ok); -assert(admin.runCommand( - {moveChunk: coll + "", find: {_id: 0}, to: shards[1]._id, _waitForDelete: true}) - .ok); -assert(admin.runCommand( - {moveChunk: coll + "", find: {_id: 1}, to: shards[1]._id, _waitForDelete: true}) - .ok); +assert( + admin + .runCommand({moveChunk: coll + "", find: {_id: 0}, to: shards[1]._id, _waitForDelete: true}) + .ok); +assert( + admin + .runCommand({moveChunk: coll + "", find: {_id: 1}, to: shards[1]._id, _waitForDelete: true}) + .ok); var metadata = st.shard1.getDB("admin").runCommand({getShardVersion: coll + "", fullMetadata: true}).metadata; @@ -52,9 +54,10 @@ assert.eq(metadata.shardVersion.t, 0); assert.neq(metadata.collVersion.t, 0); assert.eq(metadata.pending.length, 0); -assert(admin.runCommand( - {moveChunk: coll + "", find: {_id: 1}, to: shards[0]._id, _waitForDelete: true}) - .ok); +assert( + admin + .runCommand({moveChunk: coll + "", find: {_id: 1}, to: shards[0]._id, _waitForDelete: true}) + .ok); var metadata = st.shard0.getDB("admin").runCommand({getShardVersion: coll + "", fullMetadata: true}).metadata; diff --git a/jstests/sharding/coll_epoch_test0.js b/jstests/sharding/coll_epoch_test0.js index 0ec0a5d3201..49fe99914a0 100644 --- a/jstests/sharding/coll_epoch_test0.js +++ b/jstests/sharding/coll_epoch_test0.js @@ -21,19 +21,18 @@ config.shards.find().forEach(function(doc) { var createdEpoch = null; var checkEpochs = function() { - config.chunks.find({ns: coll + ""}) - .forEach(function(chunk) { - - // Make sure the epochs exist, are non-zero, and are consistent - assert(chunk.lastmodEpoch); - print(chunk.lastmodEpoch + ""); - assert.neq(chunk.lastmodEpoch + "", "000000000000000000000000"); - if (createdEpoch == null) - createdEpoch = chunk.lastmodEpoch; - else - assert.eq(createdEpoch, chunk.lastmodEpoch); - - }); + config.chunks.find({ns: coll + ""}).forEach(function(chunk) { + + // Make sure the epochs exist, are non-zero, and are consistent + assert(chunk.lastmodEpoch); + print(chunk.lastmodEpoch + ""); + assert.neq(chunk.lastmodEpoch + "", "000000000000000000000000"); + if (createdEpoch == null) + createdEpoch = chunk.lastmodEpoch; + else + assert.eq(createdEpoch, chunk.lastmodEpoch); + + }); }; checkEpochs(); diff --git a/jstests/sharding/commands_that_write_accept_wc_configRS.js b/jstests/sharding/commands_that_write_accept_wc_configRS.js index c8dd99fb06d..4ae7071da82 100644 --- a/jstests/sharding/commands_that_write_accept_wc_configRS.js +++ b/jstests/sharding/commands_that_write_accept_wc_configRS.js @@ -59,8 +59,8 @@ load('jstests/multiVersion/libs/auth_helpers.js'); shardCollectionWithChunks(st, coll); adminDB.system.version.update( {_id: "authSchema"}, {"currentVersion": 3}, {upsert: true}); - localDB.getSiblingDB('admin') - .system.version.update({_id: "authSchema"}, {"currentVersion": 3}, {upsert: true}); + localDB.getSiblingDB('admin').system.version.update( + {_id: "authSchema"}, {"currentVersion": 3}, {upsert: true}); db.createUser({user: 'user1', pwd: 'pass', roles: jsTest.basicUserRoles}); assert(db.auth({mechanism: 'MONGODB-CR', user: 'user1', pwd: 'pass'})); @@ -238,10 +238,7 @@ load('jstests/multiVersion/libs/auth_helpers.js'); var setupFunc = cmd.setupFunc; var confirmFunc = cmd.confirmFunc; - req.writeConcern = { - w: 'majority', - wtimeout: 25000 - }; + req.writeConcern = {w: 'majority', wtimeout: 25000}; jsTest.log("Testing " + tojson(req)); dropTestData(); diff --git a/jstests/sharding/commands_that_write_accept_wc_shards.js b/jstests/sharding/commands_that_write_accept_wc_shards.js index f5bd55550e2..e584b4ee264 100644 --- a/jstests/sharding/commands_that_write_accept_wc_shards.js +++ b/jstests/sharding/commands_that_write_accept_wc_shards.js @@ -404,10 +404,7 @@ load('jstests/libs/write_concern_util.js'); }); function testValidWriteConcern(cmd) { - cmd.req.writeConcern = { - w: 'majority', - wtimeout: 25000 - }; + cmd.req.writeConcern = {w: 'majority', wtimeout: 25000}; jsTest.log("Testing " + tojson(cmd.req)); dropTestDatabase(); @@ -420,9 +417,7 @@ load('jstests/libs/write_concern_util.js'); } function testInvalidWriteConcern(cmd) { - cmd.req.writeConcern = { - w: 'invalid' - }; + cmd.req.writeConcern = {w: 'invalid'}; jsTest.log("Testing " + tojson(cmd.req)); dropTestDatabase(); diff --git a/jstests/sharding/conf_server_write_concern.js b/jstests/sharding/conf_server_write_concern.js index c4e08939548..d6ca0e006e0 100644 --- a/jstests/sharding/conf_server_write_concern.js +++ b/jstests/sharding/conf_server_write_concern.js @@ -10,12 +10,12 @@ function writeToConfigTest() { {_id: 'balancer'}, {$set: {stopped: true}}, {writeConcern: {w: 'majority'}})); // w:1 should still work - it gets automatically upconverted to w:majority - assert.writeOK(confDB.settings.update( - {_id: 'balancer'}, {$set: {stopped: true}}, {writeConcern: {w: 1}})); + assert.writeOK( + confDB.settings.update({_id: 'balancer'}, {$set: {stopped: true}}, {writeConcern: {w: 1}})); // Write concerns other than w:1 and w:majority should fail. - assert.writeError(confDB.settings.update( - {_id: 'balancer'}, {$set: {stopped: true}}, {writeConcern: {w: 2}})); + assert.writeError( + confDB.settings.update({_id: 'balancer'}, {$set: {stopped: true}}, {writeConcern: {w: 2}})); st.stop(); } diff --git a/jstests/sharding/covered_shard_key_indexes.js b/jstests/sharding/covered_shard_key_indexes.js index 307dc241d9f..98168e7dccb 100644 --- a/jstests/sharding/covered_shard_key_indexes.js +++ b/jstests/sharding/covered_shard_key_indexes.js @@ -46,10 +46,9 @@ assert.eq(0, coll.find({a: true}, {_id: 1, a: 1}).explain(true).executionStats.t assert.commandWorked(coll.dropIndexes()); assert.commandWorked(coll.ensureIndex({a: 1, b: 1, _id: 1})); assert.eq(1, coll.find({a: true, b: true}).explain(true).executionStats.totalDocsExamined); -assert.eq(0, - coll.find({a: true, b: true}, {_id: 1, a: 1}) - .explain(true) - .executionStats.totalDocsExamined); +assert.eq( + 0, + coll.find({a: true, b: true}, {_id: 1, a: 1}).explain(true).executionStats.totalDocsExamined); // // @@ -126,20 +125,18 @@ assert.writeOK(coll.insert({_id: true, a: {b: true}, c: true})); // Index without shard key query - not covered assert.commandWorked(coll.ensureIndex({c: 1})); assert.eq(1, coll.find({c: true}).explain(true).executionStats.totalDocsExamined); -assert.eq(1, - coll.find({c: true}, {_id: 0, 'a.b': 1, c: 1}) - .explain(true) - .executionStats.totalDocsExamined); +assert.eq( + 1, + coll.find({c: true}, {_id: 0, 'a.b': 1, c: 1}).explain(true).executionStats.totalDocsExamined); // // Index with shard key query - nested query not covered even when projecting assert.commandWorked(coll.dropIndex({c: 1})); assert.commandWorked(coll.ensureIndex({c: 1, 'a.b': 1})); assert.eq(1, coll.find({c: true}).explain(true).executionStats.totalDocsExamined); -assert.eq(1, - coll.find({c: true}, {_id: 0, 'a.b': 1, c: 1}) - .explain(true) - .executionStats.totalDocsExamined); +assert.eq( + 1, + coll.find({c: true}, {_id: 0, 'a.b': 1, c: 1}).explain(true).executionStats.totalDocsExamined); // // diff --git a/jstests/sharding/delete_during_migrate.js b/jstests/sharding/delete_during_migrate.js index 982b0c00787..3926d180acb 100644 --- a/jstests/sharding/delete_during_migrate.js +++ b/jstests/sharding/delete_during_migrate.js @@ -38,8 +38,8 @@ startMongoProgramNoConnect("mongo", dbname); // migrate while deletions are happening -var moveResult = s.adminCommand( - {moveChunk: ns, find: {a: 1}, to: st.getOther(st.getPrimaryShard(dbname)).name}); +var moveResult = + s.adminCommand({moveChunk: ns, find: {a: 1}, to: st.getOther(st.getPrimaryShard(dbname)).name}); // check if migration worked assert(moveResult.ok, "migration didn't work while doing deletes"); diff --git a/jstests/sharding/drop_sharded_db.js b/jstests/sharding/drop_sharded_db.js index 962ff84fc40..9a0a56ca245 100644 --- a/jstests/sharding/drop_sharded_db.js +++ b/jstests/sharding/drop_sharded_db.js @@ -21,9 +21,7 @@ dbC.getCollection("data" + (i % numColls)).insert({_id: i}); } - var key = { - _id: 1 - }; + var key = {_id: 1}; for (var i = 0; i < numColls; i++) { st.shardColl(dbA.getCollection("data" + i), key); st.shardColl(dbB.getCollection("data" + i), key); diff --git a/jstests/sharding/empty_doc_results.js b/jstests/sharding/empty_doc_results.js index be63f509532..2038a27c538 100644 --- a/jstests/sharding/empty_doc_results.js +++ b/jstests/sharding/empty_doc_results.js @@ -2,10 +2,7 @@ // Verifies that mongos correctly handles empty documents when all fields are projected out // -var options = { - mongosOptions: {binVersion: ""}, - shardOptions: {binVersion: ""} -}; +var options = {mongosOptions: {binVersion: ""}, shardOptions: {binVersion: ""}}; var st = new ShardingTest({shards: 2, other: options}); diff --git a/jstests/sharding/explain_cmd.js b/jstests/sharding/explain_cmd.js index 767e26c7eb2..c638fccbced 100644 --- a/jstests/sharding/explain_cmd.js +++ b/jstests/sharding/explain_cmd.js @@ -50,10 +50,8 @@ assert.eq(2, explain.queryPlanner.winningPlan.shards.length); assert.eq(2, explain.executionStats.executionStages.shards.length); // An explain of a command that doesn't exist should fail gracefully. -explain = db.runCommand({ - explain: {nonexistent: collSharded.getName(), query: {b: 1}}, - verbosity: "allPlansExecution" -}); +explain = db.runCommand( + {explain: {nonexistent: collSharded.getName(), query: {b: 1}}, verbosity: "allPlansExecution"}); printjson(explain); assert.commandFailed(explain); diff --git a/jstests/sharding/explain_find_and_modify_sharded.js b/jstests/sharding/explain_find_and_modify_sharded.js index 7c1b10321c2..62ffa2d35f8 100644 --- a/jstests/sharding/explain_find_and_modify_sharded.js +++ b/jstests/sharding/explain_find_and_modify_sharded.js @@ -12,9 +12,7 @@ st.stopBalancer(); var testDB = st.s.getDB('test'); - var shardKey = { - a: 1 - }; + var shardKey = {a: 1}; // Create a collection with an index on the intended shard key. var shardedColl = testDB.getCollection(collName); diff --git a/jstests/sharding/explain_read_pref.js b/jstests/sharding/explain_read_pref.js index cdf1d1e74a4..8ac4fc4ff49 100644 --- a/jstests/sharding/explain_read_pref.js +++ b/jstests/sharding/explain_read_pref.js @@ -32,28 +32,28 @@ var testAllModes = function(conn, isMongos) { // { tag: 'two' } so we can test the interaction of modes and tags. Test // a bunch of combinations. [ - // mode, tagSets, expectedHost - ['primary', undefined, false], - ['primary', [{}], false], + // mode, tagSets, expectedHost + ['primary', undefined, false], + ['primary', [{}], false], - ['primaryPreferred', undefined, false], - ['primaryPreferred', [{tag: 'one'}], false], - // Correctly uses primary and ignores the tag - ['primaryPreferred', [{tag: 'two'}], false], + ['primaryPreferred', undefined, false], + ['primaryPreferred', [{tag: 'one'}], false], + // Correctly uses primary and ignores the tag + ['primaryPreferred', [{tag: 'two'}], false], - ['secondary', undefined, true], - ['secondary', [{tag: 'two'}], true], - ['secondary', [{tag: 'doesntexist'}, {}], true], - ['secondary', [{tag: 'doesntexist'}, {tag: 'two'}], true], + ['secondary', undefined, true], + ['secondary', [{tag: 'two'}], true], + ['secondary', [{tag: 'doesntexist'}, {}], true], + ['secondary', [{tag: 'doesntexist'}, {tag: 'two'}], true], - ['secondaryPreferred', undefined, true], - ['secondaryPreferred', [{tag: 'one'}], false], - ['secondaryPreferred', [{tag: 'two'}], true], + ['secondaryPreferred', undefined, true], + ['secondaryPreferred', [{tag: 'one'}], false], + ['secondaryPreferred', [{tag: 'two'}], true], - // We don't have a way to alter ping times so we can't predict where an - // untagged 'nearest' command should go, hence only test with tags. - ['nearest', [{tag: 'one'}], false], - ['nearest', [{tag: 'two'}], true] + // We don't have a way to alter ping times so we can't predict where an + // untagged 'nearest' command should go, hence only test with tags. + ['nearest', [{tag: 'one'}], false], + ['nearest', [{tag: 'two'}], true] ].forEach(function(args) { var mode = args[0], tagSets = args[1], secExpected = args[2]; @@ -101,14 +101,8 @@ ReplSetTest.awaitRSClientHosts(st.s, st.rs0.nodes); // Tag primary with { dc: 'ny', tag: 'one' }, secondary with { dc: 'ny', tag: 'two' } var primary = st.rs0.getPrimary(); var secondary = st.rs0.getSecondary(); -var PRIMARY_TAG = { - dc: 'ny', - tag: 'one' -}; -var SECONDARY_TAG = { - dc: 'ny', - tag: 'two' -}; +var PRIMARY_TAG = {dc: 'ny', tag: 'one'}; +var SECONDARY_TAG = {dc: 'ny', tag: 'two'}; var rsConfig = primary.getDB("local").system.replset.findOne(); jsTest.log('got rsconf ' + tojson(rsConfig)); diff --git a/jstests/sharding/fair_balancer_round.js b/jstests/sharding/fair_balancer_round.js index 90fc345c8cb..6b477efac78 100644 --- a/jstests/sharding/fair_balancer_round.js +++ b/jstests/sharding/fair_balancer_round.js @@ -2,9 +2,7 @@ // Tests that a balancer round loads newly sharded collection data // -var options = { - mongosOptions: {verbose: 1} -}; +var options = {mongosOptions: {verbose: 1}}; var st = new ShardingTest({shards: 2, mongos: 2, other: options}); @@ -30,8 +28,8 @@ for (var i = 0; i < numSplits; i++) { st.stopMongos(0); // Start balancer, which lets the stale mongos balance -assert.writeOK(staleMongos.getDB("config") - .settings.update({_id: "balancer"}, {$set: {stopped: false}}, true)); +assert.writeOK( + staleMongos.getDB("config").settings.update({_id: "balancer"}, {$set: {stopped: false}}, true)); // Make sure we eventually start moving chunks assert.soon(function() { diff --git a/jstests/sharding/features1.js b/jstests/sharding/features1.js index dc547ddad74..d545ea096d6 100644 --- a/jstests/sharding/features1.js +++ b/jstests/sharding/features1.js @@ -182,13 +182,15 @@ printjson(db.foo6.getIndexes()); assert.eq(2, - db.foo6.group({ - key: {a: 1}, - initial: {count: 0}, - reduce: function(z, prev) { - prev.count++; - } - }).length); + db.foo6 + .group({ + key: {a: 1}, + initial: {count: 0}, + reduce: function(z, prev) { + prev.count++; + } + }) + .length); assert.eq(3, db.foo6.find().count()); assert(s.admin.runCommand({shardcollection: "test.foo6", key: {a: 1}}).ok); @@ -202,11 +204,8 @@ // Remove when SERVER-10232 is fixed assert.soon(function() { - var cmdRes = s.admin.runCommand({ - movechunk: "test.foo6", - find: {a: 3}, - to: s.getOther(s.getPrimaryShard("test")).name - }); + var cmdRes = s.admin.runCommand( + {movechunk: "test.foo6", find: {a: 3}, to: s.getOther(s.getPrimaryShard("test")).name}); return cmdRes.ok; }, 'move chunk test.foo6', 60000, 1000); diff --git a/jstests/sharding/features2.js b/jstests/sharding/features2.js index 010289ac1cc..fd28882213b 100644 --- a/jstests/sharding/features2.js +++ b/jstests/sharding/features2.js @@ -86,9 +86,7 @@ for (var i = 0; i < values.length; i++) { total += values[i].count; } - return { - count: total - }; + return {count: total}; }; doMR = function(n) { @@ -146,12 +144,7 @@ doMR("after extra split"); - cmd = { - mapreduce: "mr", - map: "emit( ", - reduce: "fooz + ", - out: "broken1" - }; + cmd = {mapreduce: "mr", map: "emit( ", reduce: "fooz + ", out: "broken1"}; x = db.runCommand(cmd); y = s._connections[0].getDB("test").runCommand(cmd); diff --git a/jstests/sharding/fts_score_sort_sharded.js b/jstests/sharding/fts_score_sort_sharded.js index e6bf01503be..8ce5c3383ad 100644 --- a/jstests/sharding/fts_score_sort_sharded.js +++ b/jstests/sharding/fts_score_sort_sharded.js @@ -51,8 +51,9 @@ assert.throws(function() { }); // Projection specified with incorrect field name. -cursor = coll.find({$text: {$search: "pizza"}}, {t: {$meta: "textScore"}}) - .sort({s: {$meta: "textScore"}}); +cursor = coll.find({$text: {$search: "pizza"}}, {t: {$meta: "textScore"}}).sort({ + s: {$meta: "textScore"} +}); assert.throws(function() { cursor.next(); }); diff --git a/jstests/sharding/geo_near_random1.js b/jstests/sharding/geo_near_random1.js index 0229c84555c..707d3c550a0 100644 --- a/jstests/sharding/geo_near_random1.js +++ b/jstests/sharding/geo_near_random1.js @@ -38,9 +38,7 @@ printShardingSizes(); - var opts = { - sharded: true - }; + var opts = {sharded: true}; test.testPt([0, 0], opts); test.testPt(test.mkPt(), opts); test.testPt(test.mkPt(), opts); diff --git a/jstests/sharding/geo_near_random2.js b/jstests/sharding/geo_near_random2.js index cdf8543274a..4833f5bc0d0 100644 --- a/jstests/sharding/geo_near_random2.js +++ b/jstests/sharding/geo_near_random2.js @@ -36,11 +36,7 @@ // Turn balancer back on, for actual tests // s.startBalancer(); // SERVER-13365 - opts = { - sphere: 0, - nToTest: test.nPts * 0.01, - sharded: true - }; + opts = {sphere: 0, nToTest: test.nPts * 0.01, sharded: true}; test.testPt([0, 0], opts); test.testPt(test.mkPt(), opts); test.testPt(test.mkPt(), opts); diff --git a/jstests/sharding/geo_shardedgeonear.js b/jstests/sharding/geo_shardedgeonear.js index 54bda17cf16..123b4b174cc 100644 --- a/jstests/sharding/geo_shardedgeonear.js +++ b/jstests/sharding/geo_shardedgeonear.js @@ -39,12 +39,7 @@ function test(db, sharded, indexType) { assert.commandWorked(db[coll].ensureIndex({loc: indexType})); var queryPoint = [0, 0]; - geoCmd = { - geoNear: coll, - near: queryPoint, - spherical: true, - includeLocs: true - }; + geoCmd = {geoNear: coll, near: queryPoint, spherical: true, includeLocs: true}; assert.commandWorked(db.runCommand(geoCmd), tojson({sharded: sharded, indexType: indexType})); } diff --git a/jstests/sharding/group_slaveok.js b/jstests/sharding/group_slaveok.js index 0d9221ed896..2a18cd7a22e 100644 --- a/jstests/sharding/group_slaveok.js +++ b/jstests/sharding/group_slaveok.js @@ -40,12 +40,13 @@ // Should not throw exception, since slaveOk'd assert.eq(10, coll.group({ - key: {i: true}, - reduce: function(obj, ctx) { - ctx.count += 1; - }, - initial: {count: 0} - }).length); + key: {i: true}, + reduce: function(obj, ctx) { + ctx.count += 1; + }, + initial: {count: 0} + }) + .length); try { conn.setSlaveOk(false); diff --git a/jstests/sharding/hash_shard1.js b/jstests/sharding/hash_shard1.js index 10ab1b1308b..21b69472e3c 100644 --- a/jstests/sharding/hash_shard1.js +++ b/jstests/sharding/hash_shard1.js @@ -35,8 +35,8 @@ assert.neq(chunk, null, "all chunks on shard0000!"); printjson(chunk); // try to move the chunk using an invalid specification method. should fail. -var res = db.adminCommand( - {movechunk: ns, find: {a: 0}, bounds: [chunk.min, chunk.max], to: "shard0000"}); +var res = + db.adminCommand({movechunk: ns, find: {a: 0}, bounds: [chunk.min, chunk.max], to: "shard0000"}); assert.eq(res.ok, 0, "moveChunk shouldn't work with invalid specification method"); // now move a chunk using the lower/upper bound method. should work. diff --git a/jstests/sharding/index1.js b/jstests/sharding/index1.js index 766bd96e260..9b57c3e43f8 100644 --- a/jstests/sharding/index1.js +++ b/jstests/sharding/index1.js @@ -118,9 +118,11 @@ // Make sure the index created is unique! assert.eq(1, - coll.getIndexes().filter(function(z) { - return friendlyEqual(z.key, {num: 1}) && z.unique; - }).length); + coll.getIndexes() + .filter(function(z) { + return friendlyEqual(z.key, {num: 1}) && z.unique; + }) + .length); } if (i == 7) { coll.remove({}); @@ -156,9 +158,11 @@ // Make sure the index created is unique! assert.eq(1, - coll.getIndexes().filter(function(z) { - return friendlyEqual(z.key, {num: 1}) && z.unique; - }).length); + coll.getIndexes() + .filter(function(z) { + return friendlyEqual(z.key, {num: 1}) && z.unique; + }) + .length); } if (i == 9) { // Unique index exists on a different field as well diff --git a/jstests/sharding/key_many.js b/jstests/sharding/key_many.js index 93ce1b4d64a..96e351c25e8 100644 --- a/jstests/sharding/key_many.js +++ b/jstests/sharding/key_many.js @@ -115,9 +115,7 @@ function makeInQuery() { if (curT.compound) { // cheating a bit... - return { - 'o.a': {$in: [1, 2]} - }; + return {'o.a': {$in: [1, 2]}}; } else { return makeObjectDotted({$in: curT.values}); } @@ -178,26 +176,26 @@ assert.eq( 6, c.find().sort(makeObjectDotted(1)).count(), curT.name + " total count with count()"); - assert.eq( - 2, - c.find({$or: [makeObjectDotted(curT.values[2]), makeObjectDotted(curT.values[4])]}) - .count(), - curT.name + " $or count()"); - assert.eq( - 2, - c.find({$or: [makeObjectDotted(curT.values[2]), makeObjectDotted(curT.values[4])]}) - .itcount(), - curT.name + " $or itcount()"); - assert.eq( - 4, - c.find({$nor: [makeObjectDotted(curT.values[2]), makeObjectDotted(curT.values[4])]}) - .count(), - curT.name + " $nor count()"); - assert.eq( - 4, - c.find({$nor: [makeObjectDotted(curT.values[2]), makeObjectDotted(curT.values[4])]}) - .itcount(), - curT.name + " $nor itcount()"); + assert.eq(2, + c.find({ + $or: [makeObjectDotted(curT.values[2]), makeObjectDotted(curT.values[4])] + }).count(), + curT.name + " $or count()"); + assert.eq(2, + c.find({ + $or: [makeObjectDotted(curT.values[2]), makeObjectDotted(curT.values[4])] + }).itcount(), + curT.name + " $or itcount()"); + assert.eq(4, + c.find({ + $nor: [makeObjectDotted(curT.values[2]), makeObjectDotted(curT.values[4])] + }).count(), + curT.name + " $nor count()"); + assert.eq(4, + c.find({ + $nor: [makeObjectDotted(curT.values[2]), makeObjectDotted(curT.values[4])] + }).itcount(), + curT.name + " $nor itcount()"); var stats = c.stats(); printjson(stats); diff --git a/jstests/sharding/key_string.js b/jstests/sharding/key_string.js index 414e056bf1f..43a270e0175 100644 --- a/jstests/sharding/key_string.js +++ b/jstests/sharding/key_string.js @@ -49,12 +49,9 @@ }), "sort 1"); assert.eq("sara,mark,joe,eliot,bob,allan", - db.foo.find() - .sort({name: -1}) - .toArray() - .map(function(z) { - return z.name; - }), + db.foo.find().sort({name: -1}).toArray().map(function(z) { + return z.name; + }), "sort 2"); // make sure we can't foce a split on an extreme key diff --git a/jstests/sharding/lagged_config_secondary.js b/jstests/sharding/lagged_config_secondary.js index 5c28f79f24f..92f0453b941 100644 --- a/jstests/sharding/lagged_config_secondary.js +++ b/jstests/sharding/lagged_config_secondary.js @@ -9,8 +9,8 @@ var configSecondaryToKill = configSecondaryList[0]; var delayedConfigSecondary = configSecondaryList[1]; - delayedConfigSecondary.getDB('admin') - .adminCommand({configureFailPoint: 'rsSyncApplyStop', mode: 'alwaysOn'}); + delayedConfigSecondary.getDB('admin').adminCommand( + {configureFailPoint: 'rsSyncApplyStop', mode: 'alwaysOn'}); var testDB = st.s.getDB('test'); testDB.adminCommand({enableSharding: 'test'}); diff --git a/jstests/sharding/limit_push.js b/jstests/sharding/limit_push.js index 055b5c8b788..b681f328298 100644 --- a/jstests/sharding/limit_push.js +++ b/jstests/sharding/limit_push.js @@ -31,9 +31,7 @@ // The query is asking for the maximum value below a given value // db.limit_push.find( { x : { $lt : 60} } ).sort( { x:-1} ).limit(1) - q = { - x: {$lt: 60} - }; + q = {x: {$lt: 60}}; // Make sure the basic queries are correct assert.eq(60, db.limit_push.find(q).count(), "Did not find 60 documents"); diff --git a/jstests/sharding/localhostAuthBypass.js b/jstests/sharding/localhostAuthBypass.js index 459e627fb3f..b36972da685 100644 --- a/jstests/sharding/localhostAuthBypass.js +++ b/jstests/sharding/localhostAuthBypass.js @@ -107,17 +107,13 @@ var assertCannotRunCommands = function(mongo, st) { {param: "userCacheInvalidationIntervalSecs", val: 300} ]; params.forEach(function(p) { - var cmd = { - setParameter: 1 - }; + var cmd = {setParameter: 1}; cmd[p.param] = p.val; assert.commandFailedWithCode( mongo.getDB("admin").runCommand(cmd), authorizeErrorCode, "setParameter: " + p.param); }); params.forEach(function(p) { - var cmd = { - getParameter: 1 - }; + var cmd = {getParameter: 1}; cmd[p.param] = 1; assert.commandFailedWithCode( mongo.getDB("admin").runCommand(cmd), authorizeErrorCode, "getParameter: " + p.param); diff --git a/jstests/sharding/max_time_ms_sharded.js b/jstests/sharding/max_time_ms_sharded.js index 7194c98750c..36ccf7d1d6f 100644 --- a/jstests/sharding/max_time_ms_sharded.js +++ b/jstests/sharding/max_time_ms_sharded.js @@ -160,17 +160,16 @@ // Positive test for "mapReduce". configureMaxTimeAlwaysTimeOut("alwaysOn"); - res = coll.runCommand("mapReduce", - { - map: function() { - emit(0, 0); - }, - reduce: function(key, values) { - return 0; - }, - out: {inline: 1}, - maxTimeMS: 60 * 1000 - }); + res = coll.runCommand("mapReduce", { + map: function() { + emit(0, 0); + }, + reduce: function(key, values) { + return 0; + }, + out: {inline: 1}, + maxTimeMS: 60 * 1000 + }); assert.commandFailed( res, "expected mapReduce to fail in mongod due to maxTimeAlwaysTimeOut fail point"); assert.eq( @@ -180,17 +179,16 @@ // Negative test for "mapReduce". configureMaxTimeAlwaysTimeOut("off"); - assert.commandWorked(coll.runCommand("mapReduce", - { - map: function() { - emit(0, 0); - }, - reduce: function(key, values) { - return 0; - }, - out: {inline: 1}, - maxTimeMS: 60 * 1000 - }), + assert.commandWorked(coll.runCommand("mapReduce", { + map: function() { + emit(0, 0); + }, + reduce: function(key, values) { + return 0; + }, + out: {inline: 1}, + maxTimeMS: 60 * 1000 + }), "expected mapReduce to not hit time limit in mongod"); // Positive test for "aggregate". diff --git a/jstests/sharding/migrateBig.js b/jstests/sharding/migrateBig.js index 8895d14c0d6..01260123b67 100644 --- a/jstests/sharding/migrateBig.js +++ b/jstests/sharding/migrateBig.js @@ -42,11 +42,8 @@ s.printShardingStatus(); assert.throws(function() { - s.adminCommand({ - movechunk: "test.foo", - find: {x: 50}, - to: s.getOther(s.getPrimaryShard("test")).name - }); + s.adminCommand( + {movechunk: "test.foo", find: {x: 50}, to: s.getOther(s.getPrimaryShard("test")).name}); }, [], "move should fail"); for (i = 0; i < 20; i += 2) { diff --git a/jstests/sharding/migration_failure.js b/jstests/sharding/migration_failure.js index 6198c8d2cef..aee7fdc97db 100644 --- a/jstests/sharding/migration_failure.js +++ b/jstests/sharding/migration_failure.js @@ -53,8 +53,8 @@ assert.neq(version.global, failVersion.global); - assert.commandWorked(st.shard0.getDB("admin") - .runCommand({configureFailPoint: 'failApplyChunkOps', mode: 'off'})); + assert.commandWorked(st.shard0.getDB("admin").runCommand( + {configureFailPoint: 'failApplyChunkOps', mode: 'off'})); assert.commandWorked(st.shard0.getDB("admin").runCommand( {configureFailPoint: 'failCommitMigrationCommand', mode: 'off'})); diff --git a/jstests/sharding/min_optime_recovery.js b/jstests/sharding/min_optime_recovery.js index d77f1e2ad42..69ccc78f02c 100644 --- a/jstests/sharding/min_optime_recovery.js +++ b/jstests/sharding/min_optime_recovery.js @@ -47,12 +47,10 @@ assert.eq(null, doc); } - var restartCmdLineOptions = Object.merge( - st.d0.fullOptions, - { - setParameter: 'recoverShardingState=' + (withRecovery ? 'true' : 'false'), - restart: true - }); + var restartCmdLineOptions = Object.merge(st.d0.fullOptions, { + setParameter: 'recoverShardingState=' + (withRecovery ? 'true' : 'false'), + restart: true + }); // Restart the shard that donated a chunk to trigger the optime recovery logic. st.stopMongod(0); diff --git a/jstests/sharding/mongos_no_replica_set_refresh.js b/jstests/sharding/mongos_no_replica_set_refresh.js index 3d9af893b55..53809fd88aa 100644 --- a/jstests/sharding/mongos_no_replica_set_refresh.js +++ b/jstests/sharding/mongos_no_replica_set_refresh.js @@ -10,7 +10,11 @@ load("jstests/replsets/rslib.js"); mongos: 1, other: { rs0: { - nodes: [{}, {rsConfig: {priority: 0}}, {rsConfig: {priority: 0}}, ], + nodes: [ + {}, + {rsConfig: {priority: 0}}, + {rsConfig: {priority: 0}}, + ], } } }); diff --git a/jstests/sharding/mongos_rs_auth_shard_failure_tolerance.js b/jstests/sharding/mongos_rs_auth_shard_failure_tolerance.js index 8eaf9653f11..0acb2cc5609 100644 --- a/jstests/sharding/mongos_rs_auth_shard_failure_tolerance.js +++ b/jstests/sharding/mongos_rs_auth_shard_failure_tolerance.js @@ -11,11 +11,7 @@ // (connection connected after shard change). // -var options = { - rs: true, - rsOptions: {nodes: 2}, - keyFile: "jstests/libs/key1" -}; +var options = {rs: true, rsOptions: {nodes: 2}, keyFile: "jstests/libs/key1"}; var st = new ShardingTest({shards: 3, mongos: 1, other: options}); @@ -82,9 +78,7 @@ authDBUsers(mongosConnActive); var mongosConnIdle = null; var mongosConnNew = null; -var wc = { - writeConcern: {w: 2, wtimeout: 60000} -}; +var wc = {writeConcern: {w: 2, wtimeout: 60000}}; assert.writeOK(mongosConnActive.getCollection(collSharded.toString()).insert({_id: -1}, wc)); assert.writeOK(mongosConnActive.getCollection(collSharded.toString()).insert({_id: 1}, wc)); diff --git a/jstests/sharding/mongos_rs_shard_failure_tolerance.js b/jstests/sharding/mongos_rs_shard_failure_tolerance.js index e24566605ce..f811c9ad443 100644 --- a/jstests/sharding/mongos_rs_shard_failure_tolerance.js +++ b/jstests/sharding/mongos_rs_shard_failure_tolerance.js @@ -50,9 +50,7 @@ var mongosConnIdle = null; var mongosConnNew = null; - var wc = { - writeConcern: {w: 2, wtimeout: 60000} - }; + var wc = {writeConcern: {w: 2, wtimeout: 60000}}; assert.writeOK(mongosConnActive.getCollection(collSharded.toString()).insert({_id: -1}, wc)); assert.writeOK(mongosConnActive.getCollection(collSharded.toString()).insert({_id: 1}, wc)); diff --git a/jstests/sharding/mongos_shard_failure_tolerance.js b/jstests/sharding/mongos_shard_failure_tolerance.js index 73455666635..b3e480ae3ed 100644 --- a/jstests/sharding/mongos_shard_failure_tolerance.js +++ b/jstests/sharding/mongos_shard_failure_tolerance.js @@ -32,8 +32,8 @@ // Create the unsharded database assert.writeOK(collUnsharded.insert({some: "doc"})); assert.writeOK(collUnsharded.remove({})); - assert.commandWorked(admin.runCommand( - {movePrimary: collUnsharded.getDB().toString(), to: st.shard0.shardName})); + assert.commandWorked( + admin.runCommand({movePrimary: collUnsharded.getDB().toString(), to: st.shard0.shardName})); // // Setup is complete diff --git a/jstests/sharding/move_chunk_basic.js b/jstests/sharding/move_chunk_basic.js index 69bdf4d8c90..267ca74f718 100644 --- a/jstests/sharding/move_chunk_basic.js +++ b/jstests/sharding/move_chunk_basic.js @@ -33,10 +33,10 @@ assert(aChunk); // Error if either of the bounds is not a valid shard key (BSON object - 1 yields a NaN) - assert.commandFailed(mongos.adminCommand( - {moveChunk: ns, bounds: [aChunk.min - 1, aChunk.max], to: shard1})); - assert.commandFailed(mongos.adminCommand( - {moveChunk: ns, bounds: [aChunk.min, aChunk.max - 1], to: shard1})); + assert.commandFailed( + mongos.adminCommand({moveChunk: ns, bounds: [aChunk.min - 1, aChunk.max], to: shard1})); + assert.commandFailed( + mongos.adminCommand({moveChunk: ns, bounds: [aChunk.min, aChunk.max - 1], to: shard1})); // Fail if find and bounds are both set. assert.commandFailed(mongos.adminCommand( diff --git a/jstests/sharding/move_chunk_wc.js b/jstests/sharding/move_chunk_wc.js index 9f7d4b2b646..1ebf1be6b36 100644 --- a/jstests/sharding/move_chunk_wc.js +++ b/jstests/sharding/move_chunk_wc.js @@ -57,10 +57,7 @@ load('jstests/libs/write_concern_util.js'); _waitForDelete: true }; - req.writeConcern = { - w: 1, - wtimeout: 30000 - }; + req.writeConcern = {w: 1, wtimeout: 30000}; jsTest.log("Testing " + tojson(req)); var res = db.adminCommand(req); assert.commandWorked(res); @@ -68,10 +65,7 @@ load('jstests/libs/write_concern_util.js'); checkChunkCount(2, 0); // This should pass because w: majority is always passed to config servers. - req.writeConcern = { - w: 2, - wtimeout: 30000 - }; + req.writeConcern = {w: 2, wtimeout: 30000}; jsTest.log("Testing " + tojson(req)); req.to = s1; res = db.adminCommand(req); @@ -80,10 +74,7 @@ load('jstests/libs/write_concern_util.js'); checkChunkCount(1, 1); // This should fail because the writeConcern cannot be satisfied on the to shard. - req.writeConcern = { - w: 4, - wtimeout: 3000 - }; + req.writeConcern = {w: 4, wtimeout: 3000}; jsTest.log("Testing " + tojson(req)); req.to = s0; res = db.adminCommand(req); @@ -92,10 +83,7 @@ load('jstests/libs/write_concern_util.js'); checkChunkCount(1, 1); // This should fail because the writeConcern cannot be satisfied on the from shard. - req.writeConcern = { - w: 6, - wtimeout: 3000 - }; + req.writeConcern = {w: 6, wtimeout: 3000}; jsTest.log("Testing " + tojson(req)); req.to = s0; res = db.adminCommand(req); @@ -104,10 +92,7 @@ load('jstests/libs/write_concern_util.js'); checkChunkCount(1, 1); // This should fail because the writeConcern is invalid and cannot be satisfied anywhere. - req.writeConcern = { - w: "invalid", - wtimeout: 3000 - }; + req.writeConcern = {w: "invalid", wtimeout: 3000}; jsTest.log("Testing " + tojson(req)); req.to = s0; res = db.adminCommand(req); diff --git a/jstests/sharding/move_stale_mongos.js b/jstests/sharding/move_stale_mongos.js index 63482d894c3..ceb805ee674 100644 --- a/jstests/sharding/move_stale_mongos.js +++ b/jstests/sharding/move_stale_mongos.js @@ -17,12 +17,8 @@ for (var i = 0; i < 100; i += 10) { assert.commandWorked(st.s0.getDB('admin').runCommand({split: testNs, middle: {_id: i}})); st.configRS.awaitLastOpCommitted(); // Ensure that other mongos sees the split var nextShardIndex = (curShardIndex + 1) % shards.length; - assert.commandWorked(st.s1.getDB('admin').runCommand({ - moveChunk: testNs, - find: {_id: i + 5}, - to: shards[nextShardIndex], - _waitForDelete: true - })); + assert.commandWorked(st.s1.getDB('admin').runCommand( + {moveChunk: testNs, find: {_id: i + 5}, to: shards[nextShardIndex], _waitForDelete: true})); curShardIndex = nextShardIndex; st.configRS.awaitLastOpCommitted(); // Ensure that other mongos sees the move } diff --git a/jstests/sharding/movechunk_with_default_paranoia.js b/jstests/sharding/movechunk_with_default_paranoia.js index a6f4704ec90..52597fec149 100644 --- a/jstests/sharding/movechunk_with_default_paranoia.js +++ b/jstests/sharding/movechunk_with_default_paranoia.js @@ -10,9 +10,11 @@ var shards = [st.shard0, st.shard1]; for (i in shards) { var dbpath = shards[i].adminCommand("getCmdLineOpts").parsed.storage.dbPath; var hasMoveChunkDir = 0 != - ls(dbpath).filter(function(a) { - return null != a.match("moveChunk"); - }).length; + ls(dbpath) + .filter(function(a) { + return null != a.match("moveChunk"); + }) + .length; assert(!hasMoveChunkDir, dbpath + ": has MoveChunk directory + " + ls(dbpath)); } st.stop(); diff --git a/jstests/sharding/movechunk_with_moveParanoia.js b/jstests/sharding/movechunk_with_moveParanoia.js index 96348d827bf..f8c2fd0fbd8 100644 --- a/jstests/sharding/movechunk_with_moveParanoia.js +++ b/jstests/sharding/movechunk_with_moveParanoia.js @@ -12,9 +12,11 @@ var foundMoveChunk = false; for (i in shards) { var dbpath = shards[i].adminCommand("getCmdLineOpts").parsed.storage.dbPath; var hasMoveChunkDir = 0 != - ls(dbpath).filter(function(a) { - return null != a.match("moveChunk"); - }).length; + ls(dbpath) + .filter(function(a) { + return null != a.match("moveChunk"); + }) + .length; foundMoveChunk = foundMoveChunk || hasMoveChunkDir; } diff --git a/jstests/sharding/movechunk_with_noMoveParanoia.js b/jstests/sharding/movechunk_with_noMoveParanoia.js index ae8ef5899a8..4e75421543a 100644 --- a/jstests/sharding/movechunk_with_noMoveParanoia.js +++ b/jstests/sharding/movechunk_with_noMoveParanoia.js @@ -11,9 +11,11 @@ var shards = [st.shard0, st.shard1]; for (i in shards) { var dbpath = shards[i].adminCommand("getCmdLineOpts").parsed.storage.dbPath; var hasMoveChunkDir = 0 != - ls(dbpath).filter(function(a) { - return null != a.match("moveChunk"); - }).length; + ls(dbpath) + .filter(function(a) { + return null != a.match("moveChunk"); + }) + .length; assert(!hasMoveChunkDir, dbpath + ": has MoveChunk directory + " + ls(dbpath)); } st.stop(); diff --git a/jstests/sharding/mrShardedOutput.js b/jstests/sharding/mrShardedOutput.js index ab3bae28d74..39def771ef9 100644 --- a/jstests/sharding/mrShardedOutput.js +++ b/jstests/sharding/mrShardedOutput.js @@ -64,9 +64,8 @@ assert.eq(numDocs, // Make sure it's sharded and split var newNumChunks = config.chunks.count({ns: testDB.mrShardedOut._fullName}); -assert.gt(newNumChunks, - 1, - "Sharding FAILURE: " + testDB.mrShardedOut._fullName + " has only 1 chunk"); +assert.gt( + newNumChunks, 1, "Sharding FAILURE: " + testDB.mrShardedOut._fullName + " has only 1 chunk"); // Check that there are no "jumbo" chunks. var objSize = Object.bsonsize(testDB.mrShardedOut.findOne()); @@ -74,13 +73,11 @@ var docsPerChunk = 1024 * 1024 / objSize * 1.1; // 1MB chunk size + allowance st.printShardingStatus(true); -config.chunks.find({ns: testDB.mrShardedOut.getFullName()}) - .forEach(function(chunkDoc) { - var count = - testDB.mrShardedOut.find({_id: {$gte: chunkDoc.min._id, $lt: chunkDoc.max._id}}) - .itcount(); - assert.lte(count, docsPerChunk, 'Chunk has too many docs: ' + tojson(chunkDoc)); - }); +config.chunks.find({ns: testDB.mrShardedOut.getFullName()}).forEach(function(chunkDoc) { + var count = + testDB.mrShardedOut.find({_id: {$gte: chunkDoc.min._id, $lt: chunkDoc.max._id}}).itcount(); + assert.lte(count, docsPerChunk, 'Chunk has too many docs: ' + tojson(chunkDoc)); +}); // Check that chunks for the newly created sharded output collection are well distributed. var shard0Chunks = @@ -127,9 +124,8 @@ assert.eq(numDocs, // Make sure it's sharded and split newNumChunks = config.chunks.count({ns: testDB.mrShardedOut._fullName}); -assert.gt(newNumChunks, - 1, - "Sharding FAILURE: " + testDB.mrShardedOut._fullName + " has only 1 chunk"); +assert.gt( + newNumChunks, 1, "Sharding FAILURE: " + testDB.mrShardedOut._fullName + " has only 1 chunk"); st.printShardingStatus(true); diff --git a/jstests/sharding/mr_shard_version.js b/jstests/sharding/mr_shard_version.js index fc2f7f02e4b..5040fc17ef2 100644 --- a/jstests/sharding/mr_shard_version.js +++ b/jstests/sharding/mr_shard_version.js @@ -31,11 +31,7 @@ jsTest.log("Starting migrations..."); - var migrateOp = { - op: "command", - ns: "admin", - command: {moveChunk: "" + coll} - }; + var migrateOp = {op: "command", ns: "admin", command: {moveChunk: "" + coll}}; var checkMigrate = function() { print("Result of migrate : "); diff --git a/jstests/sharding/multi_mongos2.js b/jstests/sharding/multi_mongos2.js index 2112408afc0..dcbd5a66655 100644 --- a/jstests/sharding/multi_mongos2.js +++ b/jstests/sharding/multi_mongos2.js @@ -28,9 +28,9 @@ assert.eq(1, res.ok, tojson(res)); printjson(s2.adminCommand({"getShardVersion": "test.existing"})); - printjson(new Mongo(s1.getPrimaryShard("test").name) - .getDB("admin") - .adminCommand({"getShardVersion": "test.existing"})); + printjson(new Mongo(s1.getPrimaryShard("test").name).getDB("admin").adminCommand({ + "getShardVersion": "test.existing" + })); assert.eq(1, s1.getDB('test').existing.count({_id: 1})); // SERVER-2828 assert.eq(1, s2.getDB('test').existing.count({_id: 1})); diff --git a/jstests/sharding/no_empty_reset.js b/jstests/sharding/no_empty_reset.js index 61fe5905cc0..da77597ecae 100644 --- a/jstests/sharding/no_empty_reset.js +++ b/jstests/sharding/no_empty_reset.js @@ -31,12 +31,8 @@ var emptyShard = st.getShard(coll, {_id: -1}); var admin = st.s.getDB("admin"); assert.soon( function() { - var result = admin.runCommand({ - moveChunk: "" + coll, - find: {_id: -1}, - to: fullShard.shardName, - _waitForDelete: true - }); + var result = admin.runCommand( + {moveChunk: "" + coll, find: {_id: -1}, to: fullShard.shardName, _waitForDelete: true}); jsTestLog('moveChunk result = ' + tojson(result)); return result.ok; }, diff --git a/jstests/sharding/pending_chunk.js b/jstests/sharding/pending_chunk.js index 21107fe370d..96089b6d491 100644 --- a/jstests/sharding/pending_chunk.js +++ b/jstests/sharding/pending_chunk.js @@ -23,10 +23,10 @@ assert.commandWorked(admin.runCommand({split: ns, middle: {_id: 0}})); assert.commandWorked(admin.runCommand({split: ns, middle: {_id: 1}})); - assert.commandWorked(admin.runCommand( - {moveChunk: ns, find: {_id: 0}, to: shards[1]._id, _waitForDelete: true})); - assert.commandWorked(admin.runCommand( - {moveChunk: ns, find: {_id: 1}, to: shards[1]._id, _waitForDelete: true})); + assert.commandWorked( + admin.runCommand({moveChunk: ns, find: {_id: 0}, to: shards[1]._id, _waitForDelete: true})); + assert.commandWorked( + admin.runCommand({moveChunk: ns, find: {_id: 1}, to: shards[1]._id, _waitForDelete: true})); function getMetadata(shard) { var admin = shard.getDB('admin'), @@ -50,8 +50,8 @@ assert.neq(metadata.collVersion.t, 0); assert.eq(metadata.pending.length, 0); - assert.commandWorked(admin.runCommand( - {moveChunk: ns, find: {_id: 1}, to: shards[0]._id, _waitForDelete: true})); + assert.commandWorked( + admin.runCommand({moveChunk: ns, find: {_id: 1}, to: shards[0]._id, _waitForDelete: true})); metadata = getMetadata(shard0); assert.eq(metadata.shardVersion.t, 0); diff --git a/jstests/sharding/prefix_shard_key.js b/jstests/sharding/prefix_shard_key.js index 92a077d73b5..a13b133e3ef 100644 --- a/jstests/sharding/prefix_shard_key.js +++ b/jstests/sharding/prefix_shard_key.js @@ -109,27 +109,23 @@ _waitForDelete: true })); - var expectedShardCount = { - shard0000: 0, - shard0001: 0 - }; - config.chunks.find({ns: 'test.user'}) - .forEach(function(chunkDoc) { - var min = chunkDoc.min.num; - var max = chunkDoc.max.num; - - if (min < 0 || min == MinKey) { - min = 0; - } + var expectedShardCount = {shard0000: 0, shard0001: 0}; + config.chunks.find({ns: 'test.user'}).forEach(function(chunkDoc) { + var min = chunkDoc.min.num; + var max = chunkDoc.max.num; - if (max > 1000 || max == MaxKey) { - max = 1000; - } + if (min < 0 || min == MinKey) { + min = 0; + } - if (max > 0) { - expectedShardCount[chunkDoc.shard] += (max - min); - } - }); + if (max > 1000 || max == MaxKey) { + max = 1000; + } + + if (max > 0) { + expectedShardCount[chunkDoc.shard] += (max - min); + } + }); assert.eq(expectedShardCount['shard0000'], shard0.getDB('test').user.find().count()); assert.eq(expectedShardCount['shard0001'], shard1.getDB('test').user.find().count()); diff --git a/jstests/sharding/printShardingStatus.js b/jstests/sharding/printShardingStatus.js index 05e6eca0d4f..63b5ef3090c 100644 --- a/jstests/sharding/printShardingStatus.js +++ b/jstests/sharding/printShardingStatus.js @@ -162,10 +162,7 @@ }; var collName = getCollName(testCollDetailsNum); - var cmdObj = { - shardCollection: collName, - key: {_id: 1} - }; + var cmdObj = {shardCollection: collName, key: {_id: 1}}; if (args.unique) { cmdObj.unique = true; } diff --git a/jstests/sharding/query_config.js b/jstests/sharding/query_config.js index c6b08b8b7c0..7547eef007a 100644 --- a/jstests/sharding/query_config.js +++ b/jstests/sharding/query_config.js @@ -164,12 +164,13 @@ assert(!cursor.hasNext()); // Aggregate query. - cursor = configDB.collections.aggregate([ - {$match: {"key.b": 1}}, - {$sort: {"_id": 1}}, - {$project: {"keyb": "$key.b", "keyc": "$key.c"}} - ], - {cursor: {batchSize: 2}}); + cursor = configDB.collections.aggregate( + [ + {$match: {"key.b": 1}}, + {$sort: {"_id": 1}}, + {$project: {"keyb": "$key.b", "keyc": "$key.c"}} + ], + {cursor: {batchSize: 2}}); assert.eq(cursor.objsLeftInBatch(), 2); assert.eq(cursor.next(), {_id: testNamespaces[3], keyb: 1, keyc: 1}); assert.eq(cursor.next(), {_id: testNamespaces[2], keyb: 1}); @@ -220,8 +221,9 @@ st.s.adminCommand({movechunk: testColl.getFullName(), find: {e: 12}, to: shard2})); // Find query. - cursor = configDB.chunks.find({ns: testColl.getFullName()}, - {_id: 0, min: 1, max: 1, shard: 1}).sort({"min.e": 1}); + cursor = + configDB.chunks.find({ns: testColl.getFullName()}, {_id: 0, min: 1, max: 1, shard: 1}) + .sort({"min.e": 1}); assert.eq(cursor.next(), {min: {e: {"$minKey": 1}}, "max": {"e": 2}, shard: shard2}); assert.eq(cursor.next(), {min: {e: 2}, max: {e: 6}, shard: shard1}); assert.eq(cursor.next(), {min: {e: 6}, max: {e: 8}, shard: shard1}); @@ -258,9 +260,7 @@ } }; var reduceFunction = function(key, values) { - return { - chunks: values.length - }; + return {chunks: values.length}; }; result = configDB.chunks.mapReduce(mapFunction, reduceFunction, {out: {inline: 1}}); assert.eq(result.ok, 1); @@ -322,13 +322,14 @@ assert(!cursor.hasNext()); // Aggregate query. - cursor = userColl.aggregate([ - {$match: {c: {$gt: 1}}}, - {$unwind: "$u"}, - {$group: {_id: "$u", sum: {$sum: "$c"}}}, - {$sort: {_id: 1}} - ], - {cursor: {batchSize: 2}}); + cursor = userColl.aggregate( + [ + {$match: {c: {$gt: 1}}}, + {$unwind: "$u"}, + {$group: {_id: "$u", sum: {$sum: "$c"}}}, + {$sort: {_id: 1}} + ], + {cursor: {batchSize: 2}}); assert.eq(cursor.objsLeftInBatch(), 2); assert.eq(cursor.next(), {_id: 1, sum: 11}); assert.eq(cursor.next(), {_id: 2, sum: 15}); @@ -365,18 +366,15 @@ emit(this.g, 1); }; var reduceFunction = function(key, values) { - return { - count: values.length - }; + return {count: values.length}; }; result = userColl.mapReduce(mapFunction, reduceFunction, {out: {inline: 1}}); assert.eq(result.ok, 1); - assert.eq(sortArrayById(result.results), - [ - {_id: 1, value: {count: 2}}, - {_id: 2, value: {count: 3}}, - {_id: 3, value: {count: 2}} - ]); + assert.eq(sortArrayById(result.results), [ + {_id: 1, value: {count: 2}}, + {_id: 2, value: {count: 3}}, + {_id: 3, value: {count: 2}} + ]); assert(userColl.drop()); }; diff --git a/jstests/sharding/read_pref.js b/jstests/sharding/read_pref.js index aadd8903344..973f02993ac 100644 --- a/jstests/sharding/read_pref.js +++ b/jstests/sharding/read_pref.js @@ -3,9 +3,7 @@ * can be found in dbtests/replica_set_monitor_test.cpp. */ -var PRI_TAG = { - dc: 'ny' -}; +var PRI_TAG = {dc: 'ny'}; var SEC_TAGS = [{dc: 'sf', s: "1"}, {dc: 'ma', s: "2"}, {dc: 'eu', s: "3"}, {dc: 'jp', s: "4"}]; var NODES = SEC_TAGS.length + 1; @@ -95,9 +93,7 @@ var doTest = function(useDollarQuerySyntax) { var getExplain = function(readPrefMode, readPrefTags) { if (useDollarQuerySyntax) { - var readPrefObj = { - mode: readPrefMode - }; + var readPrefObj = {mode: readPrefMode}; if (readPrefTags) { readPrefObj.tags = readPrefTags; diff --git a/jstests/sharding/read_pref_cmd.js b/jstests/sharding/read_pref_cmd.js index 1e4aa48ee25..3cf6a694cd0 100644 --- a/jstests/sharding/read_pref_cmd.js +++ b/jstests/sharding/read_pref_cmd.js @@ -60,9 +60,7 @@ var testReadPreference = function(conn, hostList, isMongos, mode, tagSets, secEx assert(cmdResult.ok); var testedAtLeastOnce = false; - var query = { - op: 'command' - }; + var query = {op: 'command'}; Object.extend(query, profileQuery); hostList.forEach(function(node) { @@ -216,28 +214,28 @@ var testAllModes = function(conn, hostList, isMongos) { // { tag: 'two' } so we can test the interaction of modes and tags. Test // a bunch of combinations. [ - // mode, tagSets, expectedHost - ['primary', undefined, false], - ['primary', [], false], + // mode, tagSets, expectedHost + ['primary', undefined, false], + ['primary', [], false], - ['primaryPreferred', undefined, false], - ['primaryPreferred', [{tag: 'one'}], false], - // Correctly uses primary and ignores the tag - ['primaryPreferred', [{tag: 'two'}], false], + ['primaryPreferred', undefined, false], + ['primaryPreferred', [{tag: 'one'}], false], + // Correctly uses primary and ignores the tag + ['primaryPreferred', [{tag: 'two'}], false], - ['secondary', undefined, true], - ['secondary', [{tag: 'two'}], true], - ['secondary', [{tag: 'doesntexist'}, {}], true], - ['secondary', [{tag: 'doesntexist'}, {tag: 'two'}], true], + ['secondary', undefined, true], + ['secondary', [{tag: 'two'}], true], + ['secondary', [{tag: 'doesntexist'}, {}], true], + ['secondary', [{tag: 'doesntexist'}, {tag: 'two'}], true], - ['secondaryPreferred', undefined, true], - ['secondaryPreferred', [{tag: 'one'}], false], - ['secondaryPreferred', [{tag: 'two'}], true], + ['secondaryPreferred', undefined, true], + ['secondaryPreferred', [{tag: 'one'}], false], + ['secondaryPreferred', [{tag: 'two'}], true], - // We don't have a way to alter ping times so we can't predict where an - // untagged 'nearest' command should go, hence only test with tags. - ['nearest', [{tag: 'one'}], false], - ['nearest', [{tag: 'two'}], true] + // We don't have a way to alter ping times so we can't predict where an + // untagged 'nearest' command should go, hence only test with tags. + ['nearest', [{tag: 'one'}], false], + ['nearest', [{tag: 'two'}], true] ].forEach(function(args) { var mode = args[0], tagSets = args[1], secExpected = args[2]; @@ -248,17 +246,17 @@ var testAllModes = function(conn, hostList, isMongos) { }); [ - // Tags not allowed with primary - ['primary', [{dc: 'doesntexist'}]], - ['primary', [{dc: 'ny'}]], - ['primary', [{dc: 'one'}]], + // Tags not allowed with primary + ['primary', [{dc: 'doesntexist'}]], + ['primary', [{dc: 'ny'}]], + ['primary', [{dc: 'one'}]], - // No matching node - ['secondary', [{tag: 'one'}]], - ['nearest', [{tag: 'doesntexist'}]], + // No matching node + ['secondary', [{tag: 'one'}]], + ['nearest', [{tag: 'doesntexist'}]], - ['invalid-mode', undefined], - ['secondary', ['misformatted-tags']] + ['invalid-mode', undefined], + ['secondary', ['misformatted-tags']] ].forEach(function(args) { var mode = args[0], tagSets = args[1]; @@ -278,14 +276,8 @@ ReplSetTest.awaitRSClientHosts(st.s, st.rs0.nodes); // Tag primary with { dc: 'ny', tag: 'one' }, secondary with { dc: 'ny', tag: 'two' } var primary = st.rs0.getPrimary(); var secondary = st.rs0.getSecondary(); -var PRIMARY_TAG = { - dc: 'ny', - tag: 'one' -}; -var SECONDARY_TAG = { - dc: 'ny', - tag: 'two' -}; +var PRIMARY_TAG = {dc: 'ny', tag: 'one'}; +var SECONDARY_TAG = {dc: 'ny', tag: 'two'}; var rsConfig = primary.getDB("local").system.replset.findOne(); jsTest.log('got rsconf ' + tojson(rsConfig)); diff --git a/jstests/sharding/regex_targeting.js b/jstests/sharding/regex_targeting.js index 7dd927d8aab..33411447721 100644 --- a/jstests/sharding/regex_targeting.js +++ b/jstests/sharding/regex_targeting.js @@ -162,17 +162,14 @@ collSharded.remove({}); collCompound.remove({}); collNested.remove({}); assert.writeError(collSharded.update({a: /abcde.*/}, {$set: {a: /abcde.*/}}, {upsert: true})); -assert.writeError(collCompound.update({a: /abcde.*/}, - {$set: {a: /abcde.*/, b: 1}}, - {upsert: true})); +assert.writeError( + collCompound.update({a: /abcde.*/}, {$set: {a: /abcde.*/, b: 1}}, {upsert: true})); // Exact regex in query never equality -assert.writeError(collNested.update({'a.b': /abcde.*/}, - {$set: {'a.b': /abcde.*/}}, - {upsert: true})); +assert.writeError( + collNested.update({'a.b': /abcde.*/}, {$set: {'a.b': /abcde.*/}}, {upsert: true})); // Even nested regexes are not extracted in queries -assert.writeError(collNested.update({a: {b: /abcde.*/}}, - {$set: {'a.b': /abcde.*/}}, - {upsert: true})); +assert.writeError( + collNested.update({a: {b: /abcde.*/}}, {$set: {'a.b': /abcde.*/}}, {upsert: true})); assert.writeError(collNested.update({c: 1}, {$set: {'a.b': /abcde.*/}}, {upsert: true})); // diff --git a/jstests/sharding/replmonitor_bad_seed.js b/jstests/sharding/replmonitor_bad_seed.js index 1d52ac47abc..95d6d7526a8 100644 --- a/jstests/sharding/replmonitor_bad_seed.js +++ b/jstests/sharding/replmonitor_bad_seed.js @@ -13,9 +13,7 @@ * was able to refresh before proceeding to check. */ -var rsOpt = { - oplogSize: 10 -}; +var rsOpt = {oplogSize: 10}; var st = new ShardingTest({shards: 1, rs: rsOpt}); var mongos = st.s; var replTest = st.rs0; diff --git a/jstests/sharding/secondary_query_routing.js b/jstests/sharding/secondary_query_routing.js index ff0dfcb22d9..3eb706022aa 100644 --- a/jstests/sharding/secondary_query_routing.js +++ b/jstests/sharding/secondary_query_routing.js @@ -4,9 +4,7 @@ */ (function() { - var rsOpts = { - nodes: 2 - }; + var rsOpts = {nodes: 2}; var st = new ShardingTest({mongos: 2, shards: {rs0: rsOpts, rs1: rsOpts}}); st.s0.adminCommand({enableSharding: 'test'}); diff --git a/jstests/sharding/shard2.js b/jstests/sharding/shard2.js index abe91508650..6f563aebbb0 100644 --- a/jstests/sharding/shard2.js +++ b/jstests/sharding/shard2.js @@ -40,9 +40,8 @@ db.foo.save({num: 1, name: "eliot"}); db.foo.save({num: 2, name: "sara"}); db.foo.save({num: -1, name: "joe"}); -assert.eq(3, - s.getPrimaryShard("test").getDB("test").foo.find().length(), - "not right directly to db A"); +assert.eq( + 3, s.getPrimaryShard("test").getDB("test").foo.find().length(), "not right directly to db A"); assert.eq(3, db.foo.find().length(), "not right on shard"); primary = s.getPrimaryShard("test").getDB("test"); @@ -58,12 +57,8 @@ placeCheck(2); // test move shard assert.throws(function() { - s.adminCommand({ - movechunk: "test.foo", - find: {num: 1}, - to: primary.getMongo().name, - _waitForDelete: true - }); + s.adminCommand( + {movechunk: "test.foo", find: {num: 1}, to: primary.getMongo().name, _waitForDelete: true}); }); assert.throws(function() { s.adminCommand({movechunk: "test.foo", find: {num: 1}, to: "adasd", _waitForDelete: true}); @@ -74,9 +69,8 @@ s.adminCommand( assert.eq(2, secondary.foo.find().length(), "secondary should have 2 after move shard"); assert.eq(1, primary.foo.find().length(), "primary should only have 1 after move shard"); -assert.eq(2, - s.config.chunks.count(), - "still should have 2 shards after move not:" + s.getChunksString()); +assert.eq( + 2, s.config.chunks.count(), "still should have 2 shards after move not:" + s.getChunksString()); chunks = s.config.chunks.find().toArray(); assert.neq(chunks[0].shard, chunks[1].shard, "servers should NOT be the same after the move"); diff --git a/jstests/sharding/shard_aware_init.js b/jstests/sharding/shard_aware_init.js index 199eb369557..5dda623bb77 100644 --- a/jstests/sharding/shard_aware_init.js +++ b/jstests/sharding/shard_aware_init.js @@ -40,8 +40,8 @@ mongodConn = MongoRunner.runMongod(options); waitForMaster(mongodConn); - var res = mongodConn.getDB('admin') - .system.version.update({_id: 'shardIdentity'}, shardIdentityDoc); + var res = mongodConn.getDB('admin').system.version.update({_id: 'shardIdentity'}, + shardIdentityDoc); assert.eq(1, res.nModified); MongoRunner.stopMongod(mongodConn.port); @@ -60,8 +60,8 @@ return mongodConn; }; - assert.writeOK(mongodConn.getDB('admin') - .system.version.update({_id: 'shardIdentity'}, shardIdentityDoc, true)); + assert.writeOK(mongodConn.getDB('admin').system.version.update( + {_id: 'shardIdentity'}, shardIdentityDoc, true)); var res = mongodConn.getDB('admin').runCommand({shardingState: 1}); @@ -98,8 +98,7 @@ waitForMaster(mongodConn); assert.writeOK(mongodConn.getDB('admin').system.version.update( - {_id: 'shardIdentity'}, - {_id: 'shardIdentity', shardName: 'x', clusterId: ObjectId()})); + {_id: 'shardIdentity'}, {_id: 'shardIdentity', shardName: 'x', clusterId: ObjectId()})); MongoRunner.stopMongod(mongodConn.port); diff --git a/jstests/sharding/shard_aware_primary_failover.js b/jstests/sharding/shard_aware_primary_failover.js index 0d939c6e1ea..127e74b948c 100644 --- a/jstests/sharding/shard_aware_primary_failover.js +++ b/jstests/sharding/shard_aware_primary_failover.js @@ -29,8 +29,8 @@ clusterId: ObjectId() }; - assert.writeOK(primaryConn.getDB('admin') - .system.version.insert(shardIdentityDoc, {writeConcern: {w: 'majority'}})); + assert.writeOK(primaryConn.getDB('admin').system.version.insert( + shardIdentityDoc, {writeConcern: {w: 'majority'}})); replTest.stopMaster(); replTest.waitForMaster(); diff --git a/jstests/sharding/shard_identity_config_update.js b/jstests/sharding/shard_identity_config_update.js index 4eb142d7f20..678a04c79fa 100644 --- a/jstests/sharding/shard_identity_config_update.js +++ b/jstests/sharding/shard_identity_config_update.js @@ -19,8 +19,8 @@ clusterId: ObjectId() }; - var res = conn.getDB('admin') - .system.version.update({_id: 'shardIdentity'}, shardIdentityDoc, true); + var res = conn.getDB('admin').system.version.update( + {_id: 'shardIdentity'}, shardIdentityDoc, true); assert.eq(1, res.nUpserted); }; diff --git a/jstests/sharding/sharding_balance1.js b/jstests/sharding/sharding_balance1.js index d2fad545bba..22a8aaa6210 100644 --- a/jstests/sharding/sharding_balance1.js +++ b/jstests/sharding/sharding_balance1.js @@ -39,16 +39,12 @@ assert.lt(20, diff1(), "big differential here"); print(diff1()); - assert.soon( - function() { - var d = diff1(); - return d < 5; - // Make sure there's enough time here, since balancing can sleep for 15s or so between - // balances. - }, - "balance didn't happen", - 1000 * 60 * 5, - 5000); + assert.soon(function() { + var d = diff1(); + return d < 5; + // Make sure there's enough time here, since balancing can sleep for 15s or so between + // balances. + }, "balance didn't happen", 1000 * 60 * 5, 5000); s.stop(); })(); diff --git a/jstests/sharding/sharding_balance4.js b/jstests/sharding/sharding_balance4.js index 91c9d5ce9ad..170448cbf11 100644 --- a/jstests/sharding/sharding_balance4.js +++ b/jstests/sharding/sharding_balance4.js @@ -35,13 +35,9 @@ // function doUpdate(bulk, includeString, optionalId) { - var up = { - $inc: {x: 1} - }; + var up = {$inc: {x: 1}}; if (includeString) { - up["$set"] = { - s: bigString - }; + up["$set"] = {s: bigString}; } var myid = optionalId == undefined ? Random.randInt(N) : optionalId; bulk.find({_id: myid}).upsert().update(up); diff --git a/jstests/sharding/sharding_options.js b/jstests/sharding/sharding_options.js index 0841967b18e..333b53e9cfd 100644 --- a/jstests/sharding/sharding_options.js +++ b/jstests/sharding/sharding_options.js @@ -4,9 +4,7 @@ load('jstests/libs/command_line/test_parsed_options.js'); // Move Paranoia jsTest.log("Testing \"moveParanoia\" command line option"); -var expectedResult = { - "parsed": {"sharding": {"archiveMovedChunks": true}} -}; +var expectedResult = {"parsed": {"sharding": {"archiveMovedChunks": true}}}; testGetCmdLineOptsMongod({moveParanoia: ""}, expectedResult); jsTest.log("Testing \"noMoveParanoia\" command line option"); @@ -51,9 +49,7 @@ testGetCmdLineOptsMongod({config: "jstests/libs/config_files/set_shardingrole.js // Auto Splitting jsTest.log("Testing \"noAutoSplit\" command line option"); -var expectedResult = { - "parsed": {"sharding": {"autoSplit": false}} -}; +var expectedResult = {"parsed": {"sharding": {"autoSplit": false}}}; testGetCmdLineOptsMongos({noAutoSplit: ""}, expectedResult); jsTest.log("Testing \"sharding.autoSplit\" config file option"); diff --git a/jstests/sharding/sharding_rs2.js b/jstests/sharding/sharding_rs2.js index 7c323ac5d44..ed15592a9b2 100644 --- a/jstests/sharding/sharding_rs2.js +++ b/jstests/sharding/sharding_rs2.js @@ -19,10 +19,16 @@ other: { chunkSize: 1, rs0: { - nodes: [{rsConfig: {votes: 1}}, {rsConfig: {priority: 0, votes: 0}}, ], + nodes: [ + {rsConfig: {votes: 1}}, + {rsConfig: {priority: 0, votes: 0}}, + ], }, rs1: { - nodes: [{rsConfig: {votes: 1}}, {rsConfig: {priority: 0, votes: 0}}, ], + nodes: [ + {rsConfig: {votes: 1}}, + {rsConfig: {priority: 0, votes: 0}}, + ], } } }); diff --git a/jstests/sharding/sharding_state_after_stepdown.js b/jstests/sharding/sharding_state_after_stepdown.js index 3007b4b08a2..6bd2f4927cc 100644 --- a/jstests/sharding/sharding_state_after_stepdown.js +++ b/jstests/sharding/sharding_state_after_stepdown.js @@ -38,22 +38,12 @@ st.rs0.stop(rs0Primary); st.rs1.stop(rs1Primary); - ReplSetTest.awaitRSClientHosts(mongos, - [rs0Primary, rs1Primary], - { - ok: - false - }); + ReplSetTest.awaitRSClientHosts(mongos, [rs0Primary, rs1Primary], {ok: false}); st.rs0.start(rs0Primary, Object.extend(rs0Primary.savedOptions, {restart: true})); st.rs1.start(rs1Primary, Object.extend(rs1Primary.savedOptions, {restart: true})); - ReplSetTest.awaitRSClientHosts(mongos, - [rs0Primary, rs1Primary], - { - ismaster: - true - }); + ReplSetTest.awaitRSClientHosts(mongos, [rs0Primary, rs1Primary], {ismaster: true}); }; restartPrimaries(); @@ -109,12 +99,7 @@ // Expected connection exception, will check for stepdown later } - ReplSetTest.awaitRSClientHosts(mongos, - [rs0Primary, rs1Primary], - { - secondary: - true - }); + ReplSetTest.awaitRSClientHosts(mongos, [rs0Primary, rs1Primary], {secondary: true}); assert.commandWorked(new Mongo(rs0Primary.host).adminCommand({replSetFreeze: 0})); assert.commandWorked(new Mongo(rs1Primary.host).adminCommand({replSetFreeze: 0})); @@ -126,12 +111,7 @@ assert.commandWorked(rs0Primary.adminCommand({connPoolSync: true})); assert.commandWorked(rs1Primary.adminCommand({connPoolSync: true})); - ReplSetTest.awaitRSClientHosts(mongos, - [rs0Primary, rs1Primary], - { - ismaster: - true - }); + ReplSetTest.awaitRSClientHosts(mongos, [rs0Primary, rs1Primary], {ismaster: true}); }; stepDownPrimaries(); @@ -140,30 +120,26 @@ // // No sharding metadata until shards are hit by a metadata operation assert.eq({}, - st.rs0.getPrimary().adminCommand({ - getShardVersion: collSharded.toString(), - fullMetadata: true - }).metadata); + st.rs0.getPrimary() + .adminCommand({getShardVersion: collSharded.toString(), fullMetadata: true}) + .metadata); assert.eq({}, - st.rs1.getPrimary().adminCommand({ - getShardVersion: collSharded.toString(), - fullMetadata: true - }).metadata); + st.rs1.getPrimary() + .adminCommand({getShardVersion: collSharded.toString(), fullMetadata: true}) + .metadata); // // // Metadata commands should enable sharding data implicitly assert.commandWorked(mongos.adminCommand({split: collSharded.toString(), middle: {_id: 0}})); assert.eq({}, - st.rs0.getPrimary().adminCommand({ - getShardVersion: collSharded.toString(), - fullMetadata: true - }).metadata); + st.rs0.getPrimary() + .adminCommand({getShardVersion: collSharded.toString(), fullMetadata: true}) + .metadata); assert.neq({}, - st.rs1.getPrimary().adminCommand({ - getShardVersion: collSharded.toString(), - fullMetadata: true - }).metadata); + st.rs1.getPrimary() + .adminCommand({getShardVersion: collSharded.toString(), fullMetadata: true}) + .metadata); // // @@ -171,15 +147,13 @@ assert.commandWorked(mongos.adminCommand( {moveChunk: collSharded.toString(), find: {_id: 0}, to: shards[0]._id})); assert.neq({}, - st.rs0.getPrimary().adminCommand({ - getShardVersion: collSharded.toString(), - fullMetadata: true - }).metadata); + st.rs0.getPrimary() + .adminCommand({getShardVersion: collSharded.toString(), fullMetadata: true}) + .metadata); assert.neq({}, - st.rs1.getPrimary().adminCommand({ - getShardVersion: collSharded.toString(), - fullMetadata: true - }).metadata); + st.rs1.getPrimary() + .adminCommand({getShardVersion: collSharded.toString(), fullMetadata: true}) + .metadata); st.stop(); diff --git a/jstests/sharding/sort1.js b/jstests/sharding/sort1.js index 57bae9dc390..5cf8dcfd901 100644 --- a/jstests/sharding/sort1.js +++ b/jstests/sharding/sort1.js @@ -54,10 +54,9 @@ z = db.data.find().sort({'sub.num': 1}).toArray(); }, 200); assert.eq(100, z.length, "C1"); - b = 1.5 * - Date.timeFunc(function() { - z = s.getPrimaryShard("test").getDB("test").data.find().sort({'sub.num': 1}).toArray(); - }, 200); + b = 1.5 * Date.timeFunc(function() { + z = s.getPrimaryShard("test").getDB("test").data.find().sort({'sub.num': 1}).toArray(); + }, 200); assert.eq(67, z.length, "C2"); print("a: " + a + " b:" + b + " mongos slow down: " + Math.ceil(100 * ((a - b) / b)) + "%"); diff --git a/jstests/sharding/split_large_key.js b/jstests/sharding/split_large_key.js index 5a8fe060c67..0468fce757b 100644 --- a/jstests/sharding/split_large_key.js +++ b/jstests/sharding/split_large_key.js @@ -38,10 +38,7 @@ tests.forEach(function(test) { var collName = "split_large_key_" + test.name; var midKey = {}; - var chunkKeys = { - min: {}, - max: {} - }; + var chunkKeys = {min: {}, max: {}}; for (var k in test.key) { // new Array with join creates string length 1 less than size, so add 1 midKey[k] = new Array(test.keyFieldSize + 1).join('a'); diff --git a/jstests/sharding/split_with_force.js b/jstests/sharding/split_with_force.js index c66d2f145eb..35e25b5803e 100644 --- a/jstests/sharding/split_with_force.js +++ b/jstests/sharding/split_with_force.js @@ -40,13 +40,15 @@ jsTest.log("Get split points of the chunk using force : true..."); var maxChunkSizeBytes = 1024 * 1024; -var splitKeys = shardAdmin.runCommand({ - splitVector: coll + "", - keyPattern: {_id: 1}, - min: {_id: 0}, - max: {_id: MaxKey}, - force: true -}).splitKeys; +var splitKeys = shardAdmin + .runCommand({ + splitVector: coll + "", + keyPattern: {_id: 1}, + min: {_id: 0}, + max: {_id: MaxKey}, + force: true + }) + .splitKeys; printjson(splitKeys); printjson(coll.stats()); diff --git a/jstests/sharding/stale_mongos_updates_and_removes.js b/jstests/sharding/stale_mongos_updates_and_removes.js index 791120f6f82..d5d03fcb442 100644 --- a/jstests/sharding/stale_mongos_updates_and_removes.js +++ b/jstests/sharding/stale_mongos_updates_and_removes.js @@ -76,12 +76,8 @@ var makeStaleMongosTargetSingleShard = function() { }; var checkAllRemoveQueries = function(makeMongosStaleFunc) { - var multi = { - justOne: false - }; - var single = { - justOne: true - }; + var multi = {justOne: false}; + var single = {justOne: true}; var doRemove = function(query, multiOption, makeMongosStaleFunc) { makeMongosStaleFunc(); @@ -119,23 +115,12 @@ var checkAllRemoveQueries = function(makeMongosStaleFunc) { }; var checkAllUpdateQueries = function(makeMongosStaleFunc) { - var oUpdate = { - $inc: {fieldToUpdate: 1} - }; // op-style update (non-idempotent) - var rUpdate = { - x: 0, - fieldToUpdate: 1 - }; // replacement-style update (idempotent) - var queryAfterUpdate = { - fieldToUpdate: 1 - }; + var oUpdate = {$inc: {fieldToUpdate: 1}}; // op-style update (non-idempotent) + var rUpdate = {x: 0, fieldToUpdate: 1}; // replacement-style update (idempotent) + var queryAfterUpdate = {fieldToUpdate: 1}; - var multi = { - multi: true - }; - var single = { - multi: false - }; + var multi = {multi: true}; + var single = {multi: false}; var doUpdate = function(query, update, multiOption, makeMongosStaleFunc) { makeMongosStaleFunc(); @@ -200,20 +185,14 @@ var freshMongos = st.s0; var staleMongos = st.s1; var emptyQuery = {}; -var pointQuery = { - x: 0 -}; +var pointQuery = {x: 0}; // Choose a range that would fall on only one shard. // Use (splitPoint - 1) because of SERVER-20768. -var rangeQuery = { - x: {$gte: 0, $lt: splitPoint - 1} -}; +var rangeQuery = {x: {$gte: 0, $lt: splitPoint - 1}}; // Choose points that would fall on two different shards. -var multiPointQuery = { - $or: [{x: 0}, {x: numShardKeys}] -}; +var multiPointQuery = {$or: [{x: 0}, {x: numShardKeys}]}; checkAllRemoveQueries(makeStaleMongosTargetSingleShard); checkAllRemoveQueries(makeStaleMongosTargetMultipleShards); diff --git a/jstests/sharding/stats.js b/jstests/sharding/stats.js index da6d842fb99..36ce75b520e 100644 --- a/jstests/sharding/stats.js +++ b/jstests/sharding/stats.js @@ -192,9 +192,7 @@ } // indexDetailsKey - show indexDetails results for this index key only. - var indexKey = { - a: 1 - }; + var indexKey = {a: 1}; var indexName = getIndexName(indexKey); checkIndexDetails({indexDetails: true, indexDetailsKey: indexKey}, indexName); diff --git a/jstests/sharding/top_chunk_autosplit.js b/jstests/sharding/top_chunk_autosplit.js index 74a3e942cae..b4bf2c96e60 100644 --- a/jstests/sharding/top_chunk_autosplit.js +++ b/jstests/sharding/top_chunk_autosplit.js @@ -72,10 +72,7 @@ function runTest(test) { // Insert one doc at a time until first auto-split occurs on top chunk var xval = test.inserts.value; do { - var doc = { - x: xval, - val: largeStr - }; + var doc = {x: xval, val: largeStr}; coll.insert(doc); xval += test.inserts.inc; } while (getNumberOfChunks(configDB) <= numChunks); @@ -108,44 +105,17 @@ var configDB = st.s.getDB('config'); // Define shard key ranges for each of the shard nodes var MINVAL = -500; var MAXVAL = 1500; -var lowChunkRange = { - min: MINVAL, - max: 0 -}; -var midChunkRange1 = { - min: 0, - max: 500 -}; -var midChunkRange2 = { - min: 500, - max: 1000 -}; -var highChunkRange = { - min: 1000, - max: MAXVAL -}; - -var lowChunkTagRange = { - min: MinKey, - max: 0 -}; -var highChunkTagRange = { - min: 1000, - max: MaxKey -}; - -var lowChunkInserts = { - value: 0, - inc: -1 -}; -var midChunkInserts = { - value: 1, - inc: 1 -}; -var highChunkInserts = { - value: 1000, - inc: 1 -}; +var lowChunkRange = {min: MINVAL, max: 0}; +var midChunkRange1 = {min: 0, max: 500}; +var midChunkRange2 = {min: 500, max: 1000}; +var highChunkRange = {min: 1000, max: MAXVAL}; + +var lowChunkTagRange = {min: MinKey, max: 0}; +var highChunkTagRange = {min: 1000, max: MaxKey}; + +var lowChunkInserts = {value: 0, inc: -1}; +var midChunkInserts = {value: 1, inc: 1}; +var highChunkInserts = {value: 1000, inc: 1}; var lowChunk = 1; var highChunk = -1; diff --git a/jstests/slow1/mr_during_migrate.js b/jstests/slow1/mr_during_migrate.js index cb439aeb241..61a06f11249 100644 --- a/jstests/slow1/mr_during_migrate.js +++ b/jstests/slow1/mr_during_migrate.js @@ -83,9 +83,7 @@ for (var t = 0; t < numTests; t++) { var total = 0; for (var i = 0; i < vals.length; i++) total += vals[i].c; - return { - c: total - }; + return {c: total}; }; printjson(coll.find({_id: 0}).itcount()); diff --git a/jstests/slow1/remove_during_mr.js b/jstests/slow1/remove_during_mr.js index 9b632a11a56..508a17e6f2a 100644 --- a/jstests/slow1/remove_during_mr.js +++ b/jstests/slow1/remove_during_mr.js @@ -20,10 +20,7 @@ function client2() { } for (var i = 0; i < 1000; i++) { - var options = { - out: {replace: 'bar'}, - sort: {_id: -1} - }; + var options = {out: {replace: 'bar'}, sort: {_id: -1}}; db.remove_during_mr.mapReduce(mapper, reducer, options); } diff --git a/jstests/ssl/disable_x509.js b/jstests/ssl/disable_x509.js index 5663f6a6196..c386b84c591 100644 --- a/jstests/ssl/disable_x509.js +++ b/jstests/ssl/disable_x509.js @@ -29,9 +29,12 @@ if (cmdOut.ok) { }); // Localhost exception should not be in place anymore - assert.throws(function() { - test.foo.findOne(); - }, {}, "read without login"); + assert.throws( + function() { + test.foo.findOne(); + }, + {}, + "read without login"); assert(external.auth({user: CLIENT_USER, mechanism: 'MONGODB-X509'}), "authentication with valid user failed"); diff --git a/jstests/ssl/libs/ssl_helpers.js b/jstests/ssl/libs/ssl_helpers.js index 8067076610e..50463d8dec9 100644 --- a/jstests/ssl/libs/ssl_helpers.js +++ b/jstests/ssl/libs/ssl_helpers.js @@ -9,9 +9,7 @@ var CLIENT_CERT = "jstests/libs/client.pem"; // Note: "sslAllowInvalidCertificates" is enabled to avoid // hostname conflicts with our testing certificates -var disabled = { - sslMode: "disabled" -}; +var disabled = {sslMode: "disabled"}; var allowSSL = { sslMode: "allowSSL", sslAllowInvalidCertificates: "", @@ -81,10 +79,13 @@ function testShardedLookup(shardingTest) { assert.writeOK(fooBulk.execute()); assert.writeOK(barBulk.execute()); - var docs = lookupdb.foo.aggregate([ - {$sort: {_id: 1}}, - {$lookup: {from: "bar", localField: "_id", foreignField: "_id", as: "bar_docs"}} - ]).toArray(); + var docs = + lookupdb.foo + .aggregate([ + {$sort: {_id: 1}}, + {$lookup: {from: "bar", localField: "_id", foreignField: "_id", as: "bar_docs"}} + ]) + .toArray(); assert.eq(lookupShouldReturn, docs, "error $lookup failed in this configuration"); assert.commandWorked(lookupdb.dropDatabase()); } diff --git a/jstests/ssl/ssl_hostname_validation.js b/jstests/ssl/ssl_hostname_validation.js index ab727320744..9801e14807c 100644 --- a/jstests/ssl/ssl_hostname_validation.js +++ b/jstests/ssl/ssl_hostname_validation.js @@ -8,8 +8,8 @@ var CLIENT_CERT = "jstests/libs/client.pem"; var BAD_SAN_CERT = "jstests/libs/badSAN.pem"; function testCombination(certPath, allowInvalidHost, allowInvalidCert, shouldSucceed) { - var mongod = MongoRunner.runMongod( - {sslMode: "requireSSL", sslPEMKeyFile: certPath, sslCAFile: CA_CERT}); + var mongod = + MongoRunner.runMongod({sslMode: "requireSSL", sslPEMKeyFile: certPath, sslCAFile: CA_CERT}); var mongo; if (allowInvalidCert) { diff --git a/jstests/ssl/ssl_without_ca.js b/jstests/ssl/ssl_without_ca.js index 0e865cc5fee..2255e019883 100644 --- a/jstests/ssl/ssl_without_ca.js +++ b/jstests/ssl/ssl_without_ca.js @@ -36,11 +36,7 @@ MongoRunner.stopMongod(conn.port); jsTest.log("Assert mongod doesn\'t start with CA file missing and clusterAuthMode=x509."); -var sslParams = { - clusterAuthMode: 'x509', - sslMode: 'requireSSL', - sslPEMKeyFile: SERVER_CERT -}; +var sslParams = {clusterAuthMode: 'x509', sslMode: 'requireSSL', sslPEMKeyFile: SERVER_CERT}; var conn = MongoRunner.runMongod(sslParams); assert.isnull(conn, "server started with x509 clusterAuthMode but no CA file"); diff --git a/jstests/ssl/upgrade_to_x509_ssl.js b/jstests/ssl/upgrade_to_x509_ssl.js index e9d79859077..2072d6c51c5 100644 --- a/jstests/ssl/upgrade_to_x509_ssl.js +++ b/jstests/ssl/upgrade_to_x509_ssl.js @@ -44,17 +44,16 @@ assert.eq(2, rstConn1.getDB("test").a.count(), "Error interacting with replSet") print("===== UPGRADE allowSSL,sendKeyfile -> preferSSL,sendX509 ====="); authAllNodes(); rst.awaitReplication(); -rst.upgradeSet( - { - sslMode: "preferSSL", - sslPEMKeyFile: SERVER_CERT, - sslAllowInvalidCertificates: "", - clusterAuthMode: "sendX509", - keyFile: KEYFILE, - sslCAFile: CA_CERT - }, - "root", - "pwd"); +rst.upgradeSet({ + sslMode: "preferSSL", + sslPEMKeyFile: SERVER_CERT, + sslAllowInvalidCertificates: "", + clusterAuthMode: "sendX509", + keyFile: KEYFILE, + sslCAFile: CA_CERT +}, + "root", + "pwd"); // The upgradeSet call restarts the nodes so we need to reauthenticate. authAllNodes(); var rstConn3 = rst.getPrimary(); @@ -66,17 +65,16 @@ var canConnectNoSSL = runMongoProgram("mongo", "--port", rst.ports[0], "--eval", assert.eq(0, canConnectNoSSL, "SSL Connection attempt failed when it should succeed"); print("===== UPGRADE preferSSL,sendX509 -> requireSSL,x509 ====="); -rst.upgradeSet( - { - sslMode: "requireSSL", - sslPEMKeyFile: SERVER_CERT, - sslAllowInvalidCertificates: "", - clusterAuthMode: "x509", - keyFile: KEYFILE, - sslCAFile: CA_CERT - }, - "root", - "pwd"); +rst.upgradeSet({ + sslMode: "requireSSL", + sslPEMKeyFile: SERVER_CERT, + sslAllowInvalidCertificates: "", + clusterAuthMode: "x509", + keyFile: KEYFILE, + sslCAFile: CA_CERT +}, + "root", + "pwd"); authAllNodes(); var rstConn4 = rst.getPrimary(); rstConn4.getDB("test").a.insert({a: 4, str: "TESTTESTTEST"}); diff --git a/jstests/ssl/x509_client.js b/jstests/ssl/x509_client.js index 82c726fc0fd..8c3b7254198 100644 --- a/jstests/ssl/x509_client.js +++ b/jstests/ssl/x509_client.js @@ -29,16 +29,22 @@ function authAndTest(mongo) { test = mongo.getDB("test"); // It should be impossible to create users with the same name as the server's subject - assert.throws(function() { - external.createUser( - {user: SERVER_USER, roles: [{'role': 'userAdminAnyDatabase', 'db': 'admin'}]}); - }, {}, "Created user with same name as the server's x.509 subject"); + assert.throws( + function() { + external.createUser( + {user: SERVER_USER, roles: [{'role': 'userAdminAnyDatabase', 'db': 'admin'}]}); + }, + {}, + "Created user with same name as the server's x.509 subject"); // It should be impossible to create users with names recognized as cluster members - assert.throws(function() { - external.createUser( - {user: INTERNAL_USER, roles: [{'role': 'userAdminAnyDatabase', 'db': 'admin'}]}); - }, {}, "Created user which would be recognized as a cluster member"); + assert.throws( + function() { + external.createUser( + {user: INTERNAL_USER, roles: [{'role': 'userAdminAnyDatabase', 'db': 'admin'}]}); + }, + {}, + "Created user which would be recognized as a cluster member"); // Add user using localhost exception external.createUser({ @@ -56,9 +62,12 @@ function authAndTest(mongo) { }); // Localhost exception should not be in place anymore - assert.throws(function() { - test.foo.findOne(); - }, {}, "read without login"); + assert.throws( + function() { + test.foo.findOne(); + }, + {}, + "read without login"); assert(!external.auth({user: INVALID_CLIENT_USER, mechanism: 'MONGODB-X509'}), "authentication with invalid user failed"); @@ -71,17 +80,16 @@ function authAndTest(mongo) { test.foo.findOne(); external.logout(); - assert.throws(function() { - test.foo.findOne(); - }, {}, "read after logout"); + assert.throws( + function() { + test.foo.findOne(); + }, + {}, + "read after logout"); } print("1. Testing x.509 auth to mongod"); -var x509_options = { - sslMode: "requireSSL", - sslPEMKeyFile: SERVER_CERT, - sslCAFile: CA_CERT -}; +var x509_options = {sslMode: "requireSSL", sslPEMKeyFile: SERVER_CERT, sslCAFile: CA_CERT}; var mongo = MongoRunner.runMongod(Object.merge(x509_options, {auth: ""})); diff --git a/jstests/sslSpecial/mixed_mode_sharded_transition_nossl.js b/jstests/sslSpecial/mixed_mode_sharded_transition_nossl.js index 4978b56e11f..85f775c3b6b 100644 --- a/jstests/sslSpecial/mixed_mode_sharded_transition_nossl.js +++ b/jstests/sslSpecial/mixed_mode_sharded_transition_nossl.js @@ -12,9 +12,7 @@ load('jstests/ssl/libs/ssl_helpers.js'); 'use strict'; // Disable auth explicitly - var noAuthOptions = { - noauth: '' - }; + var noAuthOptions = {noauth: ''}; var transitionToX509AllowSSL = Object.merge(allowSSL, {transitionToAuth: '', clusterAuthMode: 'x509'}); var x509RequireSSL = Object.merge(requireSSL, {clusterAuthMode: 'x509'}); diff --git a/jstests/sslSpecial/ssl_mixedmode.js b/jstests/sslSpecial/ssl_mixedmode.js index 085740f0a26..a9eefa16a2c 100644 --- a/jstests/sslSpecial/ssl_mixedmode.js +++ b/jstests/sslSpecial/ssl_mixedmode.js @@ -6,9 +6,7 @@ load("jstests/libs/ssl_test.js"); function testCombination(sslMode, sslShell, shouldSucceed) { - var serverOptionOverrides = { - sslMode: sslMode - }; + var serverOptionOverrides = {sslMode: sslMode}; var clientOptions = sslShell ? SSLTest.prototype.defaultSSLClientOptions : SSLTest.prototype.noSSLClientOptions; diff --git a/jstests/sslSpecial/upgrade_noauth_to_x509_nossl.js b/jstests/sslSpecial/upgrade_noauth_to_x509_nossl.js index 964397397de..9e56c43f81e 100644 --- a/jstests/sslSpecial/upgrade_noauth_to_x509_nossl.js +++ b/jstests/sslSpecial/upgrade_noauth_to_x509_nossl.js @@ -16,9 +16,7 @@ load('jstests/ssl/libs/ssl_helpers.js'); var dbName = 'upgradeToX509'; // Disable auth explicitly - var noAuth = { - noauth: '' - }; + var noAuth = {noauth: ''}; // Undefine the flags we're replacing, otherwise upgradeSet will keep old values. var transitionToX509AllowSSL = diff --git a/jstests/sslSpecial/upgrade_to_x509_ssl_nossl.js b/jstests/sslSpecial/upgrade_to_x509_ssl_nossl.js index ec29c991e9d..47cc303069c 100644 --- a/jstests/sslSpecial/upgrade_to_x509_ssl_nossl.js +++ b/jstests/sslSpecial/upgrade_to_x509_ssl_nossl.js @@ -38,17 +38,16 @@ assert.eq(1, rstConn1.getDB("test").a.count(), "Error interacting with replSet") print("===== UPGRADE disabled,keyFile -> allowSSL,sendKeyfile ====="); authAllNodes(); -rst.upgradeSet( - { - sslMode: "allowSSL", - sslPEMKeyFile: SERVER_CERT, - sslAllowInvalidCertificates: "", - clusterAuthMode: "sendKeyFile", - keyFile: KEYFILE, - sslCAFile: CA_CERT - }, - "root", - "pwd"); +rst.upgradeSet({ + sslMode: "allowSSL", + sslPEMKeyFile: SERVER_CERT, + sslAllowInvalidCertificates: "", + clusterAuthMode: "sendKeyFile", + keyFile: KEYFILE, + sslCAFile: CA_CERT +}, + "root", + "pwd"); authAllNodes(); rst.awaitReplication(); @@ -57,17 +56,16 @@ rstConn2.getDB("test").a.insert({a: 2, str: "CHECKCHECKCHECK"}); assert.eq(2, rstConn2.getDB("test").a.count(), "Error interacting with replSet"); print("===== UPGRADE allowSSL,sendKeyfile -> preferSSL,sendX509 ====="); -rst.upgradeSet( - { - sslMode: "preferSSL", - sslPEMKeyFile: SERVER_CERT, - sslAllowInvalidCertificates: "", - clusterAuthMode: "sendX509", - keyFile: KEYFILE, - sslCAFile: CA_CERT - }, - "root", - "pwd"); +rst.upgradeSet({ + sslMode: "preferSSL", + sslPEMKeyFile: SERVER_CERT, + sslAllowInvalidCertificates: "", + clusterAuthMode: "sendX509", + keyFile: KEYFILE, + sslCAFile: CA_CERT +}, + "root", + "pwd"); authAllNodes(); rst.awaitReplication(); @@ -88,17 +86,16 @@ assert.eq(0, canConnectSSL, "SSL Connection attempt failed when it should succee print("===== UPGRADE preferSSL,sendX509 -> preferSSL,x509 ====="); // we cannot upgrade past preferSSL here because it will break the test client -rst.upgradeSet( - { - sslMode: "preferSSL", - sslPEMKeyFile: SERVER_CERT, - sslAllowInvalidCertificates: "", - clusterAuthMode: "x509", - keyFile: KEYFILE, - sslCAFile: CA_CERT - }, - "root", - "pwd"); +rst.upgradeSet({ + sslMode: "preferSSL", + sslPEMKeyFile: SERVER_CERT, + sslAllowInvalidCertificates: "", + clusterAuthMode: "x509", + keyFile: KEYFILE, + sslCAFile: CA_CERT +}, + "root", + "pwd"); authAllNodes(); rst.awaitReplication(); var rstConn4 = rst.getPrimary(); diff --git a/jstests/tool/csvimport1.js b/jstests/tool/csvimport1.js index 28258bbe37f..0bcdcc8e789 100644 --- a/jstests/tool/csvimport1.js +++ b/jstests/tool/csvimport1.js @@ -17,8 +17,7 @@ base.push({ }); base.push({ a: 3, - b: - " This line contains the empty string and has leading and trailing whitespace inside the quotes! ", + b: " This line contains the empty string and has leading and trailing whitespace inside the quotes! ", "c": "" }); base.push({a: 4, b: "", "c": "How are empty entries handled?"}); diff --git a/jstests/tool/dumprestore7.js b/jstests/tool/dumprestore7.js index 0598e73c0a8..9235dd9c450 100644 --- a/jstests/tool/dumprestore7.js +++ b/jstests/tool/dumprestore7.js @@ -48,14 +48,13 @@ step("try mongodump with $timestamp"); var data = MongoRunner.dataDir + "/dumprestore7-dump1/"; var query = "{\"ts\":{\"$gt\":{\"$timestamp\":{\"t\":" + time.ts.t + ",\"i\":" + time.ts.i + "}}}}"; -MongoRunner.runMongoTool("mongodump", - { - "host": "127.0.0.1:" + replTest.ports[0], - "db": "local", - "collection": "oplog.rs", - "query": query, - "out": data - }); +MongoRunner.runMongoTool("mongodump", { + "host": "127.0.0.1:" + replTest.ports[0], + "db": "local", + "collection": "oplog.rs", + "query": query, + "out": data +}); step("try mongorestore from $timestamp"); diff --git a/jstests/tool/dumprestore8.js b/jstests/tool/dumprestore8.js index 9cdae87df80..4e76e8bd60c 100644 --- a/jstests/tool/dumprestore8.js +++ b/jstests/tool/dumprestore8.js @@ -31,9 +31,8 @@ db.bar.ensureIndex({x: 1}); barDocCount = db.bar.count(); assert.gt(barDocCount, 0, "No documents inserted"); assert.lt(db.bar.count(), 1000, "Capped collection didn't evict documents"); -assert.eq(5, - db.foo.getIndexes().length + db.bar.getIndexes().length, - "Indexes weren't created right"); +assert.eq( + 5, db.foo.getIndexes().length + db.bar.getIndexes().length, "Indexes weren't created right"); // Full dump/restore diff --git a/jstests/tool/dumprestoreWithNoOptions.js b/jstests/tool/dumprestoreWithNoOptions.js index 1062abd1e94..a1782d3ff7c 100644 --- a/jstests/tool/dumprestoreWithNoOptions.js +++ b/jstests/tool/dumprestoreWithNoOptions.js @@ -24,11 +24,7 @@ db.dropDatabase(); var defaultFlags = {}; -var options = { - capped: true, - size: 4096, - autoIndexId: true -}; +var options = {capped: true, size: 4096, autoIndexId: true}; db.createCollection('capped', options); assert.eq(1, db.capped.getIndexes().length, "auto index not created"); var cappedOptions = db.capped.exists().options; @@ -58,11 +54,7 @@ assert.eq(defaultFlags, // Dump/restore single DB db.dropDatabase(); -var options = { - capped: true, - size: 4096, - autoIndexId: true -}; +var options = {capped: true, size: 4096, autoIndexId: true}; db.createCollection('capped', options); assert.eq(1, db.capped.getIndexes().length, "auto index not created"); var cappedOptions = db.capped.exists().options; @@ -92,11 +84,7 @@ assert.eq(defaultFlags, // Dump/restore single collection db.dropDatabase(); -var options = { - capped: true, - size: 4096, - autoIndexId: true -}; +var options = {capped: true, size: 4096, autoIndexId: true}; db.createCollection('capped', options); assert.eq(1, db.capped.getIndexes().length, "auto index not created"); var cappedOptions = db.capped.exists().options; diff --git a/jstests/tool/dumprestore_auth3.js b/jstests/tool/dumprestore_auth3.js index b59c5c1a951..8fb70d2a91b 100644 --- a/jstests/tool/dumprestore_auth3.js +++ b/jstests/tool/dumprestore_auth3.js @@ -4,9 +4,7 @@ // Runs the tool with the given name against the given mongod. function runTool(toolName, mongod, options) { - var opts = { - host: mongod.host - }; + var opts = {host: mongod.host}; Object.extend(opts, options); MongoRunner.runMongoTool(toolName, opts); } @@ -138,15 +136,13 @@ var dumpRestoreAuth3 = function(backup_role, restore_role) { jsTestLog("Restore foo database (and user data) with --drop so it overrides the changes made"); // Restore with --drop to override the changes to user data - runTool("mongorestore", - mongod, - { - dir: dumpDir + "foo/", - db: 'foo', - drop: "", - restoreDbUsersAndRoles: "", - writeConcern: "0" - }); + runTool("mongorestore", mongod, { + dir: dumpDir + "foo/", + db: 'foo', + drop: "", + restoreDbUsersAndRoles: "", + writeConcern: "0" + }); db = mongod.getDB('foo'); admindb = mongod.getDB('admin'); diff --git a/jstests/tool/dumprestore_excludecollections.js b/jstests/tool/dumprestore_excludecollections.js index 4563b8ffc03..c3f18065ce3 100644 --- a/jstests/tool/dumprestore_excludecollections.js +++ b/jstests/tool/dumprestore_excludecollections.js @@ -23,37 +23,35 @@ ret = MongoRunner.runMongoTool("mongodump", assert.neq(ret, 0, "mongodump started successfully with --excludeCollection but no --db option"); resetDbpath(dumpDir); -ret = MongoRunner.runMongoTool("mongodump", - { - out: dumpDir, - db: testBaseName, - collection: "foo", - excludeCollection: "test", - host: mongodSource.host - }); +ret = MongoRunner.runMongoTool("mongodump", { + out: dumpDir, + db: testBaseName, + collection: "foo", + excludeCollection: "test", + host: mongodSource.host +}); assert.neq(ret, 0, "mongodump started successfully with --excludeCollection and --collection"); resetDbpath(dumpDir); ret = MongoRunner.runMongoTool( "mongodump", {out: dumpDir, excludeCollectionsWithPrefix: "test", host: mongodSource.host}); -assert.neq(ret, - 0, - "mongodump started successfully with --excludeCollectionsWithPrefix but " + - "no --db option"); +assert.neq( + ret, + 0, + "mongodump started successfully with --excludeCollectionsWithPrefix but " + "no --db option"); resetDbpath(dumpDir); -ret = MongoRunner.runMongoTool("mongodump", - { - out: dumpDir, - db: testBaseName, - collection: "foo", - excludeCollectionsWithPrefix: "test", - host: mongodSource.host - }); -assert.neq(ret, - 0, - "mongodump started successfully with --excludeCollectionsWithPrefix and " + - "--collection"); +ret = MongoRunner.runMongoTool("mongodump", { + out: dumpDir, + db: testBaseName, + collection: "foo", + excludeCollectionsWithPrefix: "test", + host: mongodSource.host +}); +assert.neq( + ret, + 0, + "mongodump started successfully with --excludeCollectionsWithPrefix and " + "--collection"); jsTest.log("Testing proper behavior of collection exclusion"); resetDbpath(dumpDir); @@ -75,13 +73,12 @@ assert.eq(destDB.foo2.findOne().f, 2, "Wrong value in document"); destDB.dropDatabase(); resetDbpath(dumpDir); -ret = MongoRunner.runMongoTool("mongodump", - { - out: dumpDir, - db: testBaseName, - excludeCollectionsWithPrefix: "test", - host: mongodSource.host - }); +ret = MongoRunner.runMongoTool("mongodump", { + out: dumpDir, + db: testBaseName, + excludeCollectionsWithPrefix: "test", + host: mongodSource.host +}); ret = MongoRunner.runMongoTool("mongorestore", {dir: dumpDir, host: mongodDest.host}); assert.eq(ret, 0, "failed to run mongodump on expected successful call"); @@ -95,14 +92,13 @@ assert.eq(destDB.foo2.findOne().f, 2, "Wrong value in document"); destDB.dropDatabase(); resetDbpath(dumpDir); -ret = MongoRunner.runMongoTool("mongodump", - { - out: dumpDir, - db: testBaseName, - excludeCollection: "foo", - excludeCollectionsWithPrefix: "test", - host: mongodSource.host - }); +ret = MongoRunner.runMongoTool("mongodump", { + out: dumpDir, + db: testBaseName, + excludeCollection: "foo", + excludeCollectionsWithPrefix: "test", + host: mongodSource.host +}); ret = MongoRunner.runMongoTool("mongorestore", {dir: dumpDir, host: mongodDest.host}); assert.eq(ret, 0, "failed to run mongodump on expected successful call"); diff --git a/jstests/tool/exportimport_bigarray.js b/jstests/tool/exportimport_bigarray.js index 0b801699d1b..60642b6afb1 100644 --- a/jstests/tool/exportimport_bigarray.js +++ b/jstests/tool/exportimport_bigarray.js @@ -11,10 +11,7 @@ dst.drop(); // Calculate the number of documents it takes to get above 16MB (here using 20MB just to be safe) var bigString = new Array(1025).toString(); -var doc = { - _id: new ObjectId(), - x: bigString -}; +var doc = {_id: new ObjectId(), x: bigString}; var docSize = Object.bsonsize(doc); var numDocs = Math.floor(20 * 1024 * 1024 / docSize); diff --git a/jstests/tool/tool_replset.js b/jstests/tool/tool_replset.js index efe55b46605..3b0338a02d4 100644 --- a/jstests/tool/tool_replset.js +++ b/jstests/tool/tool_replset.js @@ -67,17 +67,8 @@ var x = master.getDB("foo").getCollection("bar").count(); assert.eq(x, 100, "mongoimport should have successfully imported the collection"); - var doc = { - _id: 5, - x: 17 - }; - var oplogEntry = { - ts: new Timestamp(), - "op": "i", - "ns": "foo.bar", - "o": doc, - "v": NumberInt(2) - }; + var doc = {_id: 5, x: 17}; + var oplogEntry = {ts: new Timestamp(), "op": "i", "ns": "foo.bar", "o": doc, "v": NumberInt(2)}; assert.writeOK(master.getDB("local").oplog.rs.insert(oplogEntry)); assert.eq(100, |