assert_additions.js revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/**
6 * Asserts that a given argument's value is undefined.
7 * @param {object} a The argument to check.
8 */
9function assertUndefined(a) {
10  if (a !== undefined) {
11    throw new Error('Assertion failed: expected undefined');
12  }
13}
14
15/**
16 * Asserts that the argument is neither null nor undefined.
17 * @param {object} obj The argument to check.
18 * @param {string=} opt_message Error message if the condition is not met.
19 */
20function assertNotNullNorUndefined(obj, opt_message) {
21  if (obj === undefined || obj === null) {
22    throw new Error('Can\'t be null or undefined: ' + (opt_message || '') +
23        '\n' + 'Actual: ' + a);
24  }
25}
26
27/**
28 * Asserts that a given function call throws an exception.
29 * @param {string} msg Message to print if exception not thrown.
30 * @param {Function} fn The function to call.
31 * @param {string} error The name of the exception we expect {@code fn} to
32 *     throw.
33 */
34function assertException(msg, fn, error) {
35  try {
36    fn();
37  } catch (e) {
38    if (error && e.name != error) {
39      throw new Error('Expected to throw ' + error + ' but threw ' + e.name +
40          ' - ' + msg);
41    }
42    return;
43  }
44
45  throw new Error('Expected to throw exception ' + error + ' - ' + msg);
46}
47
48/**
49 * Asserts that two arrays of strings are equal.
50 * @param {Array.<string>} array1 The expected array.
51 * @param {Array.<string>} array2 The test array.
52 */
53function assertEqualStringArrays(array1, array2) {
54  var same = true;
55  if (array1.length != array2.length) {
56    same = false;
57  }
58  for (var i = 0; i < Math.min(array1.length, array2.length); i++) {
59    if (array1[i].trim() != array2[i].trim()) {
60      same = false;
61    }
62  }
63  if (!same) {
64    throw new Error('Expected ' + JSON.stringify(array1) +
65                    ', got ' + JSON.stringify(array2));
66  }
67}
68
69/**
70 * Asserts that two objects have the same JSON serialization.
71 * @param {Object} expected The expected object.
72 * @param {Object} actual The actual object.
73 * @param {string=} opt_message Message used for errors.
74 */
75function assertEqualsJSON(expected, actual, opt_message) {
76  if (JSON.stringify(actual) !== JSON.stringify(expected)) {
77    throw new Error((opt_message ? opt_message + '\n' : '') +
78        'Expected ' + JSON.stringify(expected) + '\n' +
79        'Got      ' + JSON.stringify(actual));
80  }
81}
82
83assertSame = assertEquals;
84assertNotSame = assertNotEquals;
85