propertyreplacer.js 11 KB

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