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