aboutsummaryrefslogtreecommitdiff
path: root/contexts/data/lib/closure-library/closure/goog/testing/mockclassfactory.js
blob: 4f71b398c42889e5eeb593750baf435d9c53f804 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview This file defines a factory that can be used to mock and
 * replace an entire class.  This allows for mocks to be used effectively with
 * "new" instead of having to inject all instances.  Essentially, a given class
 * is replaced with a proxy to either a loose or strict mock.  Proxies locate
 * the appropriate mock based on constructor arguments.
 *
 * The usage is:
 * <ul>
 *   <li>Create a mock with one of the provided methods with a specifc set of
 *       constructor arguments
 *   <li>Set expectations by calling methods on the mock object
 *   <li>Call $replay() on the mock object
 *   <li>Instantiate the object as normal
 *   <li>Call $verify() to make sure that expectations were met
 *   <li>Call reset on the factory to revert all classes back to their original
 *       state
 * </ul>
 *
 * For examples, please see the unit test.
 *
 */


goog.provide('goog.testing.MockClassFactory');
goog.provide('goog.testing.MockClassRecord');

goog.require('goog.array');
goog.require('goog.object');
goog.require('goog.testing.LooseMock');
goog.require('goog.testing.StrictMock');
goog.require('goog.testing.TestCase');
goog.require('goog.testing.mockmatchers');



/**
 * A record that represents all the data associated with a mock replacement of
 * a given class.
 * @param {Object} namespace The namespace in which the mocked class resides.
 * @param {string} className The name of the class within the namespace.
 * @param {Function} originalClass The original class implementation before it
 *     was replaced by a proxy.
 * @param {Function} proxy The proxy that replaced the original class.
 * @constructor
 */
goog.testing.MockClassRecord = function(namespace, className, originalClass,
    proxy) {
  /**
   * A standard closure namespace (e.g. goog.foo.bar) that contains the mock
   * class referenced by this MockClassRecord.
   * @type {Object}
   * @private
   */
  this.namespace_ = namespace;

  /**
   * The name of the class within the provided namespace.
   * @type {string}
   * @private
   */
  this.className_ = className;

  /**
   * The original class implementation.
   * @type {Function}
   * @private
   */
  this.originalClass_ = originalClass;

  /**
   * The proxy being used as a replacement for the original class.
   * @type {Function}
   * @private
   */
  this.proxy_ = proxy;

  /**
   * A mocks that will be constructed by their argument list.  The entries are
   * objects with the format {'args': args, 'mock': mock}.
   * @type {Array.<Object>}
   * @private
   */
  this.instancesByArgs_ = [];
};


/**
 * A mock associated with the static functions for a given class.
 * @type {goog.testing.StrictMock|goog.testing.LooseMock|null}
 * @private
 */
goog.testing.MockClassRecord.prototype.staticMock_ = null;


/**
 * A getter for this record's namespace.
 * @return {Object} The namespace.
 */
goog.testing.MockClassRecord.prototype.getNamespace = function() {
  return this.namespace_;
};


/**
 * A getter for this record's class name.
 * @return {string} The name of the class referenced by this record.
 */
goog.testing.MockClassRecord.prototype.getClassName = function() {
  return this.className_;
};


/**
 * A getter for the original class.
 * @return {Function} The original class implementation before mocking.
 */
goog.testing.MockClassRecord.prototype.getOriginalClass = function() {
  return this.originalClass_;
};


/**
 * A getter for the proxy being used as a replacement for the original class.
 * @return {Function} The proxy.
 */
goog.testing.MockClassRecord.prototype.getProxy = function() {
  return this.proxy_;
};


/**
 * A getter for the static mock.
 * @return {goog.testing.StrictMock|goog.testing.LooseMock|null} The static
 *     mock associated with this record.
 */
goog.testing.MockClassRecord.prototype.getStaticMock = function() {
  return this.staticMock_;
};


/**
 * A setter for the static mock.
 * @param {goog.testing.StrictMock|goog.testing.LooseMock} staticMock A mock to
 *     associate with the static functions for the referenced class.
 */
goog.testing.MockClassRecord.prototype.setStaticMock = function(staticMock) {
  this.staticMock_ = staticMock;
};


/**
 * Adds a new mock instance mapping.  The mapping connects a set of function
 * arguments to a specific mock instance.
 * @param {Array} args An array of function arguments.
 * @param {goog.testing.StrictMock|goog.testing.LooseMock} mock A mock
 *     associated with the supplied arguments.
 */
goog.testing.MockClassRecord.prototype.addMockInstance = function(args, mock) {
  this.instancesByArgs_.push({args: args, mock: mock});
};


/**
 * Finds the mock corresponding to a given argument set.  Throws an error if
 * there is no appropriate match found.
 * @param {Array} args An array of function arguments.
 * @return {goog.testing.StrictMock|goog.testing.LooseMock|null} The mock
 *     corresponding to a given argument set.
 */
goog.testing.MockClassRecord.prototype.findMockInstance = function(args) {
  for (var i = 0; i < this.instancesByArgs_.length; i++) {
    var instanceArgs = this.instancesByArgs_[i].args;
    if (goog.testing.mockmatchers.flexibleArrayMatcher(instanceArgs, args)) {
      return this.instancesByArgs_[i].mock;
    }
  }

  return null;
};


/**
 * Resets this record by reverting all the mocked classes back to the original
 * implementation and clearing out the mock instance list.
 */
goog.testing.MockClassRecord.prototype.reset = function() {
  this.namespace_[this.className_] = this.originalClass_;
  this.instancesByArgs_ = [];
};



/**
 * A factory used to create new mock class instances.  It is able to generate
 * both static and loose mocks.  The MockClassFactory is a singleton since it
 * tracks the classes that have been mocked internally.
 * @constructor
 */
goog.testing.MockClassFactory = function() {
  if (goog.testing.MockClassFactory.instance_) {
    return goog.testing.MockClassFactory.instance_;
  }

  /**
   * A map from class name -> goog.testing.MockClassRecord.
   * @type {Object}
   * @private
   */
  this.mockClassRecords_ = {};

  goog.testing.MockClassFactory.instance_ = this;
};


/**
 * A singleton instance of the MockClassFactory.
 * @type {goog.testing.MockClassFactory?}
 * @private
 */
goog.testing.MockClassFactory.instance_ = null;


/**
 * The names of the fields that are defined on Object.prototype.
 * @type {Array.<string>}
 * @private
 */
goog.testing.MockClassFactory.PROTOTYPE_FIELDS_ = [
  'constructor',
  'hasOwnProperty',
  'isPrototypeOf',
  'propertyIsEnumerable',
  'toLocaleString',
  'toString',
  'valueOf'
];


/**
 * Iterates through a namespace to find the name of a given class.  This is done
 * solely to support compilation since string identifiers would break down.
 * Tests usually aren't compiled, but the functionality is supported.
 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
 * @param {Function} classToMock The class whose name should be returned.
 * @return {string} The name of the class.
 * @private
 */
goog.testing.MockClassFactory.prototype.getClassName_ = function(namespace,
    classToMock) {
  if (namespace === goog.global) {
    namespace = goog.testing.TestCase.getGlobals();
  }
  for (var prop in namespace) {
    if (namespace[prop] === classToMock) {
      return prop;
    }
  }

  throw Error('Class is not a part of the given namespace');
};


/**
 * Returns whether or not a given class has been mocked.
 * @param {string} className The name of the class.
 * @return {boolean} Whether or not the given class name has a MockClassRecord.
 * @private
 */
goog.testing.MockClassFactory.prototype.classHasMock_ = function(className) {
  return !!this.mockClassRecords_[className];
};


/**
 * Returns a proxy constructor closure.  Since this is a constructor, "this"
 * refers to the local scope of the constructed object thus bind cannot be
 * used.
 * @param {string} className The name of the class.
 * @param {Function} mockFinder A bound function that returns the mock
 *     associated with a class given the constructor's argument list.
 * @return {Function} A proxy constructor.
 * @private
 */
goog.testing.MockClassFactory.prototype.getProxyCtor_ = function(className,
    mockFinder) {
  return function() {
    this.$mock_ = mockFinder(className, arguments);
    if (!this.$mock_) {
      // The "arguments" variable is not a proper Array so it must be converted.
      var args = Array.prototype.slice.call(arguments, 0);
      throw Error('No mock found for ' + className + ' with arguments ' +
          args.join(', '));
    }
  };
};


/**
 * Returns a proxy function for a mock class instance.  This function cannot
 * be used with bind since "this" must refer to the scope of the proxy
 * constructor.
 * @param {string} fnName The name of the function that should be proxied.
 * @return {Function} A proxy function.
 * @private
 */
goog.testing.MockClassFactory.prototype.getProxyFunction_ = function(fnName) {
  return function() {
    return this.$mock_[fnName].apply(this.$mock_, arguments);
  };
};


/**
 * Find a mock instance for a given class name and argument list.
 * @param {string} className The name of the class.
 * @param {Array} args The argument list to match.
 * @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock found for
 *     the given argument list.
 * @private
 */
goog.testing.MockClassFactory.prototype.findMockInstance_ = function(className,
    args) {
  return this.mockClassRecords_[className].findMockInstance(args);
};


/**
 * Create a proxy class.  A proxy will pass functions to the mock for a class.
 * The proxy class only covers prototype methods.  A static mock is not build
 * simultaneously since it might be strict or loose.  The proxy class inherits
 * from the target class in order to preserve instanceof checks.
 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
 * @param {Function} classToMock The class that will be proxied.
 * @param {string} className The name of the class.
 * @return {Function} The proxy for provided class.
 * @private
 */
goog.testing.MockClassFactory.prototype.createProxy_ = function(namespace,
    classToMock, className) {
  var proxy = this.getProxyCtor_(className,
      goog.bind(this.findMockInstance_, this));
  var protoToProxy = classToMock.prototype;
  goog.inherits(proxy, classToMock);

  for (var prop in protoToProxy) {
    if (goog.isFunction(protoToProxy[prop])) {
      proxy.prototype[prop] = this.getProxyFunction_(prop);
    }
  }

  // For IE the for-in-loop does not contain any properties that are not
  // enumerable on the prototype object (for example isPrototypeOf from
  // Object.prototype) and it will also not include 'replace' on objects that
  // extend String and change 'replace' (not that it is common for anyone to
  // extend anything except Object).
  // TODO (arv): Implement goog.object.getIterator and replace this loop.

  goog.array.forEach(goog.testing.MockClassFactory.PROTOTYPE_FIELDS_,
      function(field) {
        if (Object.prototype.hasOwnProperty.call(protoToProxy, field)) {
          proxy.prototype[field] = this.getProxyFunction_(field);
        }
      }, this);

  this.mockClassRecords_[className] = new goog.testing.MockClassRecord(
      namespace, className, classToMock, proxy);
  namespace[className] = proxy;
  return proxy;
};


/**
 * Gets either a loose or strict mock for a given class based on a set of
 * arguments.
 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
 * @param {Function} classToMock The class that will be mocked.
 * @param {boolean} isStrict Whether or not the mock should be strict.
 * @param {Array} ctorArgs The arguments associated with this instance's
 *     constructor.
 * @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock created
 *     for the provided class.
 * @private
 */
goog.testing.MockClassFactory.prototype.getMockClass_ =
    function(namespace, classToMock, isStrict, ctorArgs) {
  var className = this.getClassName_(namespace, classToMock);

  // The namespace and classToMock variables should be removed from the
  // passed in argument stack.
  ctorArgs = goog.array.slice(ctorArgs, 2);

  if (goog.isFunction(classToMock)) {
    var mock = isStrict ? new goog.testing.StrictMock(classToMock) :
        new goog.testing.LooseMock(classToMock);

    if (!this.classHasMock_(className)) {
      this.createProxy_(namespace, classToMock, className);
    } else {
      var instance = this.findMockInstance_(className, ctorArgs);
      if (instance) {
        throw Error('Mock instance already created for ' + className +
            ' with arguments ' + ctorArgs.join(', '));
      }
    }
    this.mockClassRecords_[className].addMockInstance(ctorArgs, mock);

    return mock;
  } else {
    throw Error('Cannot create a mock class for ' + className +
        ' of type ' + typeof classToMock);
  }
};


/**
 * Gets a strict mock for a given class.
 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
 * @param {Function} classToMock The class that will be mocked.
 * @param {...*} var_args The arguments associated with this instance's
 *     constructor.
 * @return {goog.testing.StrictMock} The mock created for the provided class.
 */
goog.testing.MockClassFactory.prototype.getStrictMockClass =
    function(namespace, classToMock, var_args) {
  var args = /** @type {Array} */ (arguments);
  return /** @type {goog.testing.StrictMock} */ (this.getMockClass_(namespace,
      classToMock, true, args));
};


/**
 * Gets a loose mock for a given class.
 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
 * @param {Function} classToMock The class that will be mocked.
 * @param {...*} var_args The arguments associated with this instance's
 *     constructor.
 * @return {goog.testing.LooseMock} The mock created for the provided class.
 */
goog.testing.MockClassFactory.prototype.getLooseMockClass =
    function(namespace, classToMock, var_args) {
  var args = /** @type {Array} */ (arguments);
  return /** @type {goog.testing.LooseMock} */ (this.getMockClass_(namespace,
      classToMock, false, args));
};


/**
 * Creates either a loose or strict mock for the static functions of a given
 * class.
 * @param {Function} classToMock The class whose static functions will be
 *     mocked.  This should be the original class and not the proxy.
 * @param {string} className The name of the class.
 * @param {Function} proxy The proxy that will replace the original class.
 * @param {boolean} isStrict Whether or not the mock should be strict.
 * @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock created
 *     for the static functions of the provided class.
 * @private
 */
goog.testing.MockClassFactory.prototype.createStaticMock_ =
    function(classToMock, className, proxy, isStrict) {
  var mock = isStrict ? new goog.testing.StrictMock(classToMock, true) :
      new goog.testing.LooseMock(classToMock, false, true);

  for (var prop in classToMock) {
    if (goog.isFunction(classToMock[prop])) {
      proxy[prop] = goog.bind(mock.$mockMethod, mock, prop);
    } else if (classToMock[prop] !== classToMock.prototype) {
      proxy[prop] = classToMock[prop];
    }
  }

  this.mockClassRecords_[className].setStaticMock(mock);
  return mock;
};


/**
 * Gets either a loose or strict mock for the static functions of a given class.
 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
 * @param {Function} classToMock The class whose static functions will be
 *     mocked.  This should be the original class and not the proxy.
 * @param {boolean} isStrict Whether or not the mock should be strict.
 * @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock created
 *     for the static functions of the provided class.
 * @private
 */
goog.testing.MockClassFactory.prototype.getStaticMock_ = function(namespace,
    classToMock, isStrict) {
  var className = this.getClassName_(namespace, classToMock);

  if (goog.isFunction(classToMock)) {
    if (!this.classHasMock_(className)) {
      var proxy = this.createProxy_(namespace, classToMock, className);
      var mock = this.createStaticMock_(classToMock, className, proxy,
          isStrict);
      return mock;
    }

    if (!this.mockClassRecords_[className].getStaticMock()) {
      var proxy = this.mockClassRecords_[className].getProxy();
      var originalClass = this.mockClassRecords_[className].getOriginalClass();
      var mock = this.createStaticMock_(originalClass, className, proxy,
          isStrict);
      return mock;
    } else {
      var mock = this.mockClassRecords_[className].getStaticMock();
      var mockIsStrict = mock instanceof goog.testing.StrictMock;

      if (mockIsStrict != isStrict) {
        var mockType = mock instanceof goog.testing.StrictMock ? 'strict' :
            'loose';
        var requestedType = isStrict ? 'strict' : 'loose';
        throw Error('Requested a ' + requestedType + ' static mock, but a ' +
            mockType + ' mock already exists.');
      }

      return mock;
    }
  } else {
    throw Error('Cannot create a mock for the static functions of ' +
        className + ' of type ' + typeof classToMock);
  }
};


/**
 * Gets a strict mock for the static functions of a given class.
 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
 * @param {Function} classToMock The class whose static functions will be
 *     mocked.  This should be the original class and not the proxy.
 * @return {goog.testing.StrictMock} The mock created for the static functions
 *     of the provided class.
 */
goog.testing.MockClassFactory.prototype.getStrictStaticMock =
    function(namespace, classToMock) {
  return /** @type {goog.testing.StrictMock} */ (this.getStaticMock_(namespace,
      classToMock, true));
};


/**
 * Gets a loose mock for the static functions of a given class.
 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
 * @param {Function} classToMock The class whose static functions will be
 *     mocked.  This should be the original class and not the proxy.
 * @return {goog.testing.LooseMock} The mock created for the static functions
 *     of the provided class.
 */
goog.testing.MockClassFactory.prototype.getLooseStaticMock =
    function(namespace, classToMock) {
  return /** @type {goog.testing.LooseMock} */ (this.getStaticMock_(namespace,
      classToMock, false));
};


/**
 * Resests the factory by reverting all mocked classes to their original
 * implementations and removing all MockClassRecords.
 */
goog.testing.MockClassFactory.prototype.reset = function() {
  goog.object.forEach(this.mockClassRecords_, function(record) {
    record.reset();
  });
  this.mockClassRecords_ = {};
};