# 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 at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// 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 and13// limitations under the License.1415/**16 * @fileoverview Helper class for creating stubs for testing.17 *18 */1920goog.provide('goog.testing.PropertyReplacer');2122/** @suppress {extraRequire} Needed for some tests to compile. */23goog.require('goog.testing.ObjectPropertyString');24goog.require('goog.userAgent');25262728/**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 test31 * 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.py34 *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 to59 *       the real constructor or kept untouched.60 * </ul>61 *62 * @constructor63 * @final64 */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'. The69   * original value for the given key in the given object is stored under the70   * 'value' key.71   * @type {Array.<Object>}72   * @private73   */74  this.original_ = [];75};767778/**79 * Indicates that a key didn't exist before having been set by the set() method.80 * @type {Object}81 * @private82 */83goog.testing.PropertyReplacer.NO_SUCH_KEY_ = {};848586/**87 * Tells if the given key exists in the object. Ignores inherited fields.88 * @param {Object|Function} obj The JavaScript or native object or function89 *     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 * @private93 */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 false99  // 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 if104  // obj is an instance of a native class. In Opera we have to fall back on105  // 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 or113    // "body" part of document. Although they are defined in the prototype of114    // HTMLElement or Document, accessing them this way throws an exception.115    // <pre>116    //   var dummy = document.body.constructor.prototype.className117    //   [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};125126127/**128 * Deletes a key from an object. Sets it to undefined or empty string if the129 * 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 * @private133 */134goog.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 objects143    // (e.g. DOM nodes or window), even if they have been added by JavaScript.144  }145146  obj[key] = undefined;147  if (obj[key] == 'undefined') {148    // Some properties such as className in IE are always evaluated as string149    // so undefined will become 'undefined'.150    obj[key] = '';151  }152};153154155/**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 to158 *     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 */162goog.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};168169170/**171 * Changes an existing value in an object to another one of the same type while172 * saving its original state. The advantage of {@code replace} over {@link #set}173 * is that {@code replace} protects against typos and erroneously passing tests174 * after some members have been renamed during a refactoring.175 * @param {Object|Function} obj The JavaScript or native object or function to176 *     alter. See the constraints in the class description.177 * @param {string} key The key to change the value for. It has to be present178 *     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 the180 *     original value. The types are compared with {@link goog.typeOf}.181 * @throws {Error} In case of missing key or type mismatch.182 */183goog.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};193194195/**196 * Builds an object structure for the provided namespace path.  Doesn't197 * 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 */201goog.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};216217218/**219 * Deletes the key from the object while saving its original value.220 * @param {Object|Function} obj The JavaScript or native object or function to221 *     alter. See the constraints in the class description.222 * @param {string} key The key to delete.223 */224goog.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};230231232/**233 * Resets all changes made by goog.testing.PropertyReplacer.prototype.set.234 */235goog.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};