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