Debian Codegraph @

closure-library/closure/goog/testing/mockclassfactory.js

raw
1 // Copyright 2008 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview This file defines a factory that can be used to mock and
17 * replace an entire class. This allows for mocks to be used effectively with
18 * "new" instead of having to inject all instances. Essentially, a given class
19 * is replaced with a proxy to either a loose or strict mock. Proxies locate
20 * the appropriate mock based on constructor arguments.
21 *
22 * The usage is:
23 * <ul>
24 * <li>Create a mock with one of the provided methods with a specifc set of
25 * constructor arguments
26 * <li>Set expectations by calling methods on the mock object
27 * <li>Call $replay() on the mock object
28 * <li>Instantiate the object as normal
29 * <li>Call $verify() to make sure that expectations were met
30 * <li>Call reset on the factory to revert all classes back to their original
31 * state
32 * </ul>
33 *
34 * For examples, please see the unit test.
35 *
36 */
37
38
39 goog.setTestOnly('goog.testing.MockClassFactory');
40 goog.provide('goog.testing.MockClassFactory');
41 goog.provide('goog.testing.MockClassRecord');
42
43 goog.require('goog.array');
44 goog.require('goog.object');
45 goog.require('goog.testing.LooseMock');
46 goog.require('goog.testing.StrictMock');
47 goog.require('goog.testing.TestCase');
48 goog.require('goog.testing.mockmatchers');
49
50
51
52 /**
53 * A record that represents all the data associated with a mock replacement of
54 * a given class.
55 * @param {Object} namespace The namespace in which the mocked class resides.
56 * @param {string} className The name of the class within the namespace.
57 * @param {Function} originalClass The original class implementation before it
58 * was replaced by a proxy.
59 * @param {Function} proxy The proxy that replaced the original class.
60 * @constructor
61 * @final
62 */
63 goog.testing.MockClassRecord = function(
64 namespace, className, originalClass, proxy) {
65 /**
66 * A standard closure namespace (e.g. goog.foo.bar) that contains the mock
67 * class referenced by this MockClassRecord.
68 * @type {Object}
69 * @private
70 */
71 this.namespace_ = namespace;
72
73 /**
74 * The name of the class within the provided namespace.
75 * @type {string}
76 * @private
77 */
78 this.className_ = className;
79
80 /**
81 * The original class implementation.
82 * @type {Function}
83 * @private
84 */
85 this.originalClass_ = originalClass;
86
87 /**
88 * The proxy being used as a replacement for the original class.
89 * @type {Function}
90 * @private
91 */
92 this.proxy_ = proxy;
93
94 /**
95 * A mocks that will be constructed by their argument list. The entries are
96 * objects with the format {'args': args, 'mock': mock}.
97 * @type {Array<Object>}
98 * @private
99 */
100 this.instancesByArgs_ = [];
101 };
102
103
104 /**
105 * A mock associated with the static functions for a given class.
106 * @type {goog.testing.StrictMock|goog.testing.LooseMock|null}
107 * @private
108 */
109 goog.testing.MockClassRecord.prototype.staticMock_ = null;
110
111
112 /**
113 * A getter for this record's namespace.
114 * @return {Object} The namespace.
115 */
116 goog.testing.MockClassRecord.prototype.getNamespace = function() {
117 return this.namespace_;
118 };
119
120
121 /**
122 * A getter for this record's class name.
123 * @return {string} The name of the class referenced by this record.
124 */
125 goog.testing.MockClassRecord.prototype.getClassName = function() {
126 return this.className_;
127 };
128
129
130 /**
131 * A getter for the original class.
132 * @return {Function} The original class implementation before mocking.
133 */
134 goog.testing.MockClassRecord.prototype.getOriginalClass = function() {
135 return this.originalClass_;
136 };
137
138
139 /**
140 * A getter for the proxy being used as a replacement for the original class.
141 * @return {Function} The proxy.
142 */
143 goog.testing.MockClassRecord.prototype.getProxy = function() {
144 return this.proxy_;
145 };
146
147
148 /**
149 * A getter for the static mock.
150 * @return {goog.testing.StrictMock|goog.testing.LooseMock|null} The static
151 * mock associated with this record.
152 */
153 goog.testing.MockClassRecord.prototype.getStaticMock = function() {
154 return this.staticMock_;
155 };
156
157
158 /**
159 * A setter for the static mock.
160 * @param {goog.testing.StrictMock|goog.testing.LooseMock} staticMock A mock to
161 * associate with the static functions for the referenced class.
162 */
163 goog.testing.MockClassRecord.prototype.setStaticMock = function(staticMock) {
164 this.staticMock_ = staticMock;
165 };
166
167
168 /**
169 * Adds a new mock instance mapping. The mapping connects a set of function
170 * arguments to a specific mock instance.
171 * @param {Array<?>} args An array of function arguments.
172 * @param {goog.testing.StrictMock|goog.testing.LooseMock} mock A mock
173 * associated with the supplied arguments.
174 */
175 goog.testing.MockClassRecord.prototype.addMockInstance = function(args, mock) {
176 this.instancesByArgs_.push({args: args, mock: mock});
177 };
178
179
180 /**
181 * Finds the mock corresponding to a given argument set. Throws an error if
182 * there is no appropriate match found.
183 * @param {Array<?>} args An array of function arguments.
184 * @return {goog.testing.StrictMock|goog.testing.LooseMock|null} The mock
185 * corresponding to a given argument set.
186 */
187 goog.testing.MockClassRecord.prototype.findMockInstance = function(args) {
188 for (var i = 0; i < this.instancesByArgs_.length; i++) {
189 var instanceArgs = this.instancesByArgs_[i].args;
190 if (goog.testing.mockmatchers.flexibleArrayMatcher(instanceArgs, args)) {
191 return this.instancesByArgs_[i].mock;
192 }
193 }
194
195 return null;
196 };
197
198
199 /**
200 * Resets this record by reverting all the mocked classes back to the original
201 * implementation and clearing out the mock instance list.
202 */
203 goog.testing.MockClassRecord.prototype.reset = function() {
204 this.namespace_[this.className_] = this.originalClass_;
205 this.instancesByArgs_ = [];
206 };
207
208
209
210 /**
211 * A factory used to create new mock class instances. It is able to generate
212 * both static and loose mocks. The MockClassFactory is a singleton since it
213 * tracks the classes that have been mocked internally.
214 * @constructor
215 * @final
216 */
217 goog.testing.MockClassFactory = function() {
218 if (goog.testing.MockClassFactory.instance_) {
219 return goog.testing.MockClassFactory.instance_;
220 }
221
222 /**
223 * A map from class name -> goog.testing.MockClassRecord.
224 * @type {Object}
225 * @private
226 */
227 this.mockClassRecords_ = {};
228
229 goog.testing.MockClassFactory.instance_ = this;
230 };
231
232
233 /**
234 * A singleton instance of the MockClassFactory.
235 * @type {goog.testing.MockClassFactory?}
236 * @private
237 */
238 goog.testing.MockClassFactory.instance_ = null;
239
240
241 /**
242 * The names of the fields that are defined on Object.prototype.
243 * @type {Array<string>}
244 * @private
245 */
246 goog.testing.MockClassFactory.PROTOTYPE_FIELDS_ = [
247 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
248 'toLocaleString', 'toString', 'valueOf'
249 ];
250
251
252 /**
253 * Iterates through a namespace to find the name of a given class. This is done
254 * solely to support compilation since string identifiers would break down.
255 * Tests usually aren't compiled, but the functionality is supported.
256 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
257 * @param {Function} classToMock The class whose name should be returned.
258 * @return {string} The name of the class.
259 * @private
260 */
261 goog.testing.MockClassFactory.prototype.getClassName_ = function(
262 namespace, classToMock) {
263 var namespaces;
264 if (namespace === goog.global) {
265 namespaces = goog.testing.TestCase.getGlobals();
266 } else {
267 namespaces = [namespace];
268 }
269 for (var i = 0; i < namespaces.length; i++) {
270 for (var prop in namespaces[i]) {
271 if (namespaces[i][prop] === classToMock) {
272 return prop;
273 }
274 }
275 }
276
277 throw new Error('Class is not a part of the given namespace');
278 };
279
280
281 /**
282 * Returns whether or not a given class has been mocked.
283 * @param {string} className The name of the class.
284 * @return {boolean} Whether or not the given class name has a MockClassRecord.
285 * @private
286 */
287 goog.testing.MockClassFactory.prototype.classHasMock_ = function(className) {
288 return !!this.mockClassRecords_[className];
289 };
290
291
292 /**
293 * Returns a proxy constructor closure. Since this is a constructor, "this"
294 * refers to the local scope of the constructed object thus bind cannot be
295 * used.
296 * @param {string} className The name of the class.
297 * @param {Function} mockFinder A bound function that returns the mock
298 * associated with a class given the constructor's argument list.
299 * @return {!Function} A proxy constructor.
300 * @private
301 */
302 goog.testing.MockClassFactory.prototype.getProxyCtor_ = function(
303 className, mockFinder) {
304 return function() {
305 this.$mock_ = mockFinder(className, arguments);
306 if (!this.$mock_) {
307 // The "arguments" variable is not a proper Array so it must be converted.
308 var args = Array.prototype.slice.call(arguments, 0);
309 throw new Error(
310 'No mock found for ' + className + ' with arguments ' +
311 args.join(', '));
312 }
313 };
314 };
315
316
317 /**
318 * Returns a proxy function for a mock class instance. This function cannot
319 * be used with bind since "this" must refer to the scope of the proxy
320 * constructor.
321 * @param {string} fnName The name of the function that should be proxied.
322 * @return {!Function} A proxy function.
323 * @private
324 */
325 goog.testing.MockClassFactory.prototype.getProxyFunction_ = function(fnName) {
326 return function() {
327 return this.$mock_[fnName].apply(this.$mock_, arguments);
328 };
329 };
330
331
332 /**
333 * Find a mock instance for a given class name and argument list.
334 * @param {string} className The name of the class.
335 * @param {Array<?>} args The argument list to match.
336 * @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock found for
337 * the given argument list.
338 * @private
339 */
340 goog.testing.MockClassFactory.prototype.findMockInstance_ = function(
341 className, args) {
342 return this.mockClassRecords_[className].findMockInstance(args);
343 };
344
345
346 /**
347 * Create a proxy class. A proxy will pass functions to the mock for a class.
348 * The proxy class only covers prototype methods. A static mock is not build
349 * simultaneously since it might be strict or loose. The proxy class inherits
350 * from the target class in order to preserve instanceof checks.
351 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
352 * @param {Function} classToMock The class that will be proxied.
353 * @param {string} className The name of the class.
354 * @return {!Function} The proxy for provided class.
355 * @private
356 */
357 goog.testing.MockClassFactory.prototype.createProxy_ = function(
358 namespace, classToMock, className) {
359 var proxy =
360 this.getProxyCtor_(className, goog.bind(this.findMockInstance_, this));
361 var protoToProxy = classToMock.prototype;
362 // Preserve base() call in mocked class
363 var classToMockBase = classToMock.base;
364 goog.inherits(proxy, classToMock);
365 proxy.base = classToMockBase;
366
367 for (var prop in protoToProxy) {
368 if (goog.isFunction(protoToProxy[prop])) {
369 proxy.prototype[prop] = this.getProxyFunction_(prop);
370 }
371 }
372
373 // For IE the for-in-loop does not contain any properties that are not
374 // enumerable on the prototype object (for example isPrototypeOf from
375 // Object.prototype) and it will also not include 'replace' on objects that
376 // extend String and change 'replace' (not that it is common for anyone to
377 // extend anything except Object).
378 // TODO (arv): Implement goog.object.getIterator and replace this loop.
379
380 goog.array.forEach(
381 goog.testing.MockClassFactory.PROTOTYPE_FIELDS_, function(field) {
382 if (Object.prototype.hasOwnProperty.call(protoToProxy, field)) {
383 proxy.prototype[field] = this.getProxyFunction_(field);
384 }
385 }, this);
386
387 this.mockClassRecords_[className] = new goog.testing.MockClassRecord(
388 namespace, className, classToMock, proxy);
389 namespace[className] = proxy;
390 return proxy;
391 };
392
393
394 /**
395 * Gets either a loose or strict mock for a given class based on a set of
396 * arguments.
397 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
398 * @param {Function} classToMock The class that will be mocked.
399 * @param {boolean} isStrict Whether or not the mock should be strict.
400 * @param {IArrayLike<?>} ctorArgs The arguments associated with this
401 * instance's constructor.
402 * @return {!goog.testing.StrictMock|!goog.testing.LooseMock} The mock created
403 * for the provided class.
404 * @private
405 */
406 goog.testing.MockClassFactory.prototype.getMockClass_ = function(
407 namespace, classToMock, isStrict, ctorArgs) {
408 var className = this.getClassName_(namespace, classToMock);
409
410 // The namespace and classToMock variables should be removed from the
411 // passed in argument stack.
412 ctorArgs = goog.array.slice(ctorArgs, 2);
413
414 if (goog.isFunction(classToMock)) {
415 var mock = isStrict ? new goog.testing.StrictMock(classToMock) :
416 new goog.testing.LooseMock(classToMock);
417
418 if (!this.classHasMock_(className)) {
419 this.createProxy_(namespace, classToMock, className);
420 } else {
421 var instance = this.findMockInstance_(className, ctorArgs);
422 if (instance) {
423 throw new Error(
424 'Mock instance already created for ' + className +
425 ' with arguments ' + ctorArgs.join(', '));
426 }
427 }
428 this.mockClassRecords_[className].addMockInstance(ctorArgs, mock);
429
430 return mock;
431 } else {
432 throw new Error(
433 'Cannot create a mock class for ' + className + ' of type ' +
434 typeof classToMock);
435 }
436 };
437
438
439 /**
440 * Gets a strict mock for a given class.
441 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
442 * @param {Function} classToMock The class that will be mocked.
443 * @param {...*} var_args The arguments associated with this instance's
444 * constructor.
445 * @return {!goog.testing.StrictMock} The mock created for the provided class.
446 */
447 goog.testing.MockClassFactory.prototype.getStrictMockClass = function(
448 namespace, classToMock, var_args) {
449 return /** @type {!goog.testing.StrictMock} */ (
450 this.getMockClass_(namespace, classToMock, true, arguments));
451 };
452
453
454 /**
455 * Gets a loose mock for a given class.
456 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
457 * @param {Function} classToMock The class that will be mocked.
458 * @param {...*} var_args The arguments associated with this instance's
459 * constructor.
460 * @return {goog.testing.LooseMock} The mock created for the provided class.
461 */
462 goog.testing.MockClassFactory.prototype.getLooseMockClass = function(
463 namespace, classToMock, var_args) {
464 return /** @type {goog.testing.LooseMock} */ (
465 this.getMockClass_(namespace, classToMock, false, arguments));
466 };
467
468
469 /**
470 * Creates either a loose or strict mock for the static functions of a given
471 * class.
472 * @param {Function} classToMock The class whose static functions will be
473 * mocked. This should be the original class and not the proxy.
474 * @param {string} className The name of the class.
475 * @param {Function} proxy The proxy that will replace the original class.
476 * @param {boolean} isStrict Whether or not the mock should be strict.
477 * @return {!goog.testing.StrictMock|!goog.testing.LooseMock} The mock created
478 * for the static functions of the provided class.
479 * @private
480 */
481 goog.testing.MockClassFactory.prototype.createStaticMock_ = function(
482 classToMock, className, proxy, isStrict) {
483 var mock = isStrict ? new goog.testing.StrictMock(classToMock, true) :
484 new goog.testing.LooseMock(classToMock, false, true);
485
486 for (var prop in classToMock) {
487 if (goog.isFunction(classToMock[prop])) {
488 proxy[prop] = goog.bind(mock.$mockMethod, mock, prop);
489 } else if (classToMock[prop] !== classToMock.prototype) {
490 proxy[prop] = classToMock[prop];
491 }
492 }
493
494 this.mockClassRecords_[className].setStaticMock(mock);
495 return mock;
496 };
497
498
499 /**
500 * Gets either a loose or strict mock for the static functions of a given class.
501 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
502 * @param {Function} classToMock The class whose static functions will be
503 * mocked. This should be the original class and not the proxy.
504 * @param {boolean} isStrict Whether or not the mock should be strict.
505 * @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock created
506 * for the static functions of the provided class.
507 * @private
508 */
509 goog.testing.MockClassFactory.prototype.getStaticMock_ = function(
510 namespace, classToMock, isStrict) {
511 var className = this.getClassName_(namespace, classToMock);
512
513 if (goog.isFunction(classToMock)) {
514 if (!this.classHasMock_(className)) {
515 var proxy = this.createProxy_(namespace, classToMock, className);
516 var mock =
517 this.createStaticMock_(classToMock, className, proxy, isStrict);
518 return mock;
519 }
520
521 if (!this.mockClassRecords_[className].getStaticMock()) {
522 var proxy = this.mockClassRecords_[className].getProxy();
523 var originalClass = this.mockClassRecords_[className].getOriginalClass();
524 var mock =
525 this.createStaticMock_(originalClass, className, proxy, isStrict);
526 return mock;
527 } else {
528 var mock = this.mockClassRecords_[className].getStaticMock();
529 var mockIsStrict = mock instanceof goog.testing.StrictMock;
530
531 if (mockIsStrict != isStrict) {
532 var mockType =
533 mock instanceof goog.testing.StrictMock ? 'strict' : 'loose';
534 var requestedType = isStrict ? 'strict' : 'loose';
535 throw new Error(
536 'Requested a ' + requestedType + ' static mock, but a ' + mockType +
537 ' mock already exists.');
538 }
539
540 return mock;
541 }
542 } else {
543 throw new Error(
544 'Cannot create a mock for the static functions of ' + className +
545 ' of type ' + typeof classToMock);
546 }
547 };
548
549
550 /**
551 * Gets a strict mock for the static functions of a given class.
552 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
553 * @param {Function} classToMock The class whose static functions will be
554 * mocked. This should be the original class and not the proxy.
555 * @return {goog.testing.StrictMock} The mock created for the static functions
556 * of the provided class.
557 */
558 goog.testing.MockClassFactory.prototype.getStrictStaticMock = function(
559 namespace, classToMock) {
560 return /** @type {goog.testing.StrictMock} */ (
561 this.getStaticMock_(namespace, classToMock, true));
562 };
563
564
565 /**
566 * Gets a loose mock for the static functions of a given class.
567 * @param {Object} namespace A javascript namespace (e.g. goog.testing).
568 * @param {Function} classToMock The class whose static functions will be
569 * mocked. This should be the original class and not the proxy.
570 * @return {goog.testing.LooseMock} The mock created for the static functions
571 * of the provided class.
572 */
573 goog.testing.MockClassFactory.prototype.getLooseStaticMock = function(
574 namespace, classToMock) {
575 return /** @type {goog.testing.LooseMock} */ (
576 this.getStaticMock_(namespace, classToMock, false));
577 };
578
579
580 /**
581 * Resests the factory by reverting all mocked classes to their original
582 * implementations and removing all MockClassRecords.
583 */
584 goog.testing.MockClassFactory.prototype.reset = function() {
585 goog.object.forEach(
586 this.mockClassRecords_, function(record) { record.reset(); });
587 this.mockClassRecords_ = {};
588 };