NaryExpression_test.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. "use strict";
  2. var assert = require("assert"),
  3. VariablesParseState = require("../../../../lib/pipeline/expressions/VariablesParseState"),
  4. VariablesIdGenerator = require("../../../../lib/pipeline/expressions/VariablesIdGenerator"),
  5. NaryExpression = require("../../../../lib/pipeline/expressions/NaryExpression"),
  6. ConstantExpression = require("../../../../lib/pipeline/expressions/ConstantExpression"),
  7. FieldPathExpression = require("../../../../lib/pipeline/expressions/FieldPathExpression"),
  8. Expression = require("../../../../lib/pipeline/expressions/Expression"),
  9. utils = require("./utils");
  10. // Mocha one-liner to make these tests self-hosted
  11. if(!module.parent)return(require.cache[__filename]=null,(new(require("mocha"))({ui:"exports",reporter:"spec",grep:process.env.TEST_GREP})).addFile(__filename).run(process.exit));
  12. // A dummy child of NaryExpression used for testing
  13. var Testable = (function(){
  14. // CONSTRUCTOR
  15. var klass = function Testable(isAssociativeAndCommutative){
  16. this._isAssociativeAndCommutative = isAssociativeAndCommutative;
  17. base.call(this);
  18. }, base = NaryExpression, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  19. // MEMBERS
  20. proto.evaluateInternal = function evaluateInternal(vars) {
  21. // Just put all the values in a list. This is not associative/commutative so
  22. // the results will change if a factory is provided and operations are reordered.
  23. var values = [];
  24. for (var i = 0, l = this.operands.length; i < l; i++) {
  25. values.push(this.operands[i].evaluateInternal(vars));
  26. }
  27. return values;
  28. };
  29. proto.getOpName = function getOpName() {
  30. return "$testable";
  31. };
  32. proto.isAssociativeAndCommutative = function isAssociativeAndCommutative(){
  33. return this._isAssociativeAndCommutative;
  34. };
  35. klass.create = function create(associativeAndCommutative) {
  36. return new Testable(Boolean(associativeAndCommutative));
  37. };
  38. klass.factory = function factory() {
  39. return new Testable(true);
  40. };
  41. klass.createFromOperands = function(operands, haveFactory) {
  42. if (haveFactory === undefined) haveFactory = false;
  43. var idGenerator = new VariablesIdGenerator(),
  44. vps = new VariablesParseState(idGenerator),
  45. testable = Testable.create(haveFactory);
  46. operands.forEach(function(element) {
  47. testable.addOperand(Expression.parseOperand(element, vps));
  48. });
  49. return testable;
  50. };
  51. proto.assertContents = function assertContents(expectedContents) {
  52. assert.deepEqual(utils.constify({$testable:expectedContents}), utils.expressionToJson(this));
  53. };
  54. return klass;
  55. })();
  56. exports.NaryExpression = {
  57. ".parseArguments()": {
  58. "should parse a fieldPathExpression": function() {
  59. var vps = new VariablesParseState(new VariablesIdGenerator()),
  60. parsedArguments = NaryExpression.parseArguments("$field.path.expression", vps);
  61. assert.equal(parsedArguments.length, 1);
  62. assert(parsedArguments[0] instanceof FieldPathExpression);
  63. },
  64. "should parse an array of fieldPathExpressions": function() {
  65. var vps = new VariablesParseState(new VariablesIdGenerator()),
  66. parsedArguments = NaryExpression.parseArguments(["$field.path.expression", "$another.FPE"], vps);
  67. assert.equal(parsedArguments.length, 2);
  68. assert(parsedArguments[0] instanceof FieldPathExpression);
  69. assert(parsedArguments[1] instanceof FieldPathExpression);
  70. },
  71. },
  72. /** Adding operands to the expression. */
  73. "AddOperand": function testAddOperand() {
  74. var testable = Testable.create();
  75. testable.addOperand(ConstantExpression.create(9));
  76. testable.assertContents([9]);
  77. testable.addOperand(FieldPathExpression.create("ab.c"));
  78. testable.assertContents([9, "$ab.c"]);
  79. },
  80. /** Dependencies of the expression. */
  81. "Dependencies": function testDependencies() {
  82. var testable = Testable.create();
  83. var assertDependencies = function assertDependencies(expectedDeps, expr) {
  84. var deps = {}, //TODO: new DepsTracker
  85. depsJson = [];
  86. expr.addDependencies(deps);
  87. deps.forEach(function(dep) {
  88. depsJson.push(dep);
  89. });
  90. assert.deepEqual(depsJson, expectedDeps);
  91. assert.equal(deps.needWholeDocument, false);
  92. assert.equal(deps.needTextScore, false);
  93. };
  94. // No arguments.
  95. assertDependencies([], testable);
  96. // Add a constant argument.
  97. testable.addOperand(new ConstantExpression(1));
  98. assertDependencies([], testable);
  99. // Add a field path argument.
  100. testable.addOperand(new FieldPathExpression("ab.c"));
  101. assertDependencies(["ab.c"], testable);
  102. // Add an object expression.
  103. var spec = {a:"$x", q:"$r"},
  104. specElement = spec,
  105. ctx = new Expression.ObjectCtx({isDocumentOk:true}),
  106. vps = new VariablesParseState(new VariablesIdGenerator());
  107. testable.addOperand(Expression.parseObject(specElement, ctx, vps));
  108. assertDependencies(["ab.c", "r", "x"]);
  109. },
  110. /** Serialize to an object. */
  111. "AddToJsonObj": function testAddToJsonObj() {
  112. var testable = Testable.create();
  113. testable.addOperand(new ConstantExpression(5));
  114. assert.deepEqual(
  115. {foo:{$testable:[{$const:5}]}},
  116. {foo:testable.serialize(false)}
  117. );
  118. },
  119. /** Serialize to an array. */
  120. "AddToJsonArray": function testAddToJsonArray() {
  121. var testable = Testable.create();
  122. testable.addOperand(new ConstantExpression(5));
  123. assert.deepEqual(
  124. [{$testable:[{$const:5}]}],
  125. [testable.serialize(false)]
  126. );
  127. },
  128. /** One operand is optimized to a constant, while another is left as is. */
  129. "OptimizeOneOperand": function testOptimizeOneOperand() {
  130. var spec = [{$and:[]}, "$abc"],
  131. testable = Testable.createFromOperands(spec);
  132. testable.assertContents(spec);
  133. assert.deepEqual(testable.serialize(), testable.optimize().serialize());
  134. testable.assertContents([true, "$abc"]);
  135. },
  136. /** All operands are constants, and the operator is evaluated with them. */
  137. "EvaluateAllConstantOperands": function testEvaluateAllConstantOperands() {
  138. var spec = [1, 2],
  139. testable = Testable.createFromOperands(spec);
  140. testable.assertContents(spec);
  141. var optimized = testable.optimize();
  142. assert.notDeepEqual(testable.serialize(), optimized.serialize());
  143. assert.deepEqual({$const:[1,2]}, utils.expressionToJson(optimized));
  144. },
  145. "NoFactoryOptimize": {
  146. // Without factory optimization, optimization will not produce a new expression.
  147. /** A string constant prevents factory optimization. */
  148. "StringConstant": function testStringConstant() {
  149. var testable = Testable.createFromOperands(["abc", "def", "$path"], true);
  150. assert.strictEqual(testable, testable.optimize());
  151. },
  152. /** A single (instead of multiple) constant prevents optimization. SERVER-6192 */
  153. "SingleConstant": function testSingleConstant() {
  154. var testable = Testable.createFromOperands([55, "$path"], true);
  155. assert.strictEqual(testable, testable.optimize());
  156. },
  157. /** Factory optimization is not used without a factory. */
  158. "NoFactory": function testNoFactory() {
  159. var testable = Testable.createFromOperands([55, 66, "$path"], false);
  160. assert.strictEqual(testable, testable.optimize());
  161. },
  162. },
  163. /** Factory optimization separates constant from non constant expressions. */
  164. "FactoryOptimize": function testFactoryOptimize() {
  165. // The constant expressions are evaluated separately and placed at the end.
  166. var testable = Testable.createFromOperands([55, 66, "$path"], true),
  167. optimized = testable.optimize();
  168. assert.deepEqual(utils.constify({$testable:["$path", [55, 66]]}), utils.expressionToJson(optimized));
  169. },
  170. /** Factory optimization flattens nested operators of the same type. */
  171. "FlattenOptimize": function testFlattenOptimize() {
  172. var testable = Testable.createFromOperands(
  173. [55, "$path", {$add:[5,6,"$q"]}, 66],
  174. true);
  175. testable.addOperand(Testable.createFromOperands(
  176. [99, 100, "$another_path"],
  177. true));
  178. var optimized = testable.optimize();
  179. assert.deepEqual(
  180. utils.constify({$testable:[
  181. "$path",
  182. {$add:["$q", 11]},
  183. "$another_path",
  184. [55, 66, [99, 100]]
  185. ]}),
  186. utils.expressionToJson(optimized));
  187. },
  188. /** Three layers of factory optimization are flattened. */
  189. "FlattenThreeLayers": function testFlattenThreeLayers() {
  190. var top = Testable.createFromOperands([1, 2, "$a"], true),
  191. nested = Testable.createFromOperands([3, 4, "$b"], true);
  192. nested.addOperand(Testable.createFromOperands([5, 6, "$c"], true));
  193. top.addOperand(nested);
  194. var optimized = top.optimize();
  195. assert.deepEqual(
  196. utils.constify({
  197. $testable: ["$a", "$b", "$c", [1, 2, [3, 4, [5, 6]]]]
  198. }),
  199. utils.expressionToJson(optimized)
  200. );
  201. },
  202. };