-
Notifications
You must be signed in to change notification settings - Fork 4
/
Assert.js
1210 lines (978 loc) · 33.7 KB
/
Assert.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
'use strict';
const isNode = typeof window === 'undefined';
const inspect = require(isNode ? 'util' : './inspect').inspect;
const arraySlice = Array.prototype.slice;
const toString = Object.prototype.toString;
function Empty () {}
Empty.prototype = Object.create(null);
/**
* @class Assert
*/
class Assert {
static expect (value) {
let A = this || Assert; // use "this" to allow for derived class
return new A(value);
}
constructor (value, previous, options) {
let me = this;
let A = me.constructor;
me.assertions = [];
me.actual = me.value = value;
me._modifiers = new Empty();
if (previous) {
me._previous = previous;
if (options) {
if (options.description) {
me._explanationPrefix += ' ' + options.description;
}
}
}
if (!A.hasOwnProperty('isSetup')) {
A.setup();
}
}
assertion () {
let me = this;
let expected = me.expected;
if (expected) {
try {
let result = !me._word.evaluate.call(me, me.value, ...expected);
me.failed = me._modifiers.not ? !result : result;
}
catch (e) {
me.failed = e.isAssertFailure ? e.message : e;
}
}
}
before (word) {
this._word = word;
}
begin (expected) {
let me = this;
let A = me.constructor;
let async = me._async;
let previous = A._current;
if (previous && !async) {
me._async = previous._async.then(() => {
me.begin(expected);
return me._async; // this is reassigned below
},
e => {
if (A._current === me) {
// If this is the end of the line of assertions, clean things up
A._current = null;
}
throw e;
});
// This assert was made after some other async asserts, so get in line...
A._current = me;
}
else if (async || Util.isPromise(me.value) || Util.isPromise(...expected)) {
me._async = A.Promise.all(expected.concat(me.value)).then(values => {
me.expected = values;
me.actual = me.value = values.pop();
if (A._current === me) {
// If this is the end of the line of assertions, clean things up
A._current = null;
}
me.assertion();
me.report();
},
e => {
if (A._current === me) {
A._current = null;
}
me.failure(e);
me.report();
});
if (!async) {
// This is the first async assert, so start the line with it...
A._current = me;
}
}
else {
me.expected = expected;
}
}
failure (e) {
this.failed = e;
}
explain () {
let me = this;
let fn = me._word.explain;
let exp = me.expected;
let n = exp.length;
const A = me.constructor;
me.actual = A.print(me.actual);
me.expectation = me.expectation || (n ? A.print(n === 1 ? exp[0] : exp) : '');
let ret = fn && fn.call(me, me.value, ...exp);
if (!ret) {
ret = `${me._explanationPrefix} ${me.actual} ${me.assertions.join(' ')}`;
if (me.expectation) {
ret += ' ' + me.expectation;
}
}
return ret;
}
finish () {
return new this.constructor._Conjunction(this);
}
report () {
let me = this;
let failure = me.failed;
if (me.hasOwnProperty('failed')) {
if (failure === true) {
me.failed = me.explain();
}
me.constructor.report(me);
}
}
static getDefaults () {
const A = this;
return this.normalize({
to: true,
not: true,
only: true,
have: true,
own: true,
exactly: true,
'a,an': {
evaluate (actual, expected) {
let te = Util.typeOf(expected);
let re = te === 'regexp';
if (!re && te !== 'string') {
return actual instanceof expected;
}
let t = Util.typeOf(actual);
if (re) {
return expected.test(t); // ex expect(2).to.be.a(/number|string/);
}
return t === expected; // ex expect(2).to.be.a('number');
},
explain (object, type) {
if (typeof type === 'string') {
this.expectation = type; // removes the quotes on "type"
}
}
},
'approx,approximately': {
evaluate (actual, expected, epsilon) {
epsilon = epsilon || 0.001;
A.expect(actual).to.be.a('number');
A.expect(expected).to.be.a('number');
A.expect(epsilon).to.be.a('number').and.to.be.gt(0);
let delta = Math.abs(actual - expected);
return delta <= epsilon;
},
explain (actual, expected, epsilon) {
epsilon = epsilon || 0.001;
this.assertions.pop(); // remove "approx"
this.expectation = `${A.print(expected)} ± ${A.print(epsilon)}`;
}
},
be (actual, expected) {
return actual === expected;
},
contain: {
evaluate (actual, expected, at) {
let i = actual.indexOf(expected);
if (at != null) {
return i === at;
}
return i > -1;
},
explain (actual, expected, at) {
if (at != null) {
this.expectation = `${A.print(expected)} at ${at}`;
}
}
},
empty (actual) {
let ret = actual == null,
t;
if (!ret) {
t = typeof actual;
if (t === 'string' || Util.isArrayLike(actual)) {
ret = !actual.length;
}
else if (t === 'object') {
ret = true;
for (t in actual) {
ret = false;
break;
}
}
}
return ret;
},
equal (actual, expected) {
if (this._modifiers.flatly && expected && typeof expected === 'object') {
this.expected[0] = expected = Util.copy({}, expected);
}
return Util.isEqual(actual, expected, false);
},
falsy (actual) {
return !actual;
},
flatly: {
get (value) {
if (value && typeof value === 'object') {
this.actual = this.value = Util.copy({}, value);
}
}
},
get: {
invoke (value, name) {
return new A(value && value[name]);
}
},
'greaterThan,gt,above' (actual, expected) {
return actual > expected;
},
'greaterThanOrEqual,atLeast,ge,gte' (actual, expected) {
return actual >= expected;
},
in (actual, set) {
return set.indexOf(actual) > -1;
},
'key,keys' (actual, ...expected) {
let ok = true;
let only = this._modifiers.only;
let own = this._modifiers.own;
let keyMap = only && {};
expected.forEach(key => {
if (ok) {
if (keyMap) {
keyMap[key] = true;
}
ok = own ? actual.hasOwnProperty(key) : (key in actual);
}
});
if (ok && only) {
for (let key in actual) {
if (!own || actual.hasOwnProperty(key)) {
if (!keyMap[key]) {
ok = false;
break;
}
}
}
}
return ok;
},
length: {
evaluate (actual, expected) {
let len = actual ? actual.length : NaN;
return len === expected;
},
get () {
let v = this.value;
this.value = v ? v.length : NaN;
}
},
'lessThan,lt,below' (actual, expected) {
return actual < expected;
},
'lessThanOrEqual,atMost,le,lte' (actual, expected) {
return actual <= expected;
},
match (actual, expected) {
return expected.test(String(actual));
},
'NaN,nan': {
evaluate (actual) {
return isNaN(actual);
},
explain () {
let assertions = this.assertions;
assertions.pop(); // remove "nan"
assertions.push('NaN');
}
},
property: {
evaluate (object, property, value) {
let only = this._modifiers.only;
//TODO deep properties "foo.bar.baz"
if (this._modifiers.own) {
if (!object.hasOwnProperty(property)) {
return false;
}
if (only) {
for (let s of Object.keys(object)) {
if (s !== property) {
return false;
}
}
}
}
else if (!(property in object)) {
return false;
}
else if (only) {
for (let s in object) {
if (s !== property) {
return false;
}
}
}
if (value !== undefined) {
return object[property] === value;
}
return true;
},
explain (object, property, value) {
if (value !== undefined) {
this.expectation = `${A.print(property)} === ${A.print(value)}`;
}
}
},
same: {
evaluate (actual, expected) {
if (this._modifiers.flatly && expected && typeof expected === 'object') {
this.expected[0] = expected = Util.copy({}, expected);
}
return Util.isEqual(actual, expected, true);
},
explain () {
let assertions = this.assertions;
assertions.pop(); // remove "same"
assertions.push('the same as');
}
},
throw: {
evaluate: function evaluate (actual, type) {
let msg, ok = false;
if (actual instanceof Error) {
// passing an Error as in "expect(e).to.throw(...)" isn't
// really what we are trying to achieve here, but rather to
// assist in augmenting the throw assertion and still access
// this criteria matching logic...
let e = actual;
ok = true;
msg = e.message;
if (type) {
if (typeof type === 'string') {
if (this._modifiers.exactly) {
ok = msg === type;
}
else {
ok = (msg.indexOf(type) > -1);
}
}
else if (type === Error ||
Error.prototype.isPrototypeOf(type.prototype)) {
ok = e instanceof type;
}
else {
ok = type.test(msg);
}
}
e.matched = ok;
this._threw = e;
}
else {
try {
actual();
}
catch (e) {
ok = evaluate.call(this, e, type);
}
}
return ok;
},
explain (fn, type) {
if (this.failed) {
let not = this._modifiers.not;
let e = this._threw;
let s = this.expectation;
s = s ? s + ' ' : '';
if (!e) {
// expect(f).to.throw('X')
// ==> Expected f to throw X and it did not throw
s += `but it did not throw`;
}
else if (type && e.matched) {
// expect(f).not.to.throw('X')
// ==> Expected f not to throw X but it did
// expect(f).not.to.throw();
// ==> Expected f not to throw but it did
s += `but it did`;
}
else {
// expect(f).to.throw('X')
// ==> Expected f to throw X but threw Y
s += `but it threw ${A.print(e.message)}`;
}
this.expectation = s;
}
}
},
'truthy,ok' (actual) {
return !!actual;
},
within: {
evaluate (actual, min, max, constraint) {
let lo, hi;
if (constraint) {
lo = constraint[0];
hi = constraint[1];
}
else if (typeof min === 'string') {
let m = Util.rangeRe.exec(min);
lo = m[1];
min = parseFloat(m[2]);
max = parseFloat(m[3]);
hi = m[4];
}
else {
lo = '[';
hi = ']';
}
this._constraint = Util._within[lo+hi];
if (lo === '[' ? actual < min : actual <= min) {
return false;
}
return hi === ']' ? actual <= max : actual < max;
},
explain (actual, min, max, constraint) {
if (constraint) {
this.expectation = A.print(this.expected.slice(0, 2));
}
this.expectation += this._constraint;
}
}
});
} // getDefaults
static normalize (registry) {
let ret = new Empty();
for (let name of Object.keys(registry)) {
let def = registry[name];
if (def === true) {
def = {};
}
else if (typeof def === 'function') {
def = {
evaluate: def
};
}
let names = name.split(',');
name = names.shift();
if (def.alias) {
names = names.concat(def.alias); // handle String or String[]
}
ret[name] = {
name: name,
alias: names,
evaluate: def.evaluate || null,
explain: def.explain || null,
get: def.get || null,
invoke: def.invoke || null,
next: def.next || null
};
}
return ret;
}
static register (...args) {
const A = this;
// ensure the defaults are setup first
if (!A.hasOwnProperty('isSetup')) {
A.setup();
}
for (let registry of args) {
if (typeof registry === 'function') {
registry.call(A, A, Util);
continue;
}
registry = A.normalize(registry);
for (let name of Object.keys(registry)) {
let def = registry[name];
let word = A._getWord(name, def);
word.update(def);
}
}
}
static print (obj, options) {
let t = Util.typeOf(obj);
if (t === 'error') {
if (obj.message) {
return `${obj.name}(${this.print(obj.message)})`;
}
return `${obj.name}`;
}
else if (t === 'arguments') {
obj = arraySlice.call(obj);
}
else if (t === 'number') {
if (isNaN(obj)) {
return 'NaN';
}
if (!isFinite(obj)) {
return obj < 0 ? '-∞' : '∞';
}
}
return Util.inspect(obj, options);
}
static report (assertion) {
let failure = assertion.failed;
if (this.log) {
this.log.push(assertion);
}
if (failure) {
this.reportFailure(failure, assertion);
}
}
static reportFailure (msg, assertion) {
let stackFrame = assertion._stackFrame;
if (this.hasOwnProperty('fullCallStacks') && this.fullCallStacks) {
stackFrame = null;
}
throw new this.Failure(msg, {
assertion: assertion
}, stackFrame);
}
static setup () {
let registry = this.getDefaults();
this.isSetup = true;
this.register(registry);
}
//-----------------------------------------------------------------------
// Private
/**
* This method accepts a modifier (such as `'not'`) and updates the `_modifiers`
* map accordingly. This method will throw an `Error` if modifier cannot be used
* in the current state.
* @param {String} modifier
* @param {Boolean} [track=true]
* @private
*/
_applyModifier (modifier, track) {
let state = this._state = this.constructor.registry[modifier];
if (track !== false) {
let modifiers = this._modifiers;
let name = state.name;
if (!modifiers[name]) {
modifiers[name] = true;
this.assertions.push(modifier);
}
}
}
_doAssert (word, expected) {
let me = this;
me.before(word);
me.begin(expected);
me.assertion();
me.report();
return me.finish();
}
_doInvoke (word, expected) {
return word.invoke.call(this, this.value, ...expected) || this;
}
static _getWord (name, def) {
let A = this;
if (!A.hasOwnProperty('registry')) {
A.registry = new Empty();
A.forbidden = {};
A._Conjunction = class extends A.Conjunction {};
let names = [];
for (let C = A; ; C = Object.getPrototypeOf(C)) {
names.push(...Object.getOwnPropertyNames(C.prototype));
if (C === Assert) {
break;
}
}
names.sort();
for (let key of names) {
if (Util.validNameRe.test(key)) {
A.forbidden[key] = true; // all keys (even inherited ones)
}
}
}
let word = A.registry[name];
if (!word && def) {
if (A.forbidden[name]) {
throw new Error(`Cannot redefine "${name}"`);
}
word = new A.Word(A, name, def);
}
return word;
}
} // Assert
Assert.Conjunction = class {
constructor (assertion) {
this._assertion = assertion;
let async = assertion._async;
if (async) {
this.then = async.then.bind(async);
}
}
get and () {
const a = this._assertion;
const A = a.constructor;
return new A(a.value, a);
}
};
Assert.Failure = class extends Error {
constructor (message, properties, stackFrame) {
super(message);
if (stackFrame && Error.captureStackTrace) {
// This is a really odd bird V8 extension that sets "stack" on
// arguments[0] and limits the trace by arguments[1]
Error.captureStackTrace(this, stackFrame);
}
// else {
// try {
// throw new Error();
// }
// catch (e) {
// this.stack = e.stack;
// }
// }
Util.copyOwnExcept(this, properties, /constructor|message|name|stack|toJSON/);
}
get isAssertFailure () {
return true;
}
get name () {
return 'Assert.Failure';
}
toJSON (includeStack) {
let data = Util.copyOwnExcept({
name: this.name
}, this, /stack/);
if (includeStack !== false && this.stack) {
data.stack = this.stack;
}
return data;
}
};
Assert.Word = class {
constructor (A, name, def) {
let me = this;
me.owner = A;
me.name = name;
me.track = def.invoke ? !!def.track : (def.track !== false);
me.define(name);
}
define (name, target) {
if (!Util.validNameRe.test(name)) {
throw new Error(`Cannot register invalid name "${name}"`);
}
const word = this;
const A = word.owner;
if (!target) {
target = A.prototype;
A.registry[name] = word;
}
Object.defineProperty(target, name, {
get () {
let me = this;
let assertion = me.$me || me;
let from = me.$word;
let get = from && from.get;
if (get) {
// We have this "previous" get method lurking if we have just
// returned a bound method (since we cannot know if that method
// will be called or simply used as a step in the dot-chain).
//
// For example:
//
// expect(x).to.be.same(y);
// ^^^^
// we are here
//
// If hypothetically "be" defined a getter, "me.$word" is "be"
// and we need to call that getter to see if it wants us to
// jump tracks "just in time" to evaluate "same".
//
let a = get.call(assertion, assertion.value);
if (a) {
me = assertion = a;
}
}
// If we are being asked for a method, we won't know whether it will
// be called or a step in the dot-chain (see above), so we return a
// special bound method. If it is called, it routes the call to the
// assertion. It also defines all the Words as properties on itself
// so we can proceed beyond it using dots.
if (word.evaluate || word.invoke) {
let bound = function (...args) {
if (word.evaluate) {
assertion._stackFrame = bound;
return assertion._doAssert(word, args);
}
return assertion._doInvoke(word, args);
};
bound.$me = assertion;
bound.$word = word;
assertion._applyModifier(name, word.track);
for (let mod in A.registry) {
let w = A.registry[mod];
// We can skip this word and its aliases...
if (w !== word) {
w.define(mod, bound);
}
}
return bound;
}
// The word is not a method, so we can process it completely now. If
// it defined a getter, we can call it now. If it wants to redirect
// the assert, we'll return the new instance, otherwise we'll track
// the word in the modifiers collection. Since "this" could be some
// bound method, we have to be careful to separate "this" (aka "me")
// from the actual Assert instance ("assertion").
get = word.get;
if (get) {
let v = get.call(assertion, assertion.value);
if (v) {
return v;
}
}
assertion._applyModifier(name, word.track);
return me;
}
});
}
defineConjunction (name) {
const word = this;
const A = word.owner;
const C = A._Conjunction;
const next = word.next;
if (next) {
if (next.length < 2) {
// If the conjunction method ("next") takes only one argument, it is
// used as a property and not called, so just define a getter on the
// Conjunction prototype. We can call the "next" method and provide
// the "actual" value parameter.
Object.defineProperty(C.prototype, name, {
get () {
let me = this._assertion; // "this" is the Conjunction
return word.next.call(me, me.value);
}
});
}
else {
// If the conjunction method takes two or more arguments, the user
// must supply them, so we simply put a method on the Conjunction
// prototype to jam in the "actual" value as the first parameter.
C.prototype[name] = function (...args) {
let me = this._assertion; // "this" is the Conjunction
return word.next.call(me, me.value, ...args);
};
}
}
}
set (def, name) {
let value = def[name];
let ret = false;
if (value) {
let me = this;
let was = me[name];
if (was && was !== value) {
value._super = was;
}
me[name] = value;
ret = !was;
}
return ret;
}
update (def) {
let me = this;
if ((def.invoke || me.invoke) && (def.evaluate || me.evaluate)) {
throw new Error(`Cannot provide both evaluate and invoke functions`);
}
me.set(def, 'evaluate');
me.set(def, 'explain');
me.set(def, 'get');
me.set(def, 'invoke');
if (me.set(def, 'next')) {
// If this word was previously not a conjunction and now is, be sure
// to define it.
me.defineConjunction(me.name);
}
if ('track' in def) {
me.track = def.track;
}
for (let s of def.alias) {
me.define(s);
me.defineConjunction(s);
}
}
};
Assert.Promise = (typeof Promise !== 'undefined') && Promise.resolve && Promise;
// This prevents shape changes but also is used to generate the list of forbidden
// names:
Object.assign(Assert.prototype, {
_async: null,
_explanationPrefix: 'Expected',
_previous: null,
_word: null,
actual: null,
assertions: null,
expectation: null,
expected: null,
failed: null,