1 // Copyright 2008 The Closure Library Authors. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
16 * @fileoverview Utilities to check the preconditions, postconditions and
19 * Methods in this package should be given special treatment by the compiler
20 * for type-inference. For example, <code>goog.asserts.assert(foo)</code>
21 * will restrict <code>foo</code> to a truthy value.
23 * The compiler has an option to disable asserts. So code like:
25 * var x = goog.asserts.assert(foo()); goog.asserts.assert(bar());
27 * will be transformed into:
31 * The compiler will leave in foo() (because its return value is used),
32 * but it will remove bar() because it assumes it does not have side-effects.
36 goog.provide('goog.asserts');
37 goog.provide('goog.asserts.AssertionError');
39 goog.require('goog.debug.Error');
40 goog.require('goog.dom.NodeType');
41 goog.require('goog.string');
45 * @define {boolean} Whether to strip out asserts or to leave them in.
47 goog.define('goog.asserts.ENABLE_ASSERTS', goog.DEBUG);
52 * Error object for failed assertions.
53 * @param {string} messagePattern The pattern that was used to form message.
54 * @param {!Array.<*>} messageArgs The items to substitute into the pattern.
56 * @extends {goog.debug.Error}
59 goog.asserts.AssertionError = function(messagePattern, messageArgs) {
60 messageArgs.unshift(messagePattern);
61 goog.debug.Error.call(this, goog.string.subs.apply(null, messageArgs));
62 // Remove the messagePattern afterwards to avoid permenantly modifying the
67 * The message pattern used to format the error message. Error handlers can
68 * use this to uniquely identify the assertion.
71 this.messagePattern = messagePattern;
73 goog.inherits(goog.asserts.AssertionError, goog.debug.Error);
77 goog.asserts.AssertionError.prototype.name = 'AssertionError';
81 * The default error handler.
82 * @param {!goog.asserts.AssertionError} e The exception to be handled.
84 goog.asserts.DEFAULT_ERROR_HANDLER = function(e) { throw e; };
88 * The handler responsible for throwing or logging assertion errors.
89 * @private {function(!goog.asserts.AssertionError)}
91 goog.asserts.errorHandler_ = goog.asserts.DEFAULT_ERROR_HANDLER;
95 * Throws an exception with the given message and "Assertion failed" prefixed
97 * @param {string} defaultMessage The message to use if givenMessage is empty.
98 * @param {Array.<*>} defaultArgs The substitution arguments for defaultMessage.
99 * @param {string|undefined} givenMessage Message supplied by the caller.
100 * @param {Array.<*>} givenArgs The substitution arguments for givenMessage.
101 * @throws {goog.asserts.AssertionError} When the value is not a number.
104 goog.asserts.doAssertFailure_ =
105 function(defaultMessage, defaultArgs, givenMessage, givenArgs) {
106 var message = 'Assertion failed';
108 message += ': ' + givenMessage;
109 var args = givenArgs;
110 } else if (defaultMessage) {
111 message += ': ' + defaultMessage;
114 // The '' + works around an Opera 10 bug in the unit tests. Without it,
115 // a stack trace is added to var message above. With this, a stack trace is
116 // not added until this line (it causes the extra garbage to be added after
117 // the assertion message instead of in the middle of it).
118 var e = new goog.asserts.AssertionError('' + message, args || []);
119 goog.asserts.errorHandler_(e);
124 * Sets a custom error handler that can be used to customize the behavior of
125 * assertion failures, for example by turning all assertion failures into log
127 * @param {function(goog.asserts.AssertionError)} errorHandler
129 goog.asserts.setErrorHandler = function(errorHandler) {
130 if (goog.asserts.ENABLE_ASSERTS) {
131 goog.asserts.errorHandler_ = errorHandler;
137 * Checks if the condition evaluates to true if goog.asserts.ENABLE_ASSERTS is
140 * @param {T} condition The condition to check.
141 * @param {string=} opt_message Error message in case of failure.
142 * @param {...*} var_args The items to substitute into the failure message.
143 * @return {T} The value of the condition.
144 * @throws {goog.asserts.AssertionError} When the condition evaluates to false.
146 goog.asserts.assert = function(condition, opt_message, var_args) {
147 if (goog.asserts.ENABLE_ASSERTS && !condition) {
148 goog.asserts.doAssertFailure_('', null, opt_message,
149 Array.prototype.slice.call(arguments, 2));
156 * Fails if goog.asserts.ENABLE_ASSERTS is true. This function is useful in case
157 * when we want to add a check in the unreachable area like switch-case
162 * case FOO: doSomething(); break;
163 * case BAR: doSomethingElse(); break;
164 * default: goog.assert.fail('Unrecognized type: ' + type);
165 * // We have only 2 types - "default:" section is unreachable code.
169 * @param {string=} opt_message Error message in case of failure.
170 * @param {...*} var_args The items to substitute into the failure message.
171 * @throws {goog.asserts.AssertionError} Failure.
173 goog.asserts.fail = function(opt_message, var_args) {
174 if (goog.asserts.ENABLE_ASSERTS) {
175 goog.asserts.errorHandler_(new goog.asserts.AssertionError(
176 'Failure' + (opt_message ? ': ' + opt_message : ''),
177 Array.prototype.slice.call(arguments, 1)));
183 * Checks if the value is a number if goog.asserts.ENABLE_ASSERTS is true.
184 * @param {*} value The value to check.
185 * @param {string=} opt_message Error message in case of failure.
186 * @param {...*} var_args The items to substitute into the failure message.
187 * @return {number} The value, guaranteed to be a number when asserts enabled.
188 * @throws {goog.asserts.AssertionError} When the value is not a number.
190 goog.asserts.assertNumber = function(value, opt_message, var_args) {
191 if (goog.asserts.ENABLE_ASSERTS && !goog.isNumber(value)) {
192 goog.asserts.doAssertFailure_('Expected number but got %s: %s.',
193 [goog.typeOf(value), value], opt_message,
194 Array.prototype.slice.call(arguments, 2));
196 return /** @type {number} */ (value);
201 * Checks if the value is a string if goog.asserts.ENABLE_ASSERTS is true.
202 * @param {*} value The value to check.
203 * @param {string=} opt_message Error message in case of failure.
204 * @param {...*} var_args The items to substitute into the failure message.
205 * @return {string} The value, guaranteed to be a string when asserts enabled.
206 * @throws {goog.asserts.AssertionError} When the value is not a string.
208 goog.asserts.assertString = function(value, opt_message, var_args) {
209 if (goog.asserts.ENABLE_ASSERTS && !goog.isString(value)) {
210 goog.asserts.doAssertFailure_('Expected string but got %s: %s.',
211 [goog.typeOf(value), value], opt_message,
212 Array.prototype.slice.call(arguments, 2));
214 return /** @type {string} */ (value);
219 * Checks if the value is a function if goog.asserts.ENABLE_ASSERTS is true.
220 * @param {*} value The value to check.
221 * @param {string=} opt_message Error message in case of failure.
222 * @param {...*} var_args The items to substitute into the failure message.
223 * @return {!Function} The value, guaranteed to be a function when asserts
225 * @throws {goog.asserts.AssertionError} When the value is not a function.
227 goog.asserts.assertFunction = function(value, opt_message, var_args) {
228 if (goog.asserts.ENABLE_ASSERTS && !goog.isFunction(value)) {
229 goog.asserts.doAssertFailure_('Expected function but got %s: %s.',
230 [goog.typeOf(value), value], opt_message,
231 Array.prototype.slice.call(arguments, 2));
233 return /** @type {!Function} */ (value);
238 * Checks if the value is an Object if goog.asserts.ENABLE_ASSERTS is true.
239 * @param {*} value The value to check.
240 * @param {string=} opt_message Error message in case of failure.
241 * @param {...*} var_args The items to substitute into the failure message.
242 * @return {!Object} The value, guaranteed to be a non-null object.
243 * @throws {goog.asserts.AssertionError} When the value is not an object.
245 goog.asserts.assertObject = function(value, opt_message, var_args) {
246 if (goog.asserts.ENABLE_ASSERTS && !goog.isObject(value)) {
247 goog.asserts.doAssertFailure_('Expected object but got %s: %s.',
248 [goog.typeOf(value), value],
249 opt_message, Array.prototype.slice.call(arguments, 2));
251 return /** @type {!Object} */ (value);
256 * Checks if the value is an Array if goog.asserts.ENABLE_ASSERTS is true.
257 * @param {*} value The value to check.
258 * @param {string=} opt_message Error message in case of failure.
259 * @param {...*} var_args The items to substitute into the failure message.
260 * @return {!Array} The value, guaranteed to be a non-null array.
261 * @throws {goog.asserts.AssertionError} When the value is not an array.
263 goog.asserts.assertArray = function(value, opt_message, var_args) {
264 if (goog.asserts.ENABLE_ASSERTS && !goog.isArray(value)) {
265 goog.asserts.doAssertFailure_('Expected array but got %s: %s.',
266 [goog.typeOf(value), value], opt_message,
267 Array.prototype.slice.call(arguments, 2));
269 return /** @type {!Array} */ (value);
274 * Checks if the value is a boolean if goog.asserts.ENABLE_ASSERTS is true.
275 * @param {*} value The value to check.
276 * @param {string=} opt_message Error message in case of failure.
277 * @param {...*} var_args The items to substitute into the failure message.
278 * @return {boolean} The value, guaranteed to be a boolean when asserts are
280 * @throws {goog.asserts.AssertionError} When the value is not a boolean.
282 goog.asserts.assertBoolean = function(value, opt_message, var_args) {
283 if (goog.asserts.ENABLE_ASSERTS && !goog.isBoolean(value)) {
284 goog.asserts.doAssertFailure_('Expected boolean but got %s: %s.',
285 [goog.typeOf(value), value], opt_message,
286 Array.prototype.slice.call(arguments, 2));
288 return /** @type {boolean} */ (value);
293 * Checks if the value is a DOM Element if goog.asserts.ENABLE_ASSERTS is true.
294 * @param {*} value The value to check.
295 * @param {string=} opt_message Error message in case of failure.
296 * @param {...*} var_args The items to substitute into the failure message.
297 * @return {!Element} The value, likely to be a DOM Element when asserts are
299 * @throws {goog.asserts.AssertionError} When the value is not a boolean.
301 goog.asserts.assertElement = function(value, opt_message, var_args) {
302 if (goog.asserts.ENABLE_ASSERTS && (!goog.isObject(value) ||
303 value.nodeType != goog.dom.NodeType.ELEMENT)) {
304 goog.asserts.doAssertFailure_('Expected Element but got %s: %s.',
305 [goog.typeOf(value), value], opt_message,
306 Array.prototype.slice.call(arguments, 2));
308 return /** @type {!Element} */ (value);
313 * Checks if the value is an instance of the user-defined type if
314 * goog.asserts.ENABLE_ASSERTS is true.
316 * The compiler may tighten the type returned by this function.
318 * @param {*} value The value to check.
319 * @param {function(new: T, ...)} type A user-defined constructor.
320 * @param {string=} opt_message Error message in case of failure.
321 * @param {...*} var_args The items to substitute into the failure message.
322 * @throws {goog.asserts.AssertionError} When the value is not an instance of
327 goog.asserts.assertInstanceof = function(value, type, opt_message, var_args) {
328 if (goog.asserts.ENABLE_ASSERTS && !(value instanceof type)) {
329 goog.asserts.doAssertFailure_('instanceof check failed.', null,
330 opt_message, Array.prototype.slice.call(arguments, 3));
337 * Checks that no enumerable keys are present in Object.prototype. Such keys
338 * would break most code that use {@code for (var ... in ...)} loops.
340 goog.asserts.assertObjectPrototypeIsIntact = function() {
341 for (var key in Object.prototype) {
342 goog.asserts.fail(key + ' should not be enumerable in Object.prototype.');