Path: blob/trunk/third_party/closure/goog/testing/propertyreplacer.js
4506 views
/**1* @license2* Copyright The Closure Library Authors.3* SPDX-License-Identifier: Apache-2.04*/56/**7* @fileoverview Helper class for creating stubs for testing.8*/910goog.setTestOnly('goog.testing.PropertyReplacer');11goog.provide('goog.testing.PropertyReplacer');1213goog.require('goog.asserts');14151617/**18* Helper class for stubbing out variables and object properties for unit tests.19* This class can change the value of some variables before running the test20* cases, and to reset them in the tearDown phase.21* See googletest.StubOutForTesting as an analogy in Python:22* http://protobuf.googlecode.com/svn/trunk/python/stubout.py23*24* Example usage:25*26* var stubs = new goog.testing.PropertyReplacer();27*28* function setUp() {29* // Mock functions used in all test cases.30* stubs.replace(Math, 'random', function() {31* return 4; // Chosen by fair dice roll. Guaranteed to be random.32* });33* }34*35* function tearDown() {36* stubs.reset();37* }38*39* function testThreeDice() {40* // Mock a constant used only in this test case.41* stubs.set(goog.global, 'DICE_COUNT', 3);42* assertEquals(12, rollAllDice());43* }44*45* Constraints on altered objects:46* <ul>47* <li>DOM subclasses aren't supported.48* <li>The value of the objects' constructor property must either be equal to49* the real constructor or kept untouched.50* </ul>51*52* Code compiled with property renaming may need to use53* `goog.reflect.objectProperty` instead of simply naming the property to54* replace.55*56* @constructor57* @final58*/59goog.testing.PropertyReplacer = function() {60'use strict';61/**62* Stores the values changed by the set() method in chronological order.63* Its items are objects with 3 fields: 'object', 'key', 'value'. The64* original value for the given key in the given object is stored under the65* 'value' key.66* @type {Array<{ object: ?, key: string, value: ? }>}67* @private68*/69this.original_ = [];70};717273/**74* Indicates that a key didn't exist before having been set by the set() method.75* @private @const76*/77goog.testing.PropertyReplacer.NO_SUCH_KEY_ = {};787980/**81* Tells if the given key exists in the object. Ignores inherited fields.82* @param {!Object|!Function} obj The JavaScript or native object or function83* whose key is to be checked.84* @param {string} key The key to check.85* @return {boolean} Whether the object has the key as own key.86* @private87* @suppress {unusedLocalVariables}88*/89goog.testing.PropertyReplacer.hasKey_ = function(obj, key) {90'use strict';91if (!(key in obj)) {92return false;93}94// hasOwnProperty is only reliable with JavaScript objects. It returns false95// for built-in DOM attributes.96if (Object.prototype.hasOwnProperty.call(obj, key)) {97return true;98}99// In all browsers except Opera obj.constructor never equals to Object if100// obj is an instance of a native class. In Opera we have to fall back on101// examining obj.toString().102if (obj.constructor == Object) {103return false;104}105try {106// Firefox hack to consider "className" part of the HTML elements or107// "body" part of document. Although they are defined in the prototype of108// HTMLElement or Document, accessing them this way throws an exception.109// <pre>110// var dummy = document.body.constructor.prototype.className111// [Exception... "Cannot modify properties of a WrappedNative"]112// </pre>113var dummy = obj.constructor.prototype[key];114} catch (e) {115return true;116}117return !(key in obj.constructor.prototype);118};119120121/**122* Deletes a key from an object. Sets it to undefined or empty string if the123* delete failed.124* @param {!Object|!Function} obj The object or function to delete a key from.125* @param {string} key The key to delete.126* @throws {Error} In case of trying to set a read-only property127* @private128*/129goog.testing.PropertyReplacer.deleteKey_ = function(obj, key) {130'use strict';131try {132delete obj[key];133// Delete has no effect for built-in properties of DOM nodes in FF.134if (!goog.testing.PropertyReplacer.hasKey_(obj, key)) {135return;136}137} catch (e) {138// IE throws TypeError when trying to delete properties of native objects139// (e.g. DOM nodes or window), even if they have been added by JavaScript.140}141142obj[key] = undefined;143if (obj[key] == 'undefined') {144// Some properties such as className in IE are always evaluated as string145// so undefined will become 'undefined'.146obj[key] = '';147}148149if (obj[key]) {150throw new Error(151'Cannot delete non configurable property "' + key + '" in ' + obj);152}153};154155156/**157* Restore the original state of a key in an object.158* @param {{ object: ?, key: string, value: ? }} original Original state159* @private160*/161goog.testing.PropertyReplacer.restoreOriginal_ = function(original) {162'use strict';163if (original.value == goog.testing.PropertyReplacer.NO_SUCH_KEY_) {164goog.testing.PropertyReplacer.deleteKey_(original.object, original.key);165} else {166original.object[original.key] = original.value;167}168};169170171/**172* Adds or changes a value in an object while saving its original state.173* @param {Object|Function} obj The JavaScript or native object or function to174* alter. See the constraints in the class description.175* @param {string} key The key to change the value for.176* @param {*} value The new value to set.177* @throws {Error} In case of trying to set a read-only property.178*/179goog.testing.PropertyReplacer.prototype.set = function(obj, key, value) {180'use strict';181goog.asserts.assert(obj);182var origValue = goog.testing.PropertyReplacer.hasKey_(obj, key) ?183obj[key] :184goog.testing.PropertyReplacer.NO_SUCH_KEY_;185this.original_.push({object: obj, key: key, value: origValue});186obj[key] = value;187188// Check whether obj[key] was a read-only value and the assignment failed.189// Also, check that we're not comparing returned pixel values when "value"190// is 0. In other words, account for this case:191// document.body.style.margin = 0;192// document.body.style.margin; // returns "0px"193if (obj[key] != value && (value + 'px') != obj[key]) {194throw new Error(195'Cannot overwrite read-only property "' + key + '" in ' + obj);196}197};198199200/**201* Changes an existing value in an object to another one of the same type while202* saving its original state. The advantage of `replace` over {@link #set}203* is that `replace` protects against typos and erroneously passing tests204* after some members have been renamed during a refactoring.205* @param {Object|Function} obj The JavaScript or native object or function to206* alter. See the constraints in the class description.207* @param {string} key The key to change the value for. It has to be present208* either in `obj` or in its prototype chain.209* @param {*} value The new value to set.210* @param {boolean=} opt_allowNullOrUndefined By default, this method requires211* `value` to match the type of the existing value, as determined by212* {@link goog.typeOf}. Setting opt_allowNullOrUndefined to `true`213* allows an existing value to be replaced by `null` or214`undefined`, or vice versa.215* @throws {Error} In case of missing key or type mismatch.216*/217goog.testing.PropertyReplacer.prototype.replace = function(218obj, key, value, opt_allowNullOrUndefined) {219'use strict';220if (!(key in obj)) {221throw new Error('Cannot replace missing property "' + key + '" in ' + obj);222}223// If opt_allowNullOrUndefined is true, then we do not check the types if224// either the original or new value is null or undefined.225var shouldCheckTypes =226!opt_allowNullOrUndefined || (obj[key] != null && value != null);227if (shouldCheckTypes) {228var originalType = goog.typeOf(obj[key]);229var newType = goog.typeOf(value);230if (originalType != newType) {231throw new Error(232'Cannot replace property "' + key + '" in ' + obj +233' with a value of different type (expected ' + originalType +234', found ' + newType + ')');235}236}237this.set(obj, key, value);238};239240241/**242* Builds an object structure for the provided namespace path. Doesn't243* overwrite those prefixes of the path that are already objects or functions.244* @param {string} path The path to create or alter, e.g. 'goog.ui.Menu'.245* @param {*} value The value to set.246*/247goog.testing.PropertyReplacer.prototype.setPath = function(path, value) {248'use strict';249var parts = path.split('.');250var obj = goog.global;251for (var i = 0; i < parts.length - 1; i++) {252var part = parts[i];253if (part == 'prototype' && !obj[part]) {254throw new Error(255'Cannot set the prototype of ' + parts.slice(0, i).join('.'));256}257if (!goog.isObject(obj[part]) && typeof obj[part] !== 'function') {258this.set(obj, part, {});259}260obj = obj[part];261}262this.set(obj, parts[parts.length - 1], value);263};264265266/**267* Deletes the key from the object while saving its original value.268* @param {Object|Function} obj The JavaScript or native object or function to269* alter. See the constraints in the class description.270* @param {string} key The key to delete.271*/272goog.testing.PropertyReplacer.prototype.remove = function(obj, key) {273'use strict';274if (obj && goog.testing.PropertyReplacer.hasKey_(obj, key)) {275this.original_.push({object: obj, key: key, value: obj[key]});276goog.testing.PropertyReplacer.deleteKey_(obj, key);277}278};279280281/**282* Restore the original state of key in an object.283* @param {!Object|!Function} obj The JavaScript or native object whose state284* should be restored.285* @param {string} key The key to restore the original value for.286* @throws {Error} In case the object/key pair hadn't been modified earlier.287*/288goog.testing.PropertyReplacer.prototype.restore = function(obj, key) {289'use strict';290for (var i = this.original_.length - 1; i >= 0; i--) {291var original = this.original_[i];292if (original.object === obj && original.key == key) {293goog.testing.PropertyReplacer.restoreOriginal_(original);294this.original_.splice(i, 1);295return;296}297}298throw new Error('Cannot restore unmodified property "' + key + '" of ' + obj);299};300301302/**303* Resets all changes made by goog.testing.PropertyReplacer.prototype.set.304*/305goog.testing.PropertyReplacer.prototype.reset = function() {306'use strict';307for (var i = this.original_.length - 1; i >= 0; i--) {308goog.testing.PropertyReplacer.restoreOriginal_(this.original_[i]);309delete this.original_[i];310}311this.original_.length = 0;312};313314315