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 | |
20 | goog.provide('goog.testing.PropertyReplacer'); |
21 | |
22 | /** @suppress {extraRequire} Needed for some tests to compile. */ |
23 | goog.require('goog.testing.ObjectPropertyString'); |
24 | goog.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 | */ |
65 | goog.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 | * @type {Object} |
81 | * @private |
82 | */ |
83 | goog.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 | */ |
94 | goog.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 | * @private |
133 | */ |
134 | goog.testing.PropertyReplacer.deleteKey_ = function(obj, key) { |
135 | try { |
136 | delete obj[key]; |
137 | // Delete has no effect for built-in properties of DOM nodes in FF. |
138 | if (!goog.testing.PropertyReplacer.hasKey_(obj, key)) { |
139 | return; |
140 | } |
141 | } catch (e) { |
142 | // IE throws TypeError when trying to delete properties of native objects |
143 | // (e.g. DOM nodes or window), even if they have been added by JavaScript. |
144 | } |
145 | |
146 | obj[key] = undefined; |
147 | if (obj[key] == 'undefined') { |
148 | // Some properties such as className in IE are always evaluated as string |
149 | // so undefined will become 'undefined'. |
150 | obj[key] = ''; |
151 | } |
152 | }; |
153 | |
154 | |
155 | /** |
156 | * Adds or changes a value in an object while saving its original state. |
157 | * @param {Object|Function} obj The JavaScript or native object or function to |
158 | * alter. See the constraints in the class description. |
159 | * @param {string} key The key to change the value for. |
160 | * @param {*} value The new value to set. |
161 | */ |
162 | goog.testing.PropertyReplacer.prototype.set = function(obj, key, value) { |
163 | var origValue = goog.testing.PropertyReplacer.hasKey_(obj, key) ? obj[key] : |
164 | goog.testing.PropertyReplacer.NO_SUCH_KEY_; |
165 | this.original_.push({object: obj, key: key, value: origValue}); |
166 | obj[key] = value; |
167 | }; |
168 | |
169 | |
170 | /** |
171 | * Changes an existing value in an object to another one of the same type while |
172 | * saving its original state. The advantage of {@code replace} over {@link #set} |
173 | * is that {@code replace} protects against typos and erroneously passing tests |
174 | * after some members have been renamed during a refactoring. |
175 | * @param {Object|Function} obj The JavaScript or native object or function to |
176 | * alter. See the constraints in the class description. |
177 | * @param {string} key The key to change the value for. It has to be present |
178 | * either in {@code obj} or in its prototype chain. |
179 | * @param {*} value The new value to set. It has to have the same type as the |
180 | * original value. The types are compared with {@link goog.typeOf}. |
181 | * @throws {Error} In case of missing key or type mismatch. |
182 | */ |
183 | goog.testing.PropertyReplacer.prototype.replace = function(obj, key, value) { |
184 | if (!(key in obj)) { |
185 | throw Error('Cannot replace missing property "' + key + '" in ' + obj); |
186 | } |
187 | if (goog.typeOf(obj[key]) != goog.typeOf(value)) { |
188 | throw Error('Cannot replace property "' + key + '" in ' + obj + |
189 | ' with a value of different type'); |
190 | } |
191 | this.set(obj, key, value); |
192 | }; |
193 | |
194 | |
195 | /** |
196 | * Builds an object structure for the provided namespace path. Doesn't |
197 | * overwrite those prefixes of the path that are already objects or functions. |
198 | * @param {string} path The path to create or alter, e.g. 'goog.ui.Menu'. |
199 | * @param {*} value The value to set. |
200 | */ |
201 | goog.testing.PropertyReplacer.prototype.setPath = function(path, value) { |
202 | var parts = path.split('.'); |
203 | var obj = goog.global; |
204 | for (var i = 0; i < parts.length - 1; i++) { |
205 | var part = parts[i]; |
206 | if (part == 'prototype' && !obj[part]) { |
207 | throw Error('Cannot set the prototype of ' + parts.slice(0, i).join('.')); |
208 | } |
209 | if (!goog.isObject(obj[part]) && !goog.isFunction(obj[part])) { |
210 | this.set(obj, part, {}); |
211 | } |
212 | obj = obj[part]; |
213 | } |
214 | this.set(obj, parts[parts.length - 1], value); |
215 | }; |
216 | |
217 | |
218 | /** |
219 | * Deletes the key from the object while saving its original value. |
220 | * @param {Object|Function} obj The JavaScript or native object or function to |
221 | * alter. See the constraints in the class description. |
222 | * @param {string} key The key to delete. |
223 | */ |
224 | goog.testing.PropertyReplacer.prototype.remove = function(obj, key) { |
225 | if (goog.testing.PropertyReplacer.hasKey_(obj, key)) { |
226 | this.original_.push({object: obj, key: key, value: obj[key]}); |
227 | goog.testing.PropertyReplacer.deleteKey_(obj, key); |
228 | } |
229 | }; |
230 | |
231 | |
232 | /** |
233 | * Resets all changes made by goog.testing.PropertyReplacer.prototype.set. |
234 | */ |
235 | goog.testing.PropertyReplacer.prototype.reset = function() { |
236 | for (var i = this.original_.length - 1; i >= 0; i--) { |
237 | var original = this.original_[i]; |
238 | if (original.value == goog.testing.PropertyReplacer.NO_SUCH_KEY_) { |
239 | goog.testing.PropertyReplacer.deleteKey_(original.object, original.key); |
240 | } else { |
241 | original.object[original.key] = original.value; |
242 | } |
243 | delete this.original_[i]; |
244 | } |
245 | this.original_.length = 0; |
246 | }; |