This repository has been archived by the owner on Aug 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathasserts.js
1907 lines (1730 loc) · 65.1 KB
/
asserts.js
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('goog.testing.asserts');
goog.setTestOnly();
goog.require('goog.dom.safe');
goog.require('goog.html.uncheckedconversions');
goog.require('goog.string');
goog.require('goog.string.Const');
goog.require('goog.testing.JsUnitException');
var DOUBLE_EQUALITY_PREDICATE = function(var1, var2) {
'use strict';
return var1 == var2;
};
var JSUNIT_UNDEFINED_VALUE = void 0;
var TO_STRING_EQUALITY_PREDICATE = function(var1, var2) {
'use strict';
return var1.toString() === var2.toString();
};
var OUTPUT_NEW_LINE_THRESHOLD = 40;
/** @typedef {function(?, ?):boolean} */
var PredicateFunctionType;
/**
* An associative array of constructors corresponding to primitive and
* well-known JS types.
* @const {!Array<string>}
*/
const PRIMITIVE_TRUE_TYPES =
['String', 'Boolean', 'Number', 'Array', 'RegExp', 'Date', 'Function'];
if (typeof ArrayBuffer === 'function') {
PRIMITIVE_TRUE_TYPES.push('ArrayBuffer');
}
/**
* @const {{
* String : !PredicateFunctionType,
* Number : !PredicateFunctionType,
* Boolean : !PredicateFunctionType,
* Date : !PredicateFunctionType,
* RegExp : !PredicateFunctionType,
* Function : !PredicateFunctionType,
* TrustedHTML : !PredicateFunctionType,
* TrustedScript : !PredicateFunctionType,
* TrustedScriptURL : !PredicateFunctionType
* }}
*/
const EQUALITY_PREDICATES = {
'String': DOUBLE_EQUALITY_PREDICATE,
'Number': DOUBLE_EQUALITY_PREDICATE,
'Bigint': DOUBLE_EQUALITY_PREDICATE,
'Boolean': DOUBLE_EQUALITY_PREDICATE,
'Date': function(date1, date2) {
'use strict';
return date1.getTime() == date2.getTime();
},
'RegExp': TO_STRING_EQUALITY_PREDICATE,
'Function': TO_STRING_EQUALITY_PREDICATE,
'TrustedHTML': TO_STRING_EQUALITY_PREDICATE,
'TrustedScript': TO_STRING_EQUALITY_PREDICATE,
'TrustedScriptURL': TO_STRING_EQUALITY_PREDICATE
};
/**
* Compares equality of two numbers, allowing them to differ up to a given
* tolerance.
* @param {number} var1 A number.
* @param {number} var2 A number.
* @param {number} tolerance the maximum allowed difference.
* @return {boolean} Whether the two variables are sufficiently close.
* @private
*/
goog.testing.asserts.numberRoughEqualityPredicate_ = function(
var1, var2, tolerance) {
'use strict';
return Math.abs(var1 - var2) <= tolerance;
};
/**
* @type {!Object<string, function(?, ?, number): boolean>}
* @private
*/
goog.testing.asserts.primitiveRoughEqualityPredicates_ = {
'Number': goog.testing.asserts.numberRoughEqualityPredicate_
};
var _trueTypeOf = function(something) {
'use strict';
let result = typeof something;
try {
switch (result) {
case 'string':
break;
case 'boolean':
break;
case 'number':
break;
case 'object':
if (something == null) {
result = 'null';
break;
}
case 'function':
let foundConstructor = false;
for (let i = 0; i < PRIMITIVE_TRUE_TYPES.length; i++) {
// NOTE: this cannot be a for-of loop because it's used from Rhino
// without the necessary Array.prototype[Symbol.iterator] polyfill.
const trueType = PRIMITIVE_TRUE_TYPES[i];
if (something.constructor === goog.global[trueType]) {
result = trueType;
foundConstructor = true;
break;
}
}
// Constructor doesn't match any of the known "primitive" constructors.
if (!foundConstructor) {
const m =
something.constructor.toString().match(/function\s*([^( ]+)\(/);
if (m) {
result = m[1];
}
}
break;
}
} catch (e) {
} finally {
result = result.slice(0, 1).toUpperCase() + result.slice(1);
}
return result;
};
var _displayStringForValue = function(aVar) {
'use strict';
var result;
try {
result = '<' + String(aVar) + '>';
} catch (ex) {
result = '<toString failed: ' + ex.message + '>';
// toString does not work on this object :-(
}
if (!(aVar === null || aVar === JSUNIT_UNDEFINED_VALUE)) {
result += ' (' + _trueTypeOf(aVar) + ')';
}
return result;
};
/** @param {?} failureMessage */
goog.testing.asserts.fail = function(failureMessage) {
'use strict';
_assert('Call to fail()', false, failureMessage);
};
/**
* @const
* @suppress {duplicate,checkTypes} Test frameworks like Jasmine may also
* define global fail functions.
*/
var fail = goog.testing.asserts.fail;
var argumentsIncludeComments = function(expectedNumberOfNonCommentArgs, args) {
'use strict';
return args.length == expectedNumberOfNonCommentArgs + 1;
};
var commentArg = function(expectedNumberOfNonCommentArgs, args) {
'use strict';
if (argumentsIncludeComments(expectedNumberOfNonCommentArgs, args)) {
return args[0];
}
return null;
};
var nonCommentArg = function(
desiredNonCommentArgIndex, expectedNumberOfNonCommentArgs, args) {
'use strict';
return argumentsIncludeComments(expectedNumberOfNonCommentArgs, args) ?
args[desiredNonCommentArgIndex] :
args[desiredNonCommentArgIndex - 1];
};
var _validateArguments = function(expectedNumberOfNonCommentArgs, args) {
'use strict';
var valid = args.length == expectedNumberOfNonCommentArgs ||
args.length == expectedNumberOfNonCommentArgs + 1 &&
typeof args[0] === 'string';
if (!valid) {
goog.testing.asserts.raiseException(
'Incorrect arguments passed to assert function.\n' +
'Expected ' + expectedNumberOfNonCommentArgs + ' argument(s) plus ' +
'optional comment; got ' + args.length + '.');
}
};
/**
* @return {?} goog.testing.TestCase or null
* We suppress the lint error and we explicitly do not goog.require()
* goog.testing.TestCase to avoid a build time dependency cycle.
* @suppress {missingRequire|undefinedVars|missingProperties}
* @private
*/
var _getCurrentTestCase = function() {
'use strict';
// Some users of goog.testing.asserts do not use goog.testing.TestRunner and
// they do not include goog.testing.TestCase. Exceptions will not be
// completely correct for these users.
if (!goog.testing.TestCase) {
if (goog.global.console) {
goog.global.console.error(
'Missing goog.testing.TestCase, ' +
'add /* @suppress {extraRequire} */' +
'goog.require(\'goog.testing.TestCase\')');
}
return null;
}
return goog.testing.TestCase.getActiveTestCase();
};
var _assert = function(comment, booleanValue, failureMessage) {
'use strict';
// If another framework has installed an adapter, tell it about the assertion.
var adapter =
typeof window !== 'undefined' && window['Closure assert adapter'];
if (adapter) {
adapter['assertWithMessage'](
booleanValue,
goog.testing.JsUnitException.generateMessage(comment, failureMessage));
// Also throw an error, for callers that assume that asserts throw. We don't
// include error details to avoid duplicate failure messages.
if (!booleanValue) throw new Error('goog.testing assertion failed');
}
if (!booleanValue) {
goog.testing.asserts.raiseException(comment, failureMessage);
}
};
/**
* @param {*} expected The expected value.
* @param {*} actual The actual value.
* @return {string} A failure message of the values don't match.
* @private
*/
goog.testing.asserts.getDefaultErrorMsg_ = function(expected, actual) {
'use strict';
var expectedDisplayString = _displayStringForValue(expected);
var actualDisplayString = _displayStringForValue(actual);
var shouldUseNewLines =
expectedDisplayString.length > OUTPUT_NEW_LINE_THRESHOLD ||
actualDisplayString.length > OUTPUT_NEW_LINE_THRESHOLD;
var msg = [
'Expected', expectedDisplayString, 'but was', actualDisplayString
].join(shouldUseNewLines ? '\n' : ' ');
if ((typeof expected == 'string') && (typeof actual == 'string')) {
// Try to find a human-readable difference.
var limit = Math.min(expected.length, actual.length);
var commonPrefix = 0;
while (commonPrefix < limit &&
expected.charAt(commonPrefix) == actual.charAt(commonPrefix)) {
commonPrefix++;
}
var commonSuffix = 0;
while (commonSuffix < limit &&
expected.charAt(expected.length - commonSuffix - 1) ==
actual.charAt(actual.length - commonSuffix - 1)) {
commonSuffix++;
}
if (commonPrefix + commonSuffix > limit) {
commonSuffix = 0;
}
if (commonPrefix > 2 || commonSuffix > 2) {
var printString = function(str) {
'use strict';
var startIndex = Math.max(0, commonPrefix - 2);
var endIndex = Math.min(str.length, str.length - (commonSuffix - 2));
return (startIndex > 0 ? '...' : '') +
str.substring(startIndex, endIndex) +
(endIndex < str.length ? '...' : '');
};
var expectedPrinted = printString(expected);
var expectedActual = printString(actual);
var shouldUseNewLinesInDiff =
expectedPrinted.length > OUTPUT_NEW_LINE_THRESHOLD ||
expectedActual.length > OUTPUT_NEW_LINE_THRESHOLD;
msg += '\nDifference was at position ' + commonPrefix + '. ' + [
'Expected', '[' + expectedPrinted + ']', 'vs. actual',
'[' + expectedActual + ']'
].join(shouldUseNewLinesInDiff ? '\n' : ' ');
}
}
return msg;
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assert = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var comment = commentArg(1, arguments);
var booleanValue = nonCommentArg(1, 1, arguments);
_assert(
comment, typeof booleanValue === 'boolean',
'Bad argument to assert(boolean): ' +
_displayStringForValue(booleanValue));
_assert(comment, booleanValue, 'Call to assert(boolean) with false');
};
/** @const */
var assert = goog.testing.asserts.assert;
/**
* Asserts that the function throws an error.
*
* @param {!(string|Function)} a The assertion comment or the function to call.
* @param {!Function=} opt_b The function to call (if the first argument of
* `assertThrows` was the comment).
* @return {!Error} The error thrown by the function. Beware that code may throw
* other types in strange scenarios.
* @throws {goog.testing.JsUnitException} If the assertion failed.
*/
goog.testing.asserts.assertThrows = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var func = nonCommentArg(1, 1, arguments);
var comment = commentArg(1, arguments);
_assert(
comment, typeof func == 'function',
'Argument passed to assertThrows is not a function');
try {
func();
} catch (e) {
goog.testing.asserts.removeOperaStacktrace_(e);
var testCase = _getCurrentTestCase();
if (e && e['isJsUnitException'] && testCase) {
goog.testing.asserts.raiseException(
comment,
'Function passed to assertThrows caught a JsUnitException (usually ' +
'from an assert or call to fail()). If this is expected, use ' +
'assertThrowsJsUnitException instead.');
}
return e;
}
goog.testing.asserts.raiseException(
comment, 'No exception thrown from function passed to assertThrows');
throw new Error('Should have thrown an error.'); // Make the compiler happy.
};
/** @const */
var assertThrows = goog.testing.asserts.assertThrows;
/**
* Removes a stacktrace from an Error object for Opera 10.0.
* @param {*} e
* @private
*/
goog.testing.asserts.removeOperaStacktrace_ = function(e) {
'use strict';
if (!goog.isObject(e)) return;
const stack = e['stacktrace'];
const errorMsg = e['message'];
if (typeof stack !== 'string' || typeof errorMsg !== 'string') {
return;
}
const stackStartIndex = errorMsg.length - stack.length;
if (errorMsg.indexOf(stack, stackStartIndex) == stackStartIndex) {
e['message'] = errorMsg.slice(0, stackStartIndex - 14);
}
};
/**
* Asserts that the function does not throw an error.
*
* @param {!(string|Function)} a The assertion comment or the function to call.
* @param {!Function=} opt_b The function to call (if the first argument of
* `assertNotThrows` was the comment).
* @return {*} The return value of the function.
* @throws {goog.testing.JsUnitException} If the assertion failed.
*/
goog.testing.asserts.assertNotThrows = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var comment = commentArg(1, arguments);
var func = nonCommentArg(1, 1, arguments);
_assert(
comment, typeof func == 'function',
'Argument passed to assertNotThrows is not a function');
try {
return func();
} catch (e) {
comment = comment ? (comment + '\n') : '';
comment += 'A non expected exception was thrown from function passed to ' +
'assertNotThrows';
// Some browsers don't have a stack trace so at least have the error
// description.
var stackTrace = e['stack'] || e['stacktrace'] || e.toString();
goog.testing.asserts.raiseException(comment, stackTrace);
}
};
/** @const */
var assertNotThrows = goog.testing.asserts.assertNotThrows;
/**
* Asserts that the given callback function results in a JsUnitException when
* called, and that the resulting failure message matches the given expected
* message.
* @param {function() : void} callback Function to be run expected to result
* in a JsUnitException (usually contains a call to an assert).
* @param {string=} opt_expectedMessage Failure message expected to be given
* with the exception.
* @return {!goog.testing.JsUnitException} The error thrown by the function.
* @throws {goog.testing.JsUnitException} If the function did not throw a
* JsUnitException.
*/
goog.testing.asserts.assertThrowsJsUnitException = function(
callback, opt_expectedMessage) {
'use strict';
try {
callback();
} catch (e) {
var testCase = _getCurrentTestCase();
if (testCase) {
testCase.invalidateAssertionException(e);
} else {
goog.global.console.error(
'Failed to remove expected exception: no test case is installed.');
}
if (!e.isJsUnitException) {
goog.testing.asserts.fail(
'Expected a JsUnitException, got \'' + e + '\' instead');
}
if (typeof opt_expectedMessage != 'undefined' &&
e.message != opt_expectedMessage) {
goog.testing.asserts.fail(
'Expected message [' + opt_expectedMessage + '] but got [' +
e.message + ']');
}
return e;
}
var msg = 'Expected a failure';
if (typeof opt_expectedMessage != 'undefined') {
msg += ': ' + opt_expectedMessage;
}
throw new goog.testing.JsUnitException(msg);
};
/** @const */
var assertThrowsJsUnitException =
goog.testing.asserts.assertThrowsJsUnitException;
/**
* Asserts that the IThenable rejects.
*
* This is useful for asserting that async functions throw, like an asynchronous
* assertThrows. Example:
*
* ```
* async function shouldThrow() { throw new Error('error!'); }
* async function testShouldThrow() {
* const error = await assertRejects(shouldThrow());
* assertEquals('error!', error.message);
* }
* ```
*
* @param {!(string|IThenable)} a The assertion comment or the IThenable.
* @param {!IThenable=} opt_b The IThenable (if the first argument of
* `assertRejects` was the comment).
* @return {!IThenable<*>} A child IThenable which resolves with the error that
* the passed in IThenable rejects with. This IThenable will reject if the
* passed in IThenable does not reject.
*/
goog.testing.asserts.assertRejects = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var thenable = /** @type {!IThenable<*>} */ (nonCommentArg(1, 1, arguments));
var comment = commentArg(1, arguments);
_assert(
comment, goog.isObject(thenable) && typeof thenable.then === 'function',
'Argument passed to assertRejects is not an IThenable');
return thenable.then(
function() {
'use strict';
goog.testing.asserts.raiseException(
comment, 'IThenable passed into assertRejects did not reject');
},
function(e) {
'use strict';
goog.testing.asserts.removeOperaStacktrace_(e);
return e;
});
};
/** @const */
var assertRejects = goog.testing.asserts.assertRejects;
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assertTrue = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var comment = commentArg(1, arguments);
var booleanValue = nonCommentArg(1, 1, arguments);
_assert(
comment, typeof booleanValue === 'boolean',
'Bad argument to assertTrue(boolean): ' +
_displayStringForValue(booleanValue));
_assert(comment, booleanValue, 'Call to assertTrue(boolean) with false');
};
/** @const */
var assertTrue = goog.testing.asserts.assertTrue;
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assertFalse = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var comment = commentArg(1, arguments);
var booleanValue = nonCommentArg(1, 1, arguments);
_assert(
comment, typeof booleanValue === 'boolean',
'Bad argument to assertFalse(boolean): ' +
_displayStringForValue(booleanValue));
_assert(comment, !booleanValue, 'Call to assertFalse(boolean) with true');
};
/** @const */
var assertFalse = goog.testing.asserts.assertFalse;
/**
* @param {*} a The expected value (2 args) or the debug message (3 args).
* @param {*} b The actual value (2 args) or the expected value (3 args).
* @param {*=} opt_c The actual value (3 args only).
*/
goog.testing.asserts.assertEquals = function(a, b, opt_c) {
'use strict';
_validateArguments(2, arguments);
var var1 = nonCommentArg(1, 2, arguments);
var var2 = nonCommentArg(2, 2, arguments);
_assert(
commentArg(2, arguments), var1 === var2,
goog.testing.asserts.getDefaultErrorMsg_(var1, var2));
};
/** @const */
var assertEquals = goog.testing.asserts.assertEquals;
/**
* @param {*} a The expected value (2 args) or the debug message (3 args).
* @param {*} b The actual value (2 args) or the expected value (3 args).
* @param {*=} opt_c The actual value (3 args only).
*/
goog.testing.asserts.assertNotEquals = function(a, b, opt_c) {
'use strict';
_validateArguments(2, arguments);
var var1 = nonCommentArg(1, 2, arguments);
var var2 = nonCommentArg(2, 2, arguments);
_assert(
commentArg(2, arguments), var1 !== var2,
'Expected not to be ' + _displayStringForValue(var2));
};
/** @const */
var assertNotEquals = goog.testing.asserts.assertNotEquals;
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assertNull = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(
commentArg(1, arguments), aVar === null,
goog.testing.asserts.getDefaultErrorMsg_(null, aVar));
};
/** @const */
var assertNull = goog.testing.asserts.assertNull;
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assertNotNull = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(
commentArg(1, arguments), aVar !== null,
'Expected not to be ' + _displayStringForValue(null));
};
/** @const */
var assertNotNull = goog.testing.asserts.assertNotNull;
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assertUndefined = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(
commentArg(1, arguments), aVar === JSUNIT_UNDEFINED_VALUE,
goog.testing.asserts.getDefaultErrorMsg_(JSUNIT_UNDEFINED_VALUE, aVar));
};
/** @const */
var assertUndefined = goog.testing.asserts.assertUndefined;
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assertNotUndefined = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(
commentArg(1, arguments), aVar !== JSUNIT_UNDEFINED_VALUE,
'Expected not to be ' + _displayStringForValue(JSUNIT_UNDEFINED_VALUE));
};
/** @const */
var assertNotUndefined = goog.testing.asserts.assertNotUndefined;
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assertNullOrUndefined = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(
commentArg(1, arguments), aVar == null,
'Expected ' + _displayStringForValue(null) + ' or ' +
_displayStringForValue(JSUNIT_UNDEFINED_VALUE) + ' but was ' +
_displayStringForValue(aVar));
};
/** @const */
var assertNullOrUndefined = goog.testing.asserts.assertNullOrUndefined;
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assertNotNullNorUndefined = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
goog.testing.asserts.assertNotNull.apply(null, arguments);
goog.testing.asserts.assertNotUndefined.apply(null, arguments);
};
/** @const */
var assertNotNullNorUndefined = goog.testing.asserts.assertNotNullNorUndefined;
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assertNonEmptyString = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(
commentArg(1, arguments), aVar !== JSUNIT_UNDEFINED_VALUE &&
aVar !== null && typeof aVar == 'string' && aVar !== '',
'Expected non-empty string but was ' + _displayStringForValue(aVar));
};
/** @const */
var assertNonEmptyString = goog.testing.asserts.assertNonEmptyString;
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assertNaN = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(
commentArg(1, arguments), aVar !== aVar,
'Expected NaN but was ' + _displayStringForValue(aVar));
};
/** @const */
var assertNaN = goog.testing.asserts.assertNaN;
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
goog.testing.asserts.assertNotNaN = function(a, opt_b) {
'use strict';
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(commentArg(1, arguments), !isNaN(aVar), 'Expected not NaN');
};
/** @const */
var assertNotNaN = goog.testing.asserts.assertNotNaN;
/**
* The return value of the equality predicate passed to findDifferences below,
* in cases where the predicate can't test the input variables for equality.
* @type {?string}
*/
goog.testing.asserts.EQUALITY_PREDICATE_CANT_PROCESS = null;
/**
* The return value of the equality predicate passed to findDifferences below,
* in cases where the input vriables are equal.
* @type {?string}
*/
goog.testing.asserts.EQUALITY_PREDICATE_VARS_ARE_EQUAL = '';
/**
* @const {!Object<string, boolean>}
*/
goog.testing.asserts.ARRAY_TYPES = {
'Array': true,
'Float32Array': true,
'Float64Array': true,
'Int8Array': true,
'Int16Array': true,
'Int32Array': true,
'Uint8Array': true,
'Uint8ClampedArray': true,
'Uint16Array': true,
'Uint32Array': true,
'BigInt64Array': true,
'BigUint64Array': true
};
/**
* The result of a comparison performed by an EqualityFunction: if undefined,
* the inputs are equal; otherwise, a human-readable description of their
* inequality.
*
* @typedef {string|undefined}
*/
goog.testing.asserts.ComparisonResult;
/**
* A equality predicate.
*
* The first two arguments are the values to be compared. The third is an
* equality function which can be used to recursively apply findDifferences.
*
* An example comparison implementation for Array could be:
*
* function arrayEq(a, b, eq) {
* if (a.length !== b.length) {
* return "lengths unequal";
* }
*
* const differences = [];
* for (let i = 0; i < a.length; i++) {
* // Use the findDifferences implementation to perform recursive
* // comparisons.
* const diff = eq(a[i], b[i], eq);
* if (diff) {
* differences[i] = diff;
* }
* }
*
* if (differences) {
* return `found array differences: ${differences}`;
* }
*
* // Otherwise return undefined, indicating no differences.
* return undefined;
* }
*
* @typedef {function(?, ?, !goog.testing.asserts.EqualityFunction):
* ?goog.testing.asserts.ComparisonResult}
*/
goog.testing.asserts.EqualityFunction;
/**
* A map from prototype to custom equality matcher.
*
* @type {!Map<!Object, !goog.testing.asserts.EqualityFunction>}
* @private
*/
goog.testing.asserts.CUSTOM_EQUALITY_MATCHERS = new Map();
/**
* Returns the custom equality predicate for a given prototype, or else
* undefined.
*
* @param {?Object} prototype
* @return {!goog.testing.asserts.EqualityFunction|undefined}
* @private
*/
goog.testing.asserts.getCustomEquality = function(prototype) {
for (; (prototype != null) && (typeof prototype === 'object') &&
(prototype !== Object.prototype);
prototype = Object.getPrototypeOf(prototype)) {
const matcher = goog.testing.asserts.CUSTOM_EQUALITY_MATCHERS.get(
/** @type {!Object} */ (prototype));
if (matcher) {
return matcher;
}
}
return undefined;
};
/**
* Returns the most specific custom equality predicate which can be applied to
* both arguments, or else undefined.
*
* @param {!Object} obj1
* @param {!Object} obj2
* @return {!goog.testing.asserts.EqualityFunction|undefined}
* @private
*/
goog.testing.asserts.getMostSpecificCustomEquality = function(obj1, obj2) {
for (let prototype = Object.getPrototypeOf(obj1); (prototype != null) &&
(typeof prototype === 'object') && (prototype !== Object.prototype);
prototype = Object.getPrototypeOf(prototype)) {
if (prototype.isPrototypeOf(obj2)) {
return goog.testing.asserts.getCustomEquality(prototype);
}
}
// Otherwise, obj1 and obj2 did not share a common ancestor other than
// Object.prototype so we cannot have a comparator.
return undefined;
};
/**
* Executes a custom equality function
*
* @param {!goog.testing.asserts.EqualityFunction} comparator
* @param {!Object} obj1
* @param {!Object} obj2
* @param {string} path of the current field being checked.
* @return {?goog.testing.asserts.ComparisonResult}
* @private
*/
goog.testing.asserts.applyCustomEqualityFunction = function(
comparator, obj1, obj2, path) {
const /* !goog.testing.asserts.EqualityFunction */ callback =
(left, right, unusedEq) => {
const result = goog.testing.asserts.findDifferences(left, right);
return result ? (path ? path + ': ' : '') + result : undefined;
};
return comparator(obj1, obj2, callback);
};
/**
* Marks the given prototype as having equality semantics provided by the given
* custom equality function.
*
* This will cause findDifferences and assertObjectEquals to use the given
* function when comparing objects with this prototype. When comparing two
* objects with different prototypes, the equality (if any) attached to their
* lowest common ancestor in the prototype hierarchy will be used.
*
* @param {!Object} prototype
* @param {!goog.testing.asserts.EqualityFunction} fn
*/
goog.testing.asserts.registerComparator = function(prototype, fn) {
// First check that there is no comparator currently defined for this
// prototype.
if (goog.testing.asserts.CUSTOM_EQUALITY_MATCHERS.has(prototype)) {
throw new Error('duplicate comparator installation for ' + prototype);
}
// We cannot install custom equality matchers on Object.prototype, as it
// would replace all other comparisons.
if (prototype === Object.prototype) {
throw new Error('cannot customize root object comparator');
}
goog.testing.asserts.CUSTOM_EQUALITY_MATCHERS.set(prototype, fn);
};
/**
* Clears the custom equality function currently applied to the given prototype.
* Returns true if a function was removed.
*
* @param {!Object} prototype
* @return {boolean} whether a comparator was removed.
*/
goog.testing.asserts.clearCustomComparator = function(prototype) {
return goog.testing.asserts.CUSTOM_EQUALITY_MATCHERS.delete(prototype);
};
/**
* Determines if two items of any type match, and formulates an error message
* if not.
* @param {*} expected Expected argument to match.
* @param {*} actual Argument as a result of performing the test.
* @param {(function(string, *, *): ?string)=} opt_equalityPredicate An optional
* function that can be used to check equality of variables. It accepts 3
* arguments: type-of-variables, var1, var2 (in that order) and returns an
* error message if the variables are not equal,
* goog.testing.asserts.EQUALITY_PREDICATE_VARS_ARE_EQUAL if the variables
* are equal, or
* goog.testing.asserts.EQUALITY_PREDICATE_CANT_PROCESS if the predicate
* couldn't check the input variables. The function will be called only if
* the types of var1 and var2 are identical.
* @return {?string} Null on success, error message on failure.
*/
goog.testing.asserts.findDifferences = function(
expected, actual, opt_equalityPredicate) {
'use strict';
var failures = [];
// Non-null if there an error at the root (with no path). If so, we should
// fail, but not add to the failures array (because it will be included at the
// top anyway).
let /** ?string*/ rootFailure = null;
var seen1 = [];
var seen2 = [];
// To avoid infinite recursion when the two parameters are self-referential
// along the same path of properties, keep track of the object pairs already
// seen in this call subtree, and abort when a cycle is detected.
function innerAssertWithCycleCheck(var1, var2, path) {
// This is used for testing, so we can afford to be slow (but more
// accurate). So we just check whether var1 is in seen1. If we
// found var1 in index i, we simply need to check whether var2 is
// in seen2[i]. If it is, we do not recurse to check var1/var2. If
// it isn't, we know that the structures of the two objects must be
// different.
//
// This is based on the fact that values at index i in seen1 and
// seen2 will be checked for equality eventually (when
// innerAssertImplementation(seen1[i], seen2[i], path) finishes).
for (var i = 0; i < seen1.length; ++i) {
var match1 = seen1[i] === var1;
var match2 = seen2[i] === var2;
if (match1 || match2) {
if (!match1 || !match2) {
// Asymmetric cycles, so the objects have different structure.
failures.push('Asymmetric cycle detected at ' + path);
}
return;
}
}
seen1.push(var1);
seen2.push(var2);
innerAssertImplementation(var1, var2, path);
seen1.pop();
seen2.pop();
}
const equalityPredicate = function(type, var1, var2) {
'use strict';
// use the custom predicate if supplied.
const customPredicateResult = opt_equalityPredicate ?
opt_equalityPredicate(type, var1, var2) :
goog.testing.asserts.EQUALITY_PREDICATE_CANT_PROCESS;
if (customPredicateResult !==
goog.testing.asserts.EQUALITY_PREDICATE_CANT_PROCESS) {