-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
1167 lines (1009 loc) · 31.8 KB
/
index.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';
var stringify = require('object-inspect')
, pruddy = require('pruddy-error')
, displayName = require('fn.name')
, isBuffer = require('is-buffer')
, propget = require('propget')
, deep = require('deep-eql');
var undefined
, called = 0
, toString = Object.prototype.toString
, hasOwn = Object.prototype.hasOwnProperty
, nodejs = !!(typeof process != 'undefined' && process.versions && process.versions.node);
/**
* Get class information for a given type.
*
* @param {Mixed} of Type to check.
* @returns {String} The name of the type.
* @api private
*/
function type(of) {
if (isBuffer(of)) return 'buffer';
if (of === undefined) return 'undefined';
if (of === null) return 'null';
if (of !== of) return 'nan';
return toString.call(of).slice(8, -1).toLowerCase();
}
/**
* Determine the size of a collection.
*
* @param {Mixed} collection The object we want to know the size of.
* @returns {Number} The size of the collection.
* @api private
*/
function size(collection) {
var x, i = 0;
if ('object' === type(collection)) {
if ('number' === type(collection.length)) return collection.length;
for (x in collection) {
if (hasOwn.call(collection, x)) i++;
}
return i;
}
try { return +collection.length || 0; }
catch (e) { return 0; }
}
/**
* Iterate over each item in an array.
*
* @param {Array} arr Array to iterate over.
* @param {Function} fn Callback for each item.
* @api private
*/
function each(what, fn) {
if ('array' === type(what)) {
for (var i = 0, length = what.length; i < length; i++) {
if (false === fn(what[i], i, what)) break;
}
} else {
for (var key in what) {
if (false === fn(what[key], key, what)) break;
}
}
}
/**
* Return a formatter function which compiles the expectation message. The
* message can contain various of patterns which will be replaced with
* a stringified/parsed version of the supplied argument for that given
* placeholder pattern. The following patterns are supported:
*
* - %% : Escape the % so you can write %d in your messages as %%d
* - %d : Cast argument in to a number.
* - %s : Cast argument in to a string.
* - %f : Transform function in to the name of the function.
* - %j : Transform object to a string.
*
* @param {String} expectation The expectation message.
* @returns {Function}
* @api private
*/
function format() {
var args = Array.prototype.slice.call(arguments, 0)
, expectation = args.shift()
, length = args.length
, i = 0;
return function compile(not) {
if (not) expectation = expectation.replace(/@/g, 'not');
else expectation = expectation.replace(/@\s/g, '');
return expectation.replace(/%[sdjf%]/g, function replace(char) {
if (i >= length) return char;
switch (char) {
case '%%':
return '%';
case '%s':
return String(args[i++]);
case '%d':
return Number(args[i++]);
case '%f':
return displayName(args[i++]);
case '%j':
try { return stringify(args[i++]); }
catch (e) { return '<error was thrown: '+ e.message +'>'; }
default: return char;
}
});
};
}
/**
* Assert values.
*
* Flags:
*
* - **stacktrace**: Include stacktrace in the assertion.
* - **diff**: Attempt to show the difference in object/values so we know why
* the assertion failed.
* - **sliceStack**: The amount of stacks we should slice off errors messages.
*
* @constructor
* @param {Mixed} value Value we need to assert.
* @param {Object} flags Assertion flags.
* @api public
*/
function Assume(value, flags) {
if (!(this instanceof Assume)) return new Assume(value, flags);
flags = flags || {};
this.stacktrace = 'stacktrace' in flags ? flags.stacktrace : Assume.config.includeStack;
this.sliceStack = 'slice' in flags ? flags.slice : Assume.config.sliceStack;
this.diff = 'diff' in flags ? flags.diff : Assume.config.showDiff;
//
// These flags are by the alias function so we can generate .not and .deep
// properties which are basically new Assume instances with these flags set.
//
for (var alias in Assume.flags) {
this[alias] = alias in flags ? flags[alias] : false;
}
this.value = value;
Assume.assign(this)('to, be, been, is, was, and, has, have, had, with, that, at, of, same, does, did, itself, which');
Assume.alias(value, this);
}
/**
* Attempt to mimic the configuration API of chai.js so it's dead simple to
* migrate from chai.js to assume.
*
* @type {Object}
* @public
*/
Assume.config = {
includeStack: true, // mapped to `stacktrace` as default value.
showDiff: true, // mapped to `diff` as default value.
sliceStack: 2 // Number of stacks that we should slice of the err stack..
};
/**
* List of flags and properties that need to be created for chaining purposes.
* Plugins could add extra properties that needed to be chained as well.
*
* @type {Object}
* @public
*/
Assume.flags = {
_not: 'doesnt, not, dont',
_deep: 'deep, deeply, strict, strictly'
};
/**
* Certain assertions can be disabled based on their environment that they are
* executing in. This object allows you in spect which of these conditional
* assertions are supported.
*
* @type {Object}
* @public
*/
Assume.supports = (function detect() {
var supports = {
generators: true,
native: true
};
try { eval('(function*(){})()'); }
catch (e) { supports.generators = false; }
try { eval('%GetV8Version()'); }
catch (e) { supports.native = false; }
return supports;
}(/* Douglas Crockford wants the dog balls inside youtu.be/taaEzHI9xyY#t=2020s */));
/**
* Registry of manually read files that are registered using Assume#register.
*
* @type {Object}
* @private
*/
Assume.registry = {};
/**
* By default we will try to read file's from disk or using Ajax calls to get
* correct line numbers for assertion errors but there are environments where
* both of these options are not available or preferred. You can manually
* register those files.
*
* @param {String} file File path for the given source code
* @param {String} source The source of the given file.
* @returns {Assume}
* @public
*/
Assume.register = function register(file, source) {
if ('object' === type(file)) {
each(file, function iterate(value, key) {
Assume.register(key, value);
});
} else {
Assume.registry[file] = source;
}
return Assume;
};
/**
* Assign values to a given thing.
*
* @param {Mixed} where Where do the new properties need to be assigned on.
* @returns {Function}
* @api public
*/
Assume.assign = function assign(where) {
return function assigns(aliases, value) {
if ('string' === typeof aliases) {
if (~aliases.indexOf(',')) aliases = aliases.split(/[\s|\,]+/);
else aliases = [aliases];
}
for (var i = 0, length = aliases.length; i < length; i++) {
where[aliases[i]] = value || where;
}
return where;
};
};
/**
* Add aliases to the given constructed asserts. This allows us to chain
* assertion calls together.
*
* @param {Mixed} value Value that we need to assert.
* @param {Assume} assert The constructed assert instance.
* @returns {Assume} The given assert instance.
* @api private
*/
Assume.alias = function alias(value, assert) {
var assign = Assume.assign(assert)
, flags, flag, prop;
for (prop in Assume.flags) {
if (!hasOwn.call(Assume.flags, prop)) continue;
if (!assert[prop]) {
flags = {};
for (flag in Assume.flags) {
if (!hasOwn.call(Assume.flags, flag)) continue;
flags[flag] = assert[flag];
}
//
// Add some default values to the flags.
//
flags.stacktrace = assert.stacktrace;
flags.diff = assert.diff;
flags[prop] = true;
assign(Assume.flags[prop], new Assume(value, flags));
} else assign(Assume.flags);
}
return assert;
};
/**
* API sugar of adding aliased prototypes to the Assume. This makes the code
* a bit more workable and human readable.
*
* @param {String|Array} aliases List of methods.
* @param {Function} fn Actual assertion function.
* @returns {Assume}
* @api public
*/
Assume.add = Assume.assign(Assume.prototype);
/**
* Asserts if the given value is the correct type. We need to use
* Object.toString here because there are some implementation bugs the `typeof`
* operator:
*
* - Chrome <= 9: /Regular Expressions/ are evaluated to `function`
*
* As well as all common flaws like Arrays being seen as Objects etc. This
* eliminates all these edge cases.
*
* @param {String} of Type of class it should equal
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('a, an', function typecheck(of, msg) {
of = of.toString().toLowerCase();
var value = type(this.value)
, expect = format('`%j` (%s) to @ be a %s', this.value, value, of);
return this.test(value === of, msg, expect);
});
/**
* Asserts if the given value is the correct type from a list of types.
* The same caveats regarding `typeof` apply as described in `a`, `an`.
*
* @param {String[]} ofs Acceptable types to check against
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('eitherOfType, oneOfType', function multitypecheck(ofs, msg) {
var value = type(this.value)
, expect = format('`%j` (%s) to @ be a %s', this.value, value, ofs.join(' or a '));
var test = false;
for (var i = 0; i < ofs.length; i++) {
if (ofs[i].toString().toLowerCase() === value) {
test = true;
break;
}
}
return this.test(test, msg, expect);
});
/**
* Asserts that the value is instanceof the given constructor.
*
* @param {Function} constructor Constructur the value should inherit from.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('instanceOf, instanceof, inherits, inherit', function of(constructor, msg) {
var expect = format('%f to @ be an instanceof %f', this.value, constructor);
return this.test(this.value instanceof constructor, msg, expect);
});
/**
* Assert that the value includes the given value.
*
* @param {Mixed} val Value to match.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('include, includes, contain, contains', function contain(val, msg) {
var includes = false
, of = type(this.value)
, expect = format('`%j` to @ include %j', this.value, val);
switch (of) {
case 'array':
for (var i = 0, length = this.value.length; i < length; i++) {
if (this._deep ? deep(this.value[i], val) : this.value[i] === val) {
includes = true;
break;
}
}
break;
case 'object':
if (val in this.value) {
includes = true;
}
break;
case 'string':
if (~this.value.indexOf(val)) {
includes = true;
}
break;
}
return this.test(includes === true, msg, expect);
});
/**
* Assert that the value is truthy.
*
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('ok, okay, truthy, truly', function ok(msg) {
var expect = format('`%j` to @ be truthy', this.value);
return this.test(Boolean(this.value), msg, expect);
});
/**
* Assert that the value is falsey.
*
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('falsely, falsey, falsy', function nope(msg) {
var expect = format('`%j` to @ be falsely', this.value);
return this.test(Boolean(this.value) === false, msg, expect);
});
/**
* Assert that the value is `true`.
*
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('true', function ok(msg) {
var expect = format('`%j` to @ equal (===) true', this.value);
return this.test(this.value === true, msg, expect);
});
/**
* Assert that the value is `true`.
*
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('false', function nope(msg) {
var expect = format('`%j` to @ equal (===) false', this.value);
return this.test(this.value === false, msg, expect);
});
/**
* Assert that the value exists.
*
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('exists, exist', function exists(msg) {
var expect = format('`%j` to @ exist', this.value);
return this.test(this.value != null, msg, expect);
});
/**
* Asserts that the value's length is the given value.
*
* @param {Number} value Size of the value.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('length, lengthOf, size', function length(value, msg) {
var actualValue = size(this.value);
var expect = format('`%j` to @ have a length of %d, found %d', this.value, value, actualValue);
return this.test(actualValue === +value, msg, expect);
});
/**
* Asserts that the value's length is 0 or doesn't contain any enumerable keys.
*
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('empty', function empty(msg) {
var expect = format('`%j` to @ be empty', this.value);
return this.test(size(this.value) === 0, msg, expect);
});
/**
* Assert that the value is greater than the specified value.
*
* @param {Number} value The greater than value.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('above, gt, greater, greaterThan', function above(value, msg) {
var amount = type(this.value) !== 'number' ? size(this.value) : this.value
, expect = format('%d to @ be greater than %d', amount, value);
return this.test(amount > value, msg, expect);
});
/**
* Assert that the value is equal or greater than the specified value.
*
* @param {Number} value The specified value.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('least, gte, atleast', function least(value, msg) {
var amount = type(this.value) !== 'number' ? size(this.value) : this.value
, expect = format('%d to @ be greater or equal to %d', amount, value);
return this.test(amount >= value, msg, expect);
});
/**
* Assert that the value starts with the given value.
*
* @param {String|Array} value String it should start with.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('start, starts, startsWith, startWith', function start(value, msg) {
var expect = format('`%j` to @ start with %j', this.value, value);
return this.test(0 === this.value.indexOf(value), msg, expect);
});
/**
* Assert that the value ends with the given value.
*
* @param {String} value String it should start with.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('end, ends, endsWith, endWith', function end(value, msg) {
var index = this.value.indexOf(value, this.value.length - value.length)
, expect = format('`%j` to @ end with %j', this.value, value);
return this.test(index >= 0, msg, expect);
});
/**
* Assert a floating point number is near the give value within the delta
* margin.
*
* @param {Number} value The specified value.
* @param {Number} delta Radius.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('closeTo, close, approximately, near', function close(value, delta, msg) {
var expect = format('`%j` to @ be close to %d ± %d', this.value, value, delta);
return this.test(Math.abs(this.value - value) <= delta, msg, expect);
});
/**
* Assert that the value is below the specified value.
*
* @param {Number} value The specified value.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('below, lt, less, lessThan', function below(value, msg) {
var amount = type(this.value) !== 'number' ? size(this.value) : this.value
, expect = format('%d to @ be less than %d', amount, value);
return this.test(amount < value, msg, expect);
});
/**
* Assert that the value is below or equal to the specified value.
*
* @param {Number} value The specified value.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('most, lte, atmost', function most(value, msg) {
var amount = type(this.value) !== 'number' ? size(this.value) : this.value
, expect = format('%d to @ be less or equal to %d', amount, value);
return this.test(amount <= value, msg, expect);
});
/**
* Assert that that value is within the given range.
*
* @param {Number} start Lower bound.
* @param {Number} finish Upper bound.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('within, between', function within(start, finish, msg) {
var amount = type(this.value) !== 'number' ? size(this.value) : this.value
, expect = format('%d to @ be greater or equal to %d and @ be less or equal to %d', amount, start, finish);
return this.test(amount >= start && amount <= finish, msg, expect);
});
/**
* Assert that the value has an own property with the given prop.
*
* @param {String} prop Property name.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('hasOwn, own, ownProperty, haveOwnProperty, property, owns, hasown', function has(prop, value, msg) {
var expect = format('`%j` @ to have own property %s', this.value, prop)
, tested = this.test(hasOwn.call(this.value, prop), msg, expect);
return arguments.length > 1
? this.clone(this.value[prop]).equals(value)
: tested;
});
/**
* Asserts that the value matches a regular expression.
*
* @param {RegExp} regex Regular expression to match against.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('match, matches', function test(regex, msg) {
if ('string' === typeof regex) regex = new RegExp(regex);
var expect = format('`%j` to @ match %j', this.value, regex);
return this.test(!!regex.test(this.value), msg, expect);
});
/**
* Assert that the value equals a given thing.
*
* @param {Mixed} thing Thing it should equal.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('equal, equals, eq, eqs, exactly', function equal(thing, msg) {
var expect = format('`%j` to @ equal (===) `%j`', this.value, thing);
if (!this._deep) return this.test(this.value === thing, msg, expect);
this.sliceStack++;
return this.eql(thing, msg);
});
/**
* Assert that the value **deeply** equals a given thing.
*
* @param {Mixed} thing Thing it should equal.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('eql, eqls', function eqls(thing, msg) {
var expect = format('`%j` to deeply equal `%j`', this.value, thing);
return this.test(deep(this.value, thing), msg, expect);
});
/**
* Assert that the value is either one of the given values.
*
* @param {Array} arrgs All the values it can match.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('either', function either(args, msg) {
var expect = '`%j` to equal either `%j` '
, i = args.length
, result = false
, values = [];
while (i-- || result) {
if (!this._deep) result = this.value === args[i];
else result = deep(this.value, args[i]);
if (result) break;
values.push(args[i]);
}
expect = format.apply(null, [expect + (new Array(values)).join('or `%j` ')].concat(values));
return this.test(result, msg, expect);
});
/**
* Assert if the given function throws.
*
* @param {Mixed} thing Thing it should equal.
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('throw, throws, fails, fail', function throws(thing, msg) {
try { this.value(); }
catch (e) {
var message = 'object' === typeof e ? e.message : e;
switch (type(thing)) {
case 'string': return this.clone(message).includes(thing, msg);
case 'regexp': return this.clone(message).matches(thing, msg);
case 'function': return this.clone(e).instanceOf(thing, msg);
case 'undefined': return this.test(true, msg, format('%f to @ throw', this.value));
default: return this.clone(e).equals(thing);
}
}
return this.test(false, msg, format('%f to @ throw', this.value));
});
/**
* Assert if the given value is finite.
*
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('isFinite, finite, finiteness', function finite(msg) {
var expect = format('`%j`s @ a is a finite number', this.value)
, result;
if (this._deep) {
result = Number.isFinite
? Number.isFinite(this.value)
: 'number' === type(this.value) && isFinite(this.value);
} else {
result = isFinite(this.value);
}
return this.test(result, msg, expect);
});
/**
* Assert if the given function is an ES6 generator.
*
* @param {String} msg Reason of failure.
* @returns {Assume}
* @api public
*/
Assume.add('generator', function generators(msg) {
var expect = format('%f to @ be a generator', this.value)
, result;
//
// Non standard function from Mozilla allows us to check if a function is
// a generator.
//
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/isGenerator
//
if ('function' === typeof this.value.isGenerator) {
result = this.value.isGenerator();
} else if ('generatorfunction' === type(this.value)) {
result = true;
} else {
result = 'function' === type(this.value) && this.value.toString().indexOf('function*') === 0;
}
return this.test(result, msg, expect);
});
/**
* Assert if the given thenable/async function results in a rejected/error state
*
* @param {String} msg Reason of failure.
* @api public
*/
Assume.add('rejected, rejects, throwAsync, throwsAsync, failAsync, failsAsync', function rejects(msg) {
var expectation = format('Thenable did @ end in a rejected state');
var value = typeof this.value == 'function' ? this.value() : this.value;
var self = this;
function test(success, resolveValue, resolve, reject) {
try {
self.test(success, msg, expectation);
resolve(resolveValue);
} catch (ex) {
reject(ex);
}
}
return {
then: function then(resolve, reject) {
value.then(function (s) {
test(false, s, resolve, reject);
}, function (r) {
test(true, r, resolve, reject);
});
}
};
});
/**
* Assert if the given thenable/async function completed and a result filled synchronously
*
* @param {String} msg Reason of failure
* @api public
*/
Assume.add('resolveSync, resolvesSync, resolvedSync, completeSync, completesSync, completedSync', function completedSync(msg) {
var expectation = format('Thenable did @ complete synchronously');
var value = typeof this.value == 'function' ? this.value() : this.value;
var self = this;
return {
then: function then(resolve, reject) {
var completed = false;
var resolveValue;
value.then(function (s) {
resolveValue = s;
completed = true;
}, function (r) {
resolveValue = r;
completed = true;
});
try {
self.test(completed, msg, expectation);
resolve(resolveValue);
} catch (ex) {
reject(ex);
}
}
};
});
//
// The following assertions require's v8's allow-natives-syntax flag to be
// enabled as this allows us to hook in to the more internal parts of the
// engine. The native syntax is wrapped in a try catch with a new Function
// construction so the rest of the code will execute when JavaScript engines do
// not understand the instructions.
//
(function v8() {
var states = 'void,yes,no,always,never,void,maybe'.split(',')
, detect;
if (!Assume.supports.native) detect = function optimized() { return 0; };
else detect = new Function('fn', 'args', 'selfie', [
'fn.apply(selfie, args);',
'%OptimizeFunctionOnNextCall(fn);',
'fn.apply(selfie, args);',
'return %GetOptimizationStatus(fn);'
].join('\n'));
/**
* Assert that a given function has reached a certain optimization level.
*
* @param {String} level Optimization level
* @param {Array} args Arguments for the function
* @param {Mixed} selfie This context for the function
* @param {String} msg Reason of failure
* @returns {Assume}
* @api public
*/
Assume.add('optimisation, optimization', function optimization(level, args, selfie, msg) {
var expect = format('%f to be optimized as %s', this.value, level)
, status = states[detect(this.value, args, selfie)];
return this.test(status === level, msg, expect);
});
/**
* Assert that the function is optimized.
*
* @param {String} msg Reason of failure
* @returns {Assume}
* @api public
*/
Assume.add('optimized, optimised', function optimized(msg) {
var expect = format('%f to be optimized', this.value)
, status = states[detect(this.value, [])];
return this.test(status === 'yes', msg, expect);
});
}());
/**
* Create a clone of the current assertion instance which has the same
* configuration but a different value.
*
* @param {Mixed} value The new value
* @returns {Assume}
* @api public
*/
Assume.add('clone', function clone(value) {
var configuration = {
stacktrace: this.stacktrace,
slice: this.sliceStack + 1,
diff: this.diff
};
for (var alias in Assume.flags) {
if (!hasOwn.call(Assume.flags, alias)) continue;
configuration[alias] = this[alias];
}
return new Assume(arguments.length ? value : this.value, configuration);
});
/**
* Validate the assertion.
*
* @param {Boolean} passed Didn't the test pass or fail.
* @param {String} msg Custom message provided by users.
* @param {Function} expectation Compiled expectation template
* @param {Number} slice The amount of stack traces we need to remove.
* @returns {Assume}
* @api public
*/
Assume.add('test', function test(passed, msg, expectation, slice) {
called++; // Needed for tracking the amount of executed assertions.
if (this._not) passed = !passed;
if (passed) return this;
msg = msg || 'Unknown assertation failure occured';
slice = slice || this.sliceStack;
if (expectation) msg += ', assumed ' + expectation(this._not);
var failure = new Error(msg)
, err = { message: failure.message, stack: '' };
if (this.stacktrace) {
err.stack = failure.stack || err.stack;
}
//
// Pre-scrub, it's possible that the error message is a multi line error
// message and that really messes up the slicing of the call stack, to prevent
// this from happening, we're just going to replace the error message that is
// on the stack with a single line as we use the `err.message` instead of the
// message that is in the stack anyways.
//
err.stack = err.stack.replace(err.message, 'assume-replaced-the-err-message');
//
// Clean up the stack by slicing off the parts that are pointless to most
// people. (Like where it enters this assertion library).
//
err.stack = err.stack.split('\n').slice(slice).join('\n') || err.stack;
err.stack = pruddy(err, {
read: function read(failing) {
if (!size(Assume.registry)) return;
return Assume.registry[failing.filename];
}
});
if ('function' !== typeof Object.create) {
if ('object' === typeof console && 'function' === typeof console.error) {
console.error(err.stack);
}
throw failure;
}
failure = Object.create(Error.prototype);
failure.message = err.message;
failure.stack = err.stack;
throw failure;
});
/**
* Plan for the amount of assertions that needed to run. This is great way to
* figure out if you have edge cases in your code which prevented an assertion or