lib/goog/testing/propertyreplacer.js

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 Helper class for creating stubs for testing.
17 *
18 */
19
20goog.provide('goog.testing.PropertyReplacer');
21
22/** @suppress {extraRequire} Needed for some tests to compile. */
23goog.require('goog.testing.ObjectPropertyString');
24goog.require('goog.userAgent');
25
26
27
28/**
29 * Helper class for stubbing out variables and object properties for unit tests.
30 * This class can change the value of some variables before running the test
31 * cases, and to reset them in the tearDown phase.
32 * See googletest.StubOutForTesting as an analogy in Python:
33 * http://protobuf.googlecode.com/svn/trunk/python/stubout.py
34 *
35 * Example usage:
36 * <pre>var stubs = new goog.testing.PropertyReplacer();
37 *
38 * function setUp() {
39 * // Mock functions used in all test cases.
40 * stubs.set(Math, 'random', function() {
41 * return 4; // Chosen by fair dice roll. Guaranteed to be random.
42 * });
43 * }
44 *
45 * function tearDown() {
46 * stubs.reset();
47 * }
48 *
49 * function testThreeDice() {
50 * // Mock a constant used only in this test case.
51 * stubs.set(goog.global, 'DICE_COUNT', 3);
52 * assertEquals(12, rollAllDice());
53 * }</pre>
54 *
55 * Constraints on altered objects:
56 * <ul>
57 * <li>DOM subclasses aren't supported.
58 * <li>The value of the objects' constructor property must either be equal to
59 * the real constructor or kept untouched.
60 * </ul>
61 *
62 * @constructor
63 * @final
64 */
65goog.testing.PropertyReplacer = function() {
66 /**
67 * Stores the values changed by the set() method in chronological order.
68 * Its items are objects with 3 fields: 'object', 'key', 'value'. The
69 * original value for the given key in the given object is stored under the
70 * 'value' key.
71 * @type {Array<Object>}
72 * @private
73 */
74 this.original_ = [];
75};
76
77
78/**
79 * Indicates that a key didn't exist before having been set by the set() method.
80 * @private @const
81 */
82goog.testing.PropertyReplacer.NO_SUCH_KEY_ = {};
83
84
85/**
86 * Tells if the given key exists in the object. Ignores inherited fields.
87 * @param {Object|Function} obj The JavaScript or native object or function
88 * whose key is to be checked.
89 * @param {string} key The key to check.
90 * @return {boolean} Whether the object has the key as own key.
91 * @private
92 */
93goog.testing.PropertyReplacer.hasKey_ = function(obj, key) {
94 if (!(key in obj)) {
95 return false;
96 }
97 // hasOwnProperty is only reliable with JavaScript objects. It returns false
98 // for built-in DOM attributes.
99 if (Object.prototype.hasOwnProperty.call(obj, key)) {
100 return true;
101 }
102 // In all browsers except Opera obj.constructor never equals to Object if
103 // obj is an instance of a native class. In Opera we have to fall back on
104 // examining obj.toString().
105 if (obj.constructor == Object &&
106 (!goog.userAgent.OPERA ||
107 Object.prototype.toString.call(obj) == '[object Object]')) {
108 return false;
109 }
110 try {
111 // Firefox hack to consider "className" part of the HTML elements or
112 // "body" part of document. Although they are defined in the prototype of
113 // HTMLElement or Document, accessing them this way throws an exception.
114 // <pre>
115 // var dummy = document.body.constructor.prototype.className
116 // [Exception... "Cannot modify properties of a WrappedNative"]
117 // </pre>
118 var dummy = obj.constructor.prototype[key];
119 } catch (e) {
120 return true;
121 }
122 return !(key in obj.constructor.prototype);
123};
124
125
126/**
127 * Deletes a key from an object. Sets it to undefined or empty string if the
128 * delete failed.
129 * @param {Object|Function} obj The object or function to delete a key from.
130 * @param {string} key The key to delete.
131 * @private
132 */
133goog.testing.PropertyReplacer.deleteKey_ = function(obj, key) {
134 try {
135 delete obj[key];
136 // Delete has no effect for built-in properties of DOM nodes in FF.
137 if (!goog.testing.PropertyReplacer.hasKey_(obj, key)) {
138 return;
139 }
140 } catch (e) {
141 // IE throws TypeError when trying to delete properties of native objects
142 // (e.g. DOM nodes or window), even if they have been added by JavaScript.
143 }
144
145 obj[key] = undefined;
146 if (obj[key] == 'undefined') {
147 // Some properties such as className in IE are always evaluated as string
148 // so undefined will become 'undefined'.
149 obj[key] = '';
150 }
151};
152
153
154/**
155 * Adds or changes a value in an object while saving its original state.
156 * @param {Object|Function} obj The JavaScript or native object or function to
157 * alter. See the constraints in the class description.
158 * @param {string} key The key to change the value for.
159 * @param {*} value The new value to set.
160 */
161goog.testing.PropertyReplacer.prototype.set = function(obj, key, value) {
162 var origValue = goog.testing.PropertyReplacer.hasKey_(obj, key) ? obj[key] :
163 goog.testing.PropertyReplacer.NO_SUCH_KEY_;
164 this.original_.push({object: obj, key: key, value: origValue});
165 obj[key] = value;
166};
167
168
169/**
170 * Changes an existing value in an object to another one of the same type while
171 * saving its original state. The advantage of {@code replace} over {@link #set}
172 * is that {@code replace} protects against typos and erroneously passing tests
173 * after some members have been renamed during a refactoring.
174 * @param {Object|Function} obj The JavaScript or native object or function to
175 * alter. See the constraints in the class description.
176 * @param {string} key The key to change the value for. It has to be present
177 * either in {@code obj} or in its prototype chain.
178 * @param {*} value The new value to set. It has to have the same type as the
179 * original value. The types are compared with {@link goog.typeOf}.
180 * @throws {Error} In case of missing key or type mismatch.
181 */
182goog.testing.PropertyReplacer.prototype.replace = function(obj, key, value) {
183 if (!(key in obj)) {
184 throw Error('Cannot replace missing property "' + key + '" in ' + obj);
185 }
186 if (goog.typeOf(obj[key]) != goog.typeOf(value)) {
187 throw Error('Cannot replace property "' + key + '" in ' + obj +
188 ' with a value of different type');
189 }
190 this.set(obj, key, value);
191};
192
193
194/**
195 * Builds an object structure for the provided namespace path. Doesn't
196 * overwrite those prefixes of the path that are already objects or functions.
197 * @param {string} path The path to create or alter, e.g. 'goog.ui.Menu'.
198 * @param {*} value The value to set.
199 */
200goog.testing.PropertyReplacer.prototype.setPath = function(path, value) {
201 var parts = path.split('.');
202 var obj = goog.global;
203 for (var i = 0; i < parts.length - 1; i++) {
204 var part = parts[i];
205 if (part == 'prototype' && !obj[part]) {
206 throw Error('Cannot set the prototype of ' + parts.slice(0, i).join('.'));
207 }
208 if (!goog.isObject(obj[part]) && !goog.isFunction(obj[part])) {
209 this.set(obj, part, {});
210 }
211 obj = obj[part];
212 }
213 this.set(obj, parts[parts.length - 1], value);
214};
215
216
217/**
218 * Deletes the key from the object while saving its original value.
219 * @param {Object|Function} obj The JavaScript or native object or function to
220 * alter. See the constraints in the class description.
221 * @param {string} key The key to delete.
222 */
223goog.testing.PropertyReplacer.prototype.remove = function(obj, key) {
224 if (goog.testing.PropertyReplacer.hasKey_(obj, key)) {
225 this.original_.push({object: obj, key: key, value: obj[key]});
226 goog.testing.PropertyReplacer.deleteKey_(obj, key);
227 }
228};
229
230
231/**
232 * Resets all changes made by goog.testing.PropertyReplacer.prototype.set.
233 */
234goog.testing.PropertyReplacer.prototype.reset = function() {
235 for (var i = this.original_.length - 1; i >= 0; i--) {
236 var original = this.original_[i];
237 if (original.value == goog.testing.PropertyReplacer.NO_SUCH_KEY_) {
238 goog.testing.PropertyReplacer.deleteKey_(original.object, original.key);
239 } else {
240 original.object[original.key] = original.value;
241 }
242 delete this.original_[i];
243 }
244 this.original_.length = 0;
245};