summaryrefslogtreecommitdiffstats
path: root/testing/modules/tests/xpcshell/test_assert.js
blob: 42b46f08f8f0fd00743ba0545bfde21798447052 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

// Test cases borrowed and adapted from:
// https://github.com/joyent/node/blob/6101eb184db77d0b11eb96e48744e57ecce4b73d/test/simple/test-assert.js
// MIT license: http://opensource.org/licenses/MIT

var { Assert } = ChromeUtils.importESModule(
  "resource://testing-common/Assert.sys.mjs"
);

add_task(function test_basic_asserts() {
  let assert = new Assert();

  function makeBlock(f, ...args) {
    return function () {
      return f.apply(assert, args);
    };
  }

  function protoCtrChain(o) {
    let result = [];
    while ((o = o.__proto__)) {
      result.push(o.constructor);
    }
    return result.join();
  }

  function indirectInstanceOf(obj, cls) {
    if (obj instanceof cls) {
      return true;
    }
    let clsChain = protoCtrChain(cls.prototype);
    let objChain = protoCtrChain(obj);
    return objChain.slice(-clsChain.length) === clsChain;
  }

  assert.ok(
    indirectInstanceOf(Assert.AssertionError.prototype, Error),
    "Assert.AssertionError instanceof Error"
  );

  assert.throws(
    makeBlock(assert.ok, false),
    Assert.AssertionError,
    "ok(false)"
  );

  assert.ok(true, "ok(true)");

  assert.ok("test", "ok('test')");

  assert.throws(
    makeBlock(assert.equal, true, false),
    Assert.AssertionError,
    "equal"
  );

  assert.equal(null, null, "equal");

  assert.equal(undefined, undefined, "equal");

  assert.equal(null, undefined, "equal");

  assert.equal(true, true, "equal");

  assert.notEqual(true, false, "notEqual");

  assert.throws(
    makeBlock(assert.notEqual, true, true),
    Assert.AssertionError,
    "notEqual"
  );

  assert.throws(
    makeBlock(assert.strictEqual, 2, "2"),
    Assert.AssertionError,
    "strictEqual"
  );

  assert.throws(
    makeBlock(assert.strictEqual, null, undefined),
    Assert.AssertionError,
    "strictEqual"
  );

  assert.notStrictEqual(2, "2", "notStrictEqual");

  // deepEquals joy!
  // 7.2
  assert.deepEqual(
    new Date(2000, 3, 14),
    new Date(2000, 3, 14),
    "deepEqual date"
  );
  assert.deepEqual(new Date(NaN), new Date(NaN), "deepEqual invalid dates");

  assert.throws(
    makeBlock(assert.deepEqual, new Date(), new Date(2000, 3, 14)),
    Assert.AssertionError,
    "deepEqual date"
  );

  // 7.3
  assert.deepEqual(/a/, /a/);
  assert.deepEqual(/a/g, /a/g);
  assert.deepEqual(/a/i, /a/i);
  assert.deepEqual(/a/m, /a/m);
  assert.deepEqual(/a/gim, /a/gim);
  assert.throws(makeBlock(assert.deepEqual, /ab/, /a/), Assert.AssertionError);
  assert.throws(makeBlock(assert.deepEqual, /a/g, /a/), Assert.AssertionError);
  assert.throws(makeBlock(assert.deepEqual, /a/i, /a/), Assert.AssertionError);
  assert.throws(makeBlock(assert.deepEqual, /a/m, /a/), Assert.AssertionError);
  assert.throws(
    makeBlock(assert.deepEqual, /a/gim, /a/im),
    Assert.AssertionError
  );

  let re1 = /a/;
  re1.lastIndex = 3;
  assert.throws(makeBlock(assert.deepEqual, re1, /a/), Assert.AssertionError);

  // 7.4
  assert.deepEqual(4, "4", "deepEqual == check");
  assert.deepEqual(true, 1, "deepEqual == check");
  assert.throws(
    makeBlock(assert.deepEqual, 4, "5"),
    Assert.AssertionError,
    "deepEqual == check"
  );

  // 7.5
  // having the same number of owned properties && the same set of keys
  assert.deepEqual({ a: 4 }, { a: 4 });
  assert.deepEqual({ a: 4, b: "2" }, { a: 4, b: "2" });
  assert.deepEqual([4], ["4"]);
  assert.throws(
    makeBlock(assert.deepEqual, { a: 4 }, { a: 4, b: true }),
    Assert.AssertionError
  );
  assert.deepEqual(["a"], { 0: "a" });

  let a1 = [1, 2, 3];
  let a2 = [1, 2, 3];
  a1.a = "test";
  a1.b = true;
  a2.b = true;
  a2.a = "test";
  assert.throws(
    makeBlock(assert.deepEqual, Object.keys(a1), Object.keys(a2)),
    Assert.AssertionError
  );
  assert.deepEqual(a1, a2);

  let nbRoot = {
    toString() {
      return this.first + " " + this.last;
    },
  };

  function nameBuilder(first, last) {
    this.first = first;
    this.last = last;
    return this;
  }
  nameBuilder.prototype = nbRoot;

  function nameBuilder2(first, last) {
    this.first = first;
    this.last = last;
    return this;
  }
  nameBuilder2.prototype = nbRoot;

  let nb1 = new nameBuilder("Ryan", "Dahl");
  let nb2 = new nameBuilder2("Ryan", "Dahl");

  assert.deepEqual(nb1, nb2);

  nameBuilder2.prototype = Object;
  nb2 = new nameBuilder2("Ryan", "Dahl");
  assert.throws(makeBlock(assert.deepEqual, nb1, nb2), Assert.AssertionError);

  // String literal + object
  assert.throws(makeBlock(assert.deepEqual, "a", {}), Assert.AssertionError);

  // Testing the throwing
  function thrower(errorConstructor) {
    throw new errorConstructor("test");
  }
  makeBlock(thrower, Assert.AssertionError);
  makeBlock(thrower, Assert.AssertionError);

  // the basic calls work
  assert.throws(
    makeBlock(thrower, Assert.AssertionError),
    Assert.AssertionError,
    "message"
  );
  assert.throws(
    makeBlock(thrower, Assert.AssertionError),
    Assert.AssertionError
  );
  assert.throws(
    makeBlock(thrower, Assert.AssertionError),
    Assert.AssertionError
  );

  // if not passing an error, catch all.
  assert.throws(makeBlock(thrower, TypeError), TypeError);

  // when passing a type, only catch errors of the appropriate type
  let threw = false;
  try {
    assert.throws(makeBlock(thrower, TypeError), Assert.AssertionError);
  } catch (e) {
    threw = true;
    assert.ok(e instanceof TypeError, "type");
  }
  assert.equal(
    true,
    threw,
    "Assert.throws with an explicit error is eating extra errors",
    Assert.AssertionError
  );
  threw = false;

  function ifError(err) {
    if (err) {
      throw err;
    }
  }
  assert.throws(function () {
    ifError(new Error("test error"));
  }, /test error/);

  // make sure that validating using constructor really works
  threw = false;
  try {
    assert.throws(function () {
      throw new Error({});
    }, Array);
  } catch (e) {
    threw = true;
  }
  assert.ok(threw, "wrong constructor validation");

  // use a RegExp to validate error message
  assert.throws(makeBlock(thrower, TypeError), /test/);

  // use a fn to validate error object
  assert.throws(makeBlock(thrower, TypeError), function (err) {
    if (err instanceof TypeError && /test/.test(err)) {
      return true;
    }
    return false;
  });
  // do the same with an arrow function
  assert.throws(makeBlock(thrower, TypeError), err => {
    if (err instanceof TypeError && /test/.test(err)) {
      return true;
    }
    return false;
  });

  function testAssertionMessage(actual, expected) {
    try {
      assert.equal(actual, "");
    } catch (e) {
      assert.equal(
        e.toString(),
        ["AssertionError:", expected, "==", '""'].join(" ")
      );
    }
  }
  testAssertionMessage(undefined, '"undefined"');
  testAssertionMessage(null, "null");
  testAssertionMessage(true, "true");
  testAssertionMessage(false, "false");
  testAssertionMessage(0, "0");
  testAssertionMessage(100, "100");
  testAssertionMessage(NaN, '"NaN"');
  testAssertionMessage(Infinity, '"Infinity"');
  testAssertionMessage(-Infinity, '"-Infinity"');
  testAssertionMessage("", '""');
  testAssertionMessage("foo", '"foo"');
  testAssertionMessage([], "[]");
  testAssertionMessage([1, 2, 3], "[1,2,3]");
  testAssertionMessage(/a/, '"/a/"');
  testAssertionMessage(/abc/gim, '"/abc/gim"');
  testAssertionMessage(function f() {}, '"function f() {}"');
  testAssertionMessage({}, "{}");
  testAssertionMessage({ a: undefined, b: null }, '{"a":"undefined","b":null}');
  testAssertionMessage(
    { a: NaN, b: Infinity, c: -Infinity },
    '{"a":"NaN","b":"Infinity","c":"-Infinity"}'
  );

  // https://github.com/joyent/node/issues/2893
  try {
    assert.throws(function () {
      ifError(null);
    });
  } catch (e) {
    threw = true;
    assert.equal(
      e.message,
      "Error: The 'expected' argument was not supplied to Assert.throws() - false == true"
    );
  }
  assert.ok(threw);

  // https://github.com/joyent/node/issues/5292
  try {
    assert.equal(1, 2);
  } catch (e) {
    assert.equal(e.toString().split("\n")[0], "AssertionError: 1 == 2");
  }

  try {
    assert.equal(1, 2, "oh no");
  } catch (e) {
    assert.equal(e.toString().split("\n")[0], "AssertionError: oh no - 1 == 2");
  }

  // Need to JSON.stringify so that their length is > 128 characters.
  let longArray0 = Array.from(Array(50), (v, i) => i);
  let longArray1 = longArray0.concat([51]);
  try {
    assert.deepEqual(longArray0, longArray1);
  } catch (e) {
    let message = e.toString();
    // Just check that they're both entirely present in the message
    assert.ok(message.includes(JSON.stringify(longArray0)));
    assert.ok(message.includes(JSON.stringify(longArray1)));
  }

  // Test XPCShell-test integration:
  ok(true, "OK, this went well");
  deepEqual(/a/g, /a/g, "deep equal should work on RegExp");
  deepEqual(/a/gim, /a/gim, "deep equal should work on RegExp");
  deepEqual(
    { a: 4, b: "1" },
    { b: "1", a: 4 },
    "deep equal should work on regular Object"
  );
  deepEqual(a1, a2, "deep equal should work on Array with Object properties");

  // Test robustness of reporting:
  equal(
    new Assert.AssertionError({
      actual: {
        toJSON() {
          throw new Error("bam!");
        },
      },
      expected: "foo",
      operator: "=",
    }).message,
    '[object Object] = "foo"'
  );

  let message;
  assert.greater(3, 2);
  try {
    assert.greater(2, 2);
  } catch (e) {
    message = e.toString().split("\n")[0];
  }
  assert.equal(message, "AssertionError: 2 > 2");

  assert.greaterOrEqual(2, 2);
  try {
    assert.greaterOrEqual(1, 2);
  } catch (e) {
    message = e.toString().split("\n")[0];
  }
  assert.equal(message, "AssertionError: 1 >= 2");

  assert.less(1, 2);
  assert.throws(
    () => assert.less(2, 2),
    e => e == "AssertionError: 2 < 2"
  );

  assert.lessOrEqual(2, 2);
  assert.throws(
    () => assert.lessOrEqual(2, 1),
    e => e == "AssertionError: 2 <= 1"
  );

  assert.throws(
    () => assert.greater(NaN, 0),
    e => e == "AssertionError: 'NaN' is not a number or date."
  );

  assert.throws(
    () => assert.greater(0, NaN),
    e => e == "AssertionError: 'NaN' is not a number or date."
  );

  let now = new Date();
  let firefoxReleaseDate = new Date("2004-11-09");
  assert.less(firefoxReleaseDate, now);
  assert.throws(
    () => assert.less(now, now),
    e => e == `AssertionError: "${now.toJSON()}" < "${now.toJSON()}"`
  );

  assert.lessOrEqual(now, now);
  assert.greaterOrEqual(now, now);
  assert.throws(
    () => assert.greaterOrEqual(firefoxReleaseDate, now),
    e =>
      e ==
      `AssertionError: "${firefoxReleaseDate.toJSON()}" >= "${now.toJSON()}"`
  );

  // Invalid date:
  assert.throws(
    () => assert.greater(firefoxReleaseDate, new Date("invalid")),
    e => e == "AssertionError: 'Invalid Date' is not a number or date."
  );

  /* ---- stringMatches ---- */
  assert.stringMatches("hello world", /llo\s/);
  assert.stringMatches("hello world", "llo\\s");
  assert.throws(
    () => assert.stringMatches("hello world", /foo/),
    /^AssertionError: "hello world" matches "\/foo\/"/
  );
  assert.throws(
    () => assert.stringMatches(5, /foo/),
    /^AssertionError: Expected a string for lhs, but "5" isn't a string./
  );
  assert.throws(
    () => assert.stringMatches("foo bar", "+"),
    /^AssertionError: Expected a valid regular expression for rhs, but "\+" isn't one./
  );

  /* ---- stringContains ---- */
  assert.stringContains("hello world", "llo");
  assert.throws(
    () => assert.stringContains(5, "foo"),
    /^AssertionError: Expected a string for both lhs and rhs, but either "5" or "foo" is not a string./
  );
});

add_task(async function test_rejects() {
  let assert = new Assert();

  // A helper function to test failures.
  async function checkRejectsFails(err, expected) {
    try {
      await assert.rejects(Promise.reject(err), expected);
      ok(false, "should have thrown");
    } catch (ex) {
      deepEqual(ex, err, "Assert.rejects threw the original unexpected error");
    }
  }

  // A "throwable" error that's not an actual Error().
  let SomeErrorLikeThing = function () {};

  // The actual tests...

  // An explicit error object:
  // An instance to check against.
  await assert.rejects(Promise.reject(new Error("oh no")), Error, "rejected");
  // A regex to match against the message.
  await assert.rejects(Promise.reject(new Error("oh no")), /oh no/, "rejected");

  // Failure cases:
  // An instance to check against that doesn't match.
  await checkRejectsFails(new Error("something else"), SomeErrorLikeThing);
  // A regex that doesn't match.
  await checkRejectsFails(new Error("something else"), /oh no/);

  // Check simple string messages.
  await assert.rejects(Promise.reject("oh no"), /oh no/, "rejected");
  // Wrong message.
  await checkRejectsFails("something else", /oh no/);

  // A non-rejection should also be an assertion failure:
  try {
    await assert.rejects(Promise.resolve(), /./, "ReSoLvEd");
    ok(false, "should have rejected");
  } catch (ex) {
    deepEqual(ex.message, "Missing expected exception ReSoLvEd");
  }
});