| 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.setTestOnly('goog.testing.PropertyReplacer'); |
| 21 |
goog.provide('goog.testing.PropertyReplacer'); |
| 22 |
|
| 23 |
/** @suppress {extraRequire} Needed for some tests to compile. */ |
| 24 |
goog.require('goog.testing.ObjectPropertyString'); |
| 25 |
goog.require('goog.userAgent'); |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
/** |
| 30 |
* Helper class for stubbing out variables and object properties for unit tests. |
| 31 |
* This class can change the value of some variables before running the test |
| 32 |
* cases, and to reset them in the tearDown phase. |
| 33 |
* See googletest.StubOutForTesting as an analogy in Python: |
| 34 |
* http://protobuf.googlecode.com/svn/trunk/python/stubout.py |
| 35 |
* |
| 36 |
* Example usage: |
| 37 |
* |
| 38 |
* var stubs = new goog.testing.PropertyReplacer(); |
| 39 |
* |
| 40 |
* function setUp() { |
| 41 |
* // Mock functions used in all test cases. |
| 42 |
* stubs.replace(Math, 'random', function() { |
| 43 |
* return 4; // Chosen by fair dice roll. Guaranteed to be random. |
| 44 |
* }); |
| 45 |
* } |
| 46 |
* |
| 47 |
* function tearDown() { |
| 48 |
* stubs.reset(); |
| 49 |
* } |
| 50 |
* |
| 51 |
* function testThreeDice() { |
| 52 |
* // Mock a constant used only in this test case. |
| 53 |
* stubs.set(goog.global, 'DICE_COUNT', 3); |
| 54 |
* assertEquals(12, rollAllDice()); |
| 55 |
* } |
| 56 |
* |
| 57 |
* Constraints on altered objects: |
| 58 |
* <ul> |
| 59 |
* <li>DOM subclasses aren't supported. |
| 60 |
* <li>The value of the objects' constructor property must either be equal to |
| 61 |
* the real constructor or kept untouched. |
| 62 |
* </ul> |
| 63 |
* |
| 64 |
* Code compiled with property renaming may need to use {@code |
| 65 |
* goog.reflect.objectProperty} instead of simply naming the property to |
| 66 |
* replace. |
| 67 |
* |
| 68 |
* @constructor |
| 69 |
* @final |
| 70 |
*/ |
| 71 |
goog.testing.PropertyReplacer = function() { |
| 72 |
/** |
| 73 |
* Stores the values changed by the set() method in chronological order. |
| 74 |
* Its items are objects with 3 fields: 'object', 'key', 'value'. The |
| 75 |
* original value for the given key in the given object is stored under the |
| 76 |
* 'value' key. |
| 77 |
* @type {Array<{ object: ?, key: string, value: ? }>} |
| 78 |
* @private |
| 79 |
*/ |
| 80 |
this.original_ = []; |
| 81 |
}; |
| 82 |
|
| 83 |
|
| 84 |
/** |
| 85 |
* Indicates that a key didn't exist before having been set by the set() method. |
| 86 |
* @private @const |
| 87 |
*/ |
| 88 |
goog.testing.PropertyReplacer.NO_SUCH_KEY_ = {}; |
| 89 |
|
| 90 |
|
| 91 |
/** |
| 92 |
* Tells if the given key exists in the object. Ignores inherited fields. |
| 93 |
* @param {Object|Function} obj The JavaScript or native object or function |
| 94 |
* whose key is to be checked. |
| 95 |
* @param {string} key The key to check. |
| 96 |
* @return {boolean} Whether the object has the key as own key. |
| 97 |
* @private |
| 98 |
* @suppress {unusedLocalVariables} |
| 99 |
*/ |
| 100 |
goog.testing.PropertyReplacer.hasKey_ = function(obj, key) { |
| 101 |
if (!(key in obj)) { |
| 102 |
return false; |
| 103 |
} |
| 104 |
// hasOwnProperty is only reliable with JavaScript objects. It returns false |
| 105 |
// for built-in DOM attributes. |
| 106 |
if (Object.prototype.hasOwnProperty.call(obj, key)) { |
| 107 |
return true; |
| 108 |
} |
| 109 |
// In all browsers except Opera obj.constructor never equals to Object if |
| 110 |
// obj is an instance of a native class. In Opera we have to fall back on |
| 111 |
// examining obj.toString(). |
| 112 |
if (obj.constructor == Object && |
| 113 |
(!goog.userAgent.OPERA || |
| 114 |
Object.prototype.toString.call(obj) == '[object Object]')) { |
| 115 |
return false; |
| 116 |
} |
| 117 |
try { |
| 118 |
// Firefox hack to consider "className" part of the HTML elements or |
| 119 |
// "body" part of document. Although they are defined in the prototype of |
| 120 |
// HTMLElement or Document, accessing them this way throws an exception. |
| 121 |
// <pre> |
| 122 |
// var dummy = document.body.constructor.prototype.className |
| 123 |
// [Exception... "Cannot modify properties of a WrappedNative"] |
| 124 |
// </pre> |
| 125 |
var dummy = obj.constructor.prototype[key]; |
| 126 |
} catch (e) { |
| 127 |
return true; |
| 128 |
} |
| 129 |
return !(key in obj.constructor.prototype); |
| 130 |
}; |
| 131 |
|
| 132 |
|
| 133 |
/** |
| 134 |
* Deletes a key from an object. Sets it to undefined or empty string if the |
| 135 |
* delete failed. |
| 136 |
* @param {Object|Function} obj The object or function to delete a key from. |
| 137 |
* @param {string} key The key to delete. |
| 138 |
* @throws {Error} In case of trying to set a read-only property |
| 139 |
* @private |
| 140 |
*/ |
| 141 |
goog.testing.PropertyReplacer.deleteKey_ = function(obj, key) { |
| 142 |
try { |
| 143 |
delete obj[key]; |
| 144 |
// Delete has no effect for built-in properties of DOM nodes in FF. |
| 145 |
if (!goog.testing.PropertyReplacer.hasKey_(obj, key)) { |
| 146 |
return; |
| 147 |
} |
| 148 |
} catch (e) { |
| 149 |
// IE throws TypeError when trying to delete properties of native objects |
| 150 |
// (e.g. DOM nodes or window), even if they have been added by JavaScript. |
| 151 |
} |
| 152 |
|
| 153 |
obj[key] = undefined; |
| 154 |
if (obj[key] == 'undefined') { |
| 155 |
// Some properties such as className in IE are always evaluated as string |
| 156 |
// so undefined will become 'undefined'. |
| 157 |
obj[key] = ''; |
| 158 |
} |
| 159 |
|
| 160 |
if (obj[key]) { |
| 161 |
throw new Error( |
| 162 |
'Cannot delete non configurable property "' + key + '" in ' + obj); |
| 163 |
} |
| 164 |
}; |
| 165 |
|
| 166 |
|
| 167 |
/** |
| 168 |
* Restore the original state of a key in an object. |
| 169 |
* @param {{ object: ?, key: string, value: ? }} original Original state |
| 170 |
* @private |
| 171 |
*/ |
| 172 |
goog.testing.PropertyReplacer.restoreOriginal_ = function(original) { |
| 173 |
if (original.value == goog.testing.PropertyReplacer.NO_SUCH_KEY_) { |
| 174 |
goog.testing.PropertyReplacer.deleteKey_(original.object, original.key); |
| 175 |
} else { |
| 176 |
original.object[original.key] = original.value; |
| 177 |
} |
| 178 |
}; |
| 179 |
|
| 180 |
|
| 181 |
/** |
| 182 |
* Adds or changes a value in an object while saving its original state. |
| 183 |
* @param {Object|Function} obj The JavaScript or native object or function to |
| 184 |
* alter. See the constraints in the class description. |
| 185 |
* @param {string} key The key to change the value for. |
| 186 |
* @param {*} value The new value to set. |
| 187 |
* @throws {Error} In case of trying to set a read-only property. |
| 188 |
*/ |
| 189 |
goog.testing.PropertyReplacer.prototype.set = function(obj, key, value) { |
| 190 |
var origValue = goog.testing.PropertyReplacer.hasKey_(obj, key) ? |
| 191 |
obj[key] : |
| 192 |
goog.testing.PropertyReplacer.NO_SUCH_KEY_; |
| 193 |
this.original_.push({object: obj, key: key, value: origValue}); |
| 194 |
obj[key] = value; |
| 195 |
|
| 196 |
// Check whether obj[key] was a read-only value and the assignment failed. |
| 197 |
// Also, check that we're not comparing returned pixel values when "value" |
| 198 |
// is 0. In other words, account for this case: |
| 199 |
// document.body.style.margin = 0; |
| 200 |
// document.body.style.margin; // returns "0px" |
| 201 |
if (obj[key] != value && (value + 'px') != obj[key]) { |
| 202 |
throw new Error( |
| 203 |
'Cannot overwrite read-only property "' + key + '" in ' + obj); |
| 204 |
} |
| 205 |
}; |
| 206 |
|
| 207 |
|
| 208 |
/** |
| 209 |
* Changes an existing value in an object to another one of the same type while |
| 210 |
* saving its original state. The advantage of {@code replace} over {@link #set} |
| 211 |
* is that {@code replace} protects against typos and erroneously passing tests |
| 212 |
* after some members have been renamed during a refactoring. |
| 213 |
* @param {Object|Function} obj The JavaScript or native object or function to |
| 214 |
* alter. See the constraints in the class description. |
| 215 |
* @param {string} key The key to change the value for. It has to be present |
| 216 |
* either in {@code obj} or in its prototype chain. |
| 217 |
* @param {*} value The new value to set. |
| 218 |
* @param {boolean=} opt_allowNullOrUndefined By default, this method requires |
| 219 |
* {@code value} to match the type of the existing value, as determined by |
| 220 |
* {@link goog.typeOf}. Setting opt_allowNullOrUndefined to {@code true} |
| 221 |
* allows an existing value to be replaced by {@code null} or |
| 222 |
{@code undefined}, or vice versa. |
| 223 |
* @throws {Error} In case of missing key or type mismatch. |
| 224 |
*/ |
| 225 |
goog.testing.PropertyReplacer.prototype.replace = function( |
| 226 |
obj, key, value, opt_allowNullOrUndefined) { |
| 227 |
if (!(key in obj)) { |
| 228 |
throw new Error('Cannot replace missing property "' + key + '" in ' + obj); |
| 229 |
} |
| 230 |
// If opt_allowNullOrUndefined is true, then we do not check the types if |
| 231 |
// either the original or new value is null or undefined. |
| 232 |
var shouldCheckTypes = !opt_allowNullOrUndefined || |
| 233 |
(goog.isDefAndNotNull(obj[key]) && goog.isDefAndNotNull(value)); |
| 234 |
if (shouldCheckTypes) { |
| 235 |
var originalType = goog.typeOf(obj[key]); |
| 236 |
var newType = goog.typeOf(value); |
| 237 |
if (originalType != newType) { |
| 238 |
throw new Error( |
| 239 |
'Cannot replace property "' + key + '" in ' + obj + |
| 240 |
' with a value of different type (expected ' + originalType + |
| 241 |
', found ' + newType + ')'); |
| 242 |
} |
| 243 |
} |
| 244 |
this.set(obj, key, value); |
| 245 |
}; |
| 246 |
|
| 247 |
|
| 248 |
/** |
| 249 |
* Builds an object structure for the provided namespace path. Doesn't |
| 250 |
* overwrite those prefixes of the path that are already objects or functions. |
| 251 |
* @param {string} path The path to create or alter, e.g. 'goog.ui.Menu'. |
| 252 |
* @param {*} value The value to set. |
| 253 |
*/ |
| 254 |
goog.testing.PropertyReplacer.prototype.setPath = function(path, value) { |
| 255 |
var parts = path.split('.'); |
| 256 |
var obj = goog.global; |
| 257 |
for (var i = 0; i < parts.length - 1; i++) { |
| 258 |
var part = parts[i]; |
| 259 |
if (part == 'prototype' && !obj[part]) { |
| 260 |
throw new Error( |
| 261 |
'Cannot set the prototype of ' + parts.slice(0, i).join('.')); |
| 262 |
} |
| 263 |
if (!goog.isObject(obj[part]) && !goog.isFunction(obj[part])) { |
| 264 |
this.set(obj, part, {}); |
| 265 |
} |
| 266 |
obj = obj[part]; |
| 267 |
} |
| 268 |
this.set(obj, parts[parts.length - 1], value); |
| 269 |
}; |
| 270 |
|
| 271 |
|
| 272 |
/** |
| 273 |
* Deletes the key from the object while saving its original value. |
| 274 |
* @param {Object|Function} obj The JavaScript or native object or function to |
| 275 |
* alter. See the constraints in the class description. |
| 276 |
* @param {string} key The key to delete. |
| 277 |
*/ |
| 278 |
goog.testing.PropertyReplacer.prototype.remove = function(obj, key) { |
| 279 |
if (goog.testing.PropertyReplacer.hasKey_(obj, key)) { |
| 280 |
this.original_.push({object: obj, key: key, value: obj[key]}); |
| 281 |
goog.testing.PropertyReplacer.deleteKey_(obj, key); |
| 282 |
} |
| 283 |
}; |
| 284 |
|
| 285 |
|
| 286 |
/** |
| 287 |
* Restore the original state of key in an object. |
| 288 |
* @param {!Object|!Function} obj The JavaScript or native object whose state |
| 289 |
* should be restored. |
| 290 |
* @param {string} key The key to restore the original value for. |
| 291 |
* @throws {Error} In case the object/key pair hadn't been modified earlier. |
| 292 |
*/ |
| 293 |
goog.testing.PropertyReplacer.prototype.restore = function(obj, key) { |
| 294 |
for (var i = this.original_.length - 1; i >= 0; i--) { |
| 295 |
var original = this.original_[i]; |
| 296 |
if (original.object === obj && original.key == key) { |
| 297 |
goog.testing.PropertyReplacer.restoreOriginal_(original); |
| 298 |
this.original_.splice(i, 1); |
| 299 |
return; |
| 300 |
} |
| 301 |
} |
| 302 |
throw new Error('Cannot restore unmodified property "' + key + '" of ' + obj); |
| 303 |
}; |
| 304 |
|
| 305 |
|
| 306 |
/** |
| 307 |
* Resets all changes made by goog.testing.PropertyReplacer.prototype.set. |
| 308 |
*/ |
| 309 |
goog.testing.PropertyReplacer.prototype.reset = function() { |
| 310 |
for (var i = this.original_.length - 1; i >= 0; i--) { |
| 311 |
goog.testing.PropertyReplacer.restoreOriginal_(this.original_[i]); |
| 312 |
delete this.original_[i]; |
| 313 |
} |
| 314 |
this.original_.length = 0; |
| 315 |
}; |