forked from spadgos/tyrtle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tyrtle.js
1482 lines (1438 loc) · 46.4 KB
/
Tyrtle.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
/*!
* Tyrtle - A JavaScript Unit Testing Framework
*
* Copyright (c) 2011-2012 Nick Fisher
* Distributed under the terms of the LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
/*globals module, window */
(function () {
var Tyrtle, Module, Test, assert,
AssertionError, SkipMe,
PASS = 0,
FAIL = 1,
SKIP = 2,
extend,
defer,
noop,
each,
slice = Array.prototype.slice,
isArray,
isFunction,
isRegExp,
getKeys,
isEqual,
isDate,
getParam,
setParams,
root,
runningInNode,
unexecutedAssertions = 0, // the count of assertions created minus the number of assertions executed.
moduleAssertions = null, // the extra assertions added by an individual module
currentTestAssertions // a counter for the number of assertions run in an individual test
;
// Gets the global object, regardless of whether run as ES3, ES5 or ES5 Strict Mode.
root = (function () {
return this || (0 || eval)('this');
}());
runningInNode = typeof window === 'undefined';
//////////////////////////
// RUNTIME PARAMETERS //
//////////////////////////
//#JSCOVERAGE_IF 0
(function () {
var urlParams, loadParams;
loadParams = runningInNode
? function () {
// node parameters must be set up manually and passed to the Tyrtle constructor
// this is because a test harness may use its own command line parameters
urlParams = {};
}
: function () {
urlParams = {};
var query, vars, i, l, pair;
query = window.location.search.substring(1);
vars = query.split("&");
for (i = 0, l = vars.length; i < l; ++i) {
pair = vars[i].split("=");
urlParams[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
}
;
getParam = function (name) {
if (!urlParams) {
loadParams();
loadParams = null;
}
return urlParams.hasOwnProperty(name) ? urlParams[name] : null;
};
setParams = function (params) {
urlParams = params || {};
};
}());
//#JSCOVERAGE_ENDIF
extend = function (target, source) {
var i;
for (i in source) {
if (source.hasOwnProperty(i)) {
target[i] = source[i];
}
}
};
// defer
//#JSCOVERAGE_IF
if (!root.postMessage) {
/**
* The regular defer method using a 0ms setTimeout. In reality, this will be executed in 4-10ms.
*/
defer = function (fn) {
setTimeout(fn, 0);
};
} else {
/**
* The postMessage defer method which will get executed as soon as the call stack has cleared.
* Credit to David Baron: http://dbaron.org/log/20100309-faster-timeouts
*/
defer = (function () {
var timeouts = [], messageName = "zero-timeout-message", setZeroTimeout, handleMessage;
setZeroTimeout = function (fn) {
timeouts.push(fn);
root.postMessage(messageName, "*");
};
handleMessage = function (event) {
if (event.source === root && event.data === messageName) {
event.stopPropagation();
if (timeouts.length > 0) {
var fn = timeouts.shift();
fn();
}
}
};
root.addEventListener("message", handleMessage, true);
return function (func) {
setZeroTimeout(func);
};
}());
}
noop = function () {};
each = function (obj, iterator, context) {
if (obj !== null && typeof obj !== 'undefined') {
if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
obj.forEach(iterator, context);
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key, obj);
}
}
}
}
};
/**
* PhantomJS's Object.keys implementation is buggy. It gives the following results:
* window.hasOwnProperty('setTimeout') === true
* Object.keys(window).indexOf('setTimeout') === -1
* So, we're always falling back to the manual method
*/
// getKeys = Object.keys;
//#JSCOVERAGE_IF
if (!getKeys) {
getKeys = function (obj) {
/*jslint newcap : false */
if (obj !== Object(obj)) {
throw new TypeError('Invalid object');
}
/*jslint newcap : true */
var keys = [], key;
for (key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
keys[keys.length] = key;
}
}
return keys;
};
}
isRegExp = function (obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
isFunction = function(obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
};
/**
* This function is taken from Underscore.js 1.1.6
* (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
* http://documentcloud.github.com/underscore
*/
//#JSCOVERAGE_IF 0
isEqual = function (a, b) {
/*jslint eqeqeq: false */
var aKeys, atype, bKeys, btype, key;
// Check object identity.
if (a === b) {
return true;
}
// Different types?
atype = typeof(a);
btype = typeof(b);
if (atype !== btype) {
return false;
}
// One is falsy and the other truthy.
if ((!a && b) || (a && !b)) {
return false;
}
// One of them implements an isEqual()?
if (a.isEqual) {
return a.isEqual(b);
}
if (b.isEqual) {
return b.isEqual(a);
}
// Check dates' integer values.
if (isDate(a) && isDate(b)) {
return a.getTime() === b.getTime();
}
// Both are NaN?
if (a !== a && b !== b) {
return false;
}
// Compare regular expressions.
if (isRegExp(a) && isRegExp(b)) {
return a.source === b.source
&& a.global === b.global
&& a.ignoreCase === b.ignoreCase
&& a.multiline === b.multiline
;
}
// If a is not an object by this point, we can't handle it.
if (atype !== 'object') {
return false;
}
// Check for different array lengths before comparing contents.
if (a.length && (a.length !== b.length)) {
return false;
}
// Nothing else worked, deep compare the contents.
aKeys = getKeys(a);
bKeys = getKeys(b);
// Different object sizes?
if (aKeys.length !== bKeys.length) {
return false;
}
// Recursive comparison of contents.
for (key in a) {
if (!(key in b) || !isEqual(a[key], b[key])) {
return false;
}
}
/*jslint eqeqeq: true */
return true;
};
isDate = function (obj) {
return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
};
isArray = Array.isArray || function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
//#JSCOVERAGE_ENDIF
//
// Tyrtle
//
(function () {
var runModule, emptyRenderer;
Tyrtle = function (options) {
options = options || {};
this.modules = [];
this.callback = options.callback || noop;
this.modFilter = options.modFilter === false
? null
: (typeof options.modFilter === 'string'
? options.modFilter
: getParam('modFilter')
)
;
this.testFilter = options.testFilter === false
? null
: (typeof options.testFilter === 'string'
? options.testFilter
: getParam('testFilter')
)
;
};
emptyRenderer = {
beforeRun : noop,
beforeModule : noop,
beforeTest : noop,
afterTest : noop,
afterModule : noop,
afterRun : noop,
templateString : function (message) {
var args = slice.call(arguments, 1);
return message.replace(
/\{([1-9][0-9]*|0)\}/g,
function (str, p1) {
var v = args[p1];
return (v === null
? "NULL"
: (typeof v === "undefined"
? "UNDEFINED"
: (v.toString ? v.toString() : String(v))
)
);
}
);
}
};
// Static methods and properties
extend(Tyrtle, {
PASS : PASS,
FAIL : FAIL,
SKIP : SKIP,
renderer : emptyRenderer,
/**
* Get the current renderer
* @return {Object}
*/
getRenderer : function () {
return this.renderer;
},
/**
* Set the current renderer. This is a static method because the renderer is global to all instances of
* Tyrtle. If one of the renderer properties is not specified, then the corresponding property from
* `emptyRenderer` is used.
* @param {Object} renderer
*/
setRenderer : function (renderer) {
each(emptyRenderer, function (val, key) {
if (!(key in renderer)) {
renderer[key] = val;
}
}, this);
this.renderer = renderer;
},
/**
* Set the parameters which Tyrtle uses for default values. In the browser, Tyrtle will automatically use
* the parameters specified in the url.
*/
setParams : setParams,
/**
* Static method used when you do not have an instance of Tyrtle yet. Modules returned by this function must
* still be added to an instance of Tyrtle using Tyrtle.module()
*
* @param {String} name The name of the module
* @param {Function} body The body function of the module
*
* @return {Module}
*/
module : function (name, body) {
return new Module(name, body);
}
});
// instance methods and properties
extend(Tyrtle.prototype, {
passes : 0,
fails : 0,
errors : 0,
skips : 0,
startTime: 0,
runTime: -1,
////
/**
* Create a new test module and add it to this instance of Tyrtle
*
* @param {String} name The name for this module
* @param {Function} body The body of the module which can define tests, local variables and test helpers,
* like before, after, beforeAll and afterAll
*/
module : function (name, body) {
var m;
if (arguments.length === 1 && name instanceof Module) {
m = name;
} else if (arguments.length === 1 && typeof name === 'object') {
each(name, function (body, name) {
this.module(name, body);
}, this);
return;
} else {
m = new Module(name, body);
}
m.tyrtle = this;
this.modules.push(m);
},
/**
* Execute the test suite.
*/
run : function () {
var runNext,
i = -1,
l = this.modules.length,
tyrtle = this
;
this.startTime = +(new Date());
Tyrtle.renderer.beforeRun(this);
runNext = function () {
var mod;
++i;
if (i === l) {
tyrtle.runTime = +(new Date()) - tyrtle.startTime;
Tyrtle.renderer.afterRun(tyrtle);
tyrtle.callback();
} else {
mod = tyrtle.modules[i];
if (tyrtle.modFilter && mod.name !== tyrtle.modFilter) {
runNext();
} else {
runModule(mod, tyrtle, function () {
each(['passes', 'fails', 'errors', 'skips'], function (key) {
tyrtle[key] += mod[key];
});
defer(runNext);
});
}
}
};
runNext();
}
});
runModule = function (mod, tyrtle, callback) {
Tyrtle.renderer.beforeModule(mod, tyrtle);
mod.run(function () {
Tyrtle.renderer.afterModule(mod, tyrtle);
callback();
});
};
}());
//
// Module
//
(function () {
var addHelper, runHelper, applyAssertions, cleanUpAssertions;
/**
* A testing module. Represents a logical grouping of tests. A Module can have custom **helpers** to assist in
* setting up and cleaning up the tests, as well as custom assertions which streamline writing the tests.
*
* @class
* @param {String} name The name of this module
* @param {Function} body The body of this function.
*/
Module = function (name, body) {
if (!body && isFunction(name)) {
throw new Error("Module instantiated without a name.");
}
this.name = name;
this.tests = [];
this.helpers = {};
this.amdName = null;
body.call(this);
};
addHelper = function (name, fn) {
if (!this.helpers[name]) {
this.helpers[name] = [];
}
this.helpers[name].push(fn);
};
runHelper = function (helpers, callback, catchBlock) {
if (helpers && helpers.length) {
var helper = helpers[0];
try {
if (helper.length) {
helper(function () {
runHelper(helpers.slice(1), callback, catchBlock);
});
} else {
helper();
runHelper(helpers.slice(1), callback, catchBlock);
}
} catch (e) {
catchBlock(e);
}
} else {
callback();
}
};
applyAssertions = function (fnMap) {
moduleAssertions = fnMap;
};
cleanUpAssertions = function () {
moduleAssertions = null;
};
extend(Module.prototype, {
tests : null, // array of tests
tyrtle : null, // reference to the owner Tyrtle instance
helpers : null, // object containing the (before|after)(All)? functions
extraAssertions : null, // object holding custom assertions. Only populated if required.
skipAll: false, // whether all tests in this module should be skipped
skipMessage: null, // The skip message for all tests if they should all be skipped.
passes : 0, // }
fails : 0, // } counts of the test results
skips : 0, // }
errors : 0, // }
//////////////////////////
/**
* Create a new Test and add it to this Module
* @param {String} name A name for this test.
* @param {Number=} expectedAssertions The number of assertions this test is expected to run. Optional.
* @param {Function} bodyFn The body function for this test.
* @param {Function=} assertionsFn If writing an asynchronous test, this is the function where assertions
* can be executed. For synchronous tests, *do not supply this parameter*.
* @return {Test} The newly created test.
*/
test : function (name, expectedAssertions, bodyFn, assertionsFn) {
var t = new Test(name, expectedAssertions, bodyFn, assertionsFn);
this.tests.push(t);
return t;
},
/**
* Add a `before` helper which is executed *before each test* is started.
* @param {Function} fn The body of the helper
*/
before : function (fn) {
addHelper.call(this, 'before', fn);
},
/**
* Add an `after` helper which is executed *after each test* has finished.
* @param {Function} fn The body of the helper
*/
after : function (fn) {
addHelper.call(this, 'after', fn);
},
/**
* Add a `beforeAll` helper which is executed *before any tests* have started.
* @param {Function} fn The body of the helper
*/
beforeAll : function (fn) {
addHelper.call(this, 'beforeAll', fn);
},
/**
* Add an `afterAll` helper which is executed *after all tests* have finished.
* @param {Function} fn The body of the helper
*/
afterAll : function (fn) {
addHelper.call(this, 'afterAll', fn);
},
/**
* Add per-module (local) assertions to this module. These *may override built-in assertions*. Assertions
* defined here are not accessible or visible to any other modules.
*
* The assertion body should return `true` or `undefined` to indicate a pass. A string will be used as the
* default error message, and an array allows the assertion to add additional arguments to be substituted
* into the error message.
*
* @example
* this.addAssertions({
* bigNumber : function (subject) {
* // returns true or false. No error message for failing assertions.
* return subject > 9000;
* },
* answer : function (subject) {
* // returns true or a string. `subject` will be substituted for "{0}"
* return subject === 42 || "The supplied value {0} is not the answer to life, & etc.";
* }
* biggerThan : function (subject, expected) {
* // returns true or an array. `expected - subject` is added to the substitution list.
* // assert(5).is.biggerThan(7)(); --> "5 is not bigger than 7. It is off by 2"
* return subject > expected || ["{0} is not bigger than {1}. It is off by {2}", expected - subject];
* }
* });
*
* @param {Object} fnMap A map of {String} AssertionName => {Function} AssertionBody.
*/
addAssertions : function (fnMap) {
if (!this.extraAssertions) {
this.extraAssertions = fnMap;
} else {
each(fnMap, function (fn, name) {
this.extraAssertions[name] = fn;
}, this);
}
},
setAMDName : function (amdName, index) {
this.amdName = amdName + (typeof index === 'number' ? ':' + index : '');
},
skipIf: function (condition, message) {
this.skipAll = !!condition;
this.skipMessage = condition ? message : null;
},
/**
* @protected
*/
run : function (callback) {
var runNext,
i = -1,
l = this.tests.length,
j, jl,
mod = this
;
runNext = function () {
var test;
if (++i >= l) { // we've done all the tests, break the loop.
cleanUpAssertions();
runHelper(mod.helpers.afterAll, callback, function (e) {
test = mod.tests[mod.tests.length - 1];
if (test) {
switch (test.status) {
case PASS :
--mod.passes;
break;
case SKIP :
--mod.skips;
break;
case FAIL :
--mod.fails;
}
++mod.fails;
if (!test.error) {
++mod.errors;
test.error = e;
}
}
callback();
});
} else {
test = mod.tests[i];
if (mod.tyrtle.testFilter && test.name !== mod.tyrtle.testFilter) {
runNext();
} else {
mod.runTest(test, function () {
switch (test.status) {
case PASS :
++mod.passes;
break;
case FAIL :
++mod.fails;
if (test.error) {
++mod.errors;
}
break;
case SKIP :
++mod.skips;
break;
}
Tyrtle.renderer.afterTest(test, mod, mod.tyrtle);
defer(runNext);
});
}
}
};
if (this.skipAll) {
for (j = 0, jl = mod.tests.length; j < jl; ++j) {
mod.tests[j].status = SKIP;
mod.tests[j].statusMessage = "Skipped" + (this.skipMessage ? " because " + this.skipMessage : "");
}
callback();
} else {
applyAssertions(this.extraAssertions);
runHelper(this.helpers.beforeAll, runNext, function (e) {
// mark all the tests as failed.
for (j = 0, jl = mod.tests.length; j < jl; ++j) {
Tyrtle.renderer.beforeTest(mod.tests[j], mod, mod.tyrtle);
mod.tests[j].status = FAIL;
mod.tests[j].error = e;
Tyrtle.renderer.afterTest(mod.tests[j], mod, mod.tyrtle);
}
// set the group statistics
mod.passes = mod.skips = 0;
mod.fails = mod.errors = jl;
i = l; // <-- so the 'runNext' function thinks it's done all the tests & will call the afterAll.
runNext();
});
}
},
/**
* @protected
*/
runTest : function (test, callback) {
var m = this, t = this.tyrtle, go, done;
Tyrtle.renderer.beforeTest(test, m, t);
go = function () {
test.run(done);
};
done = function () {
runHelper(m.helpers.after, callback, function (e) {
test.status = FAIL;
if (!test.error) {
test.statusMessage = "Error in the after helper. " + e.message;
test.error = e;
}
callback();
});
};
runHelper(this.helpers.before, go, function (e) {
test.status = FAIL;
test.statusMessage = "Error in the before helper.";
test.error = e;
done();
});
},
/**
* @protected
*/
rerunTest : function (test, tyrtle, callback) {
var mod = this, run, complete;
switch (test.status) {
case PASS :
--this.passes;
--tyrtle.passes;
break;
case FAIL :
--this.fails;
--tyrtle.fails;
if (test.error) {
delete test.error;
--this.errors;
--tyrtle.errors;
}
break;
case SKIP :
--this.skips;
--tyrtle.skips;
}
run = function () {
applyAssertions(mod.extraAssertions);
mod.runTest(test, function () {
var aftersDone = function () {
switch (test.status) {
case PASS :
++mod.passes;
++tyrtle.passes;
break;
case FAIL :
++mod.fails;
++tyrtle.fails;
if (test.error) {
++mod.errors;
++tyrtle.errors;
}
break;
case SKIP :
++mod.skips;
++tyrtle.skips;
}
complete();
};
runHelper(mod.helpers.afterAll, aftersDone, function (e) {
test.status = FAIL;
test.error = e;
test.statusMessage = "Error in the afterAll helper";
aftersDone();
});
});
};
complete = function () {
Tyrtle.renderer.afterTest(test, mod, tyrtle);
Tyrtle.renderer.afterModule(mod, tyrtle);
Tyrtle.renderer.afterRun(tyrtle);
cleanUpAssertions();
if (callback) {
callback();
}
};
runHelper(this.helpers.beforeAll, run, function (e) {
test.status = FAIL;
test.error = e;
test.statusMessage = "Error in the beforeAll helper";
++mod.fails;
++tyrtle.fails;
++mod.errors;
++tyrtle.errors;
complete();
});
}
});
}());
//
// Test
//
(function () {
var runAssertions;
Test = function (name, expectedAssertions, body, asyncFn) {
if (typeof expectedAssertions !== 'number') {
asyncFn = body;
body = expectedAssertions;
} else {
this.expect(expectedAssertions);
}
if (typeof name !== 'string') {
throw new Error('Test instantiated without a name.');
}
this.name = name;
this.body = body;
this.asyncFn = asyncFn;
};
extend(Test.prototype, {
/** @type {Status} one of PASS, FAIL, SKIP or null */
status : null,
statusMessage: '',
runTime : -1,
error : null, // If an error (not an AssertionError is thrown it is stored here)
exception : null, // Any thrown error is stored here (including AssertionErrors)
asyncFn : null,
expectedAssertions : -1,
assertionCount: 0,
///////////////
/**
* Skip this test.
* @param {String=} reason A reason why this test is being skipped.
*/
skip : function (reason) {
throw new SkipMe(reason);
},
/**
* Conditionally skip this test.
* @example
* this.skipIf(typeof window === 'undefined', "Test only applies to browsers")
* @param {Boolean} condition
* @param {String=} reason A reason why this test is being skipped.
*/
skipIf : function (condition, reason) {
if (condition) {
this.skip(reason);
}
},
/**
* Expect an exact number of assertions that should be run by this test.
* @param {Number} numAssertions
*/
expect : function (numAssertions) {
this.expectedAssertions = numAssertions;
},
/**
* @protected
*/
run : function (callback) {
var start, success, handleError, oldGlobals,
callbackExecuted = false, test = this;
success = function () {
test.runTime = new Date() - start;
test.status = PASS;
test.statusMessage = 'Passed';
callback(test);
};
handleError = function (e) {
var message = (e && e.message) || String(e);
if (e instanceof SkipMe) {
test.status = SKIP;
test.statusMessage = "Skipped" + (e.message ? " because " + e.message : "");
} else {
test.status = FAIL;
test.statusMessage = "Failed" + (message ? ": " + message : "");
test.exception = e;
if (!(e instanceof AssertionError)) {
test.error = e;
}
}
callback(test);
};
try {
oldGlobals = getKeys(root);
start = new Date();
if (this.asyncFn) {
// actually executes the asyncTest here.
this.body(function (variables) {
if (!callbackExecuted) {
callbackExecuted = true;
runAssertions(test, {
assertions: function () {
test.asyncFn.call(variables || {}, assert);
},
success: success,
failure: handleError,
oldGlobals: oldGlobals
});
}
});
} else {
runAssertions(test, {
assertions: function () {
test.body(assert);
},
success: success,
failure: handleError,
oldGlobals: oldGlobals
});
}
} catch (e) {
handleError(e);
}
}
});
runAssertions = function (test, options) {
var assertionsFn = options.assertions,
successFn = options.success,
oldGlobals = options.oldGlobals,
onError = options.failure,
originalUnexecutedAssertions;
try {
// this is incremented by the `since` function
currentTestAssertions = 0;
// remember how many unexecuted assertion there were at the start
originalUnexecutedAssertions = unexecutedAssertions;
assertionsFn();
if (test.expectedAssertions !== -1) {
assert
.that(currentTestAssertions)
.is(test.expectedAssertions)
.since("Incorrect number of assertions made by this test.");
}
test.assertionCount = currentTestAssertions;
// check that no assertions were left unexecuted.
assert
.that(unexecutedAssertions - originalUnexecutedAssertions)
.is(0)
.since("This test defines assertions which are never executed");
each(getKeys(root), function (newGlobal) {
if (oldGlobals.indexOf(newGlobal) < 0) {
throw new AssertionError('Test introduced new global variable "{0}"', [newGlobal]);
}
});
successFn();
} catch (ee) {
onError(ee);
}
};
}());
/**
* AssertionError exception class. An instance of this class is thrown whenever an assertion fails.
* @class
* @param {String} msg A message for the failed assertion, this is defined by the assertion itself.
* @param {Array} args Arguments passed to the assertion, these are used to substitute into the error message.
* @param {String} userMessage An error message as defined by the user.
*/
AssertionError = function (msg, args, userMessage) {
var newError = new Error(),
re_stack = /([^(\s]+\.js):(\d+):(\d+)/g
;
this.message = Tyrtle.renderer.templateString.apply(
Tyrtle.renderer,
[(msg || "") + (msg && userMessage ? ": " : "") + (userMessage || "")].concat(args)
);
if (newError.stack) { // TODO: cross-browser implementation
this.stack = [];
each(newError.stack.match(re_stack), function (str) {
re_stack.lastIndex = 0;
var parts = re_stack.exec(str);
if (parts) {
this.stack.push(parts.slice(1));
}
}, this);
this.stack = this.stack.slice(3);
}
};
AssertionError.prototype.name = "AssertionError";
/**
* SkipMe exception. This is thrown by tests when `this.skip()` or `this.skipIf(true)` is called.
* @class
* @param {String} reason A reason for this test to be skipped.
*/
SkipMe = function (reason) {
this.message = reason;
};
SkipMe.prototype.name = 'SkipMe';
//////////////////
// Assertions //
//////////////////
(function () {
var assertions,
build,
invert,
handleAssertionResult,
internalAssertionCount = 0,
bodies;
bodies = {
ok: function (a) {
return !!a;
},
ofType: function (a, e) {
var type = typeof a;
//#JSCOVERAGE_IF typeof /a/ === 'function'
// webkit (incorrectly?) reports regexes as functions. Normalize this to 'object'.
if (type === 'function' && a.constructor === RegExp) {
type = 'object';
}
//#JSCOVERAGE_ENDIF
switch (e.toLowerCase()) {
case 'array' :
return isArray(a);
case 'date' :
return isDate(a);
case 'regexp' :
return isRegExp(a);
default :
return type === e;
}
},
matches: function (a, m) {
return m.test(a);