-
Notifications
You must be signed in to change notification settings - Fork 2
/
jdoctest.js
1539 lines (1348 loc) · 47 KB
/
jdoctest.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
/**
jDoctest
~~~~~~~~
Tests interactive JavaScript examples such as Python's doctest module.
Links
`````
* `documentation`_
* `development version`_
.. _documentation:
http://lunant.github.com/jdoctest
.. _development version:
http://github.com/lunant/jdoctest/zipball/master#egg=jdoctest-dev
*/
this.jDoctest = (function( window, $ ) { var meta = {
NAME: "jDoctest",
VERSION: "0.0.10",
AUTHORS: ["Heungsub Lee <[email protected]>",
"Kijun Seo <[email protected]>"],
URL: "http://jdoctest.lunant.org/",
GITHUB: "http://github.com/lunant/jdoctest"
/** jDoctest has to have meta data.
>>> jDoctest.NAME;
'jDoctest'
>>> jDoctest.VERSION !== undefined;
true
>>> $.isArray( jDoctest.AUTHORS );
true
*/
};
// Checks dependencies
if ( !$ ) {
throw new ReferenceError( "jDoctest needs jQuery framework" );
}
/***********************************************************************
* jDoctest
***********************************************************************/
var jDoctest = j = function( examples, name, source, fileName, lineNo ) {
/**class:jDoctest( examples[, name[, source[, fileName[, lineNo ] ] ] )
A collaction of examples.
>>> new jDoctest([
... new jDoctest.Example( "1;" ),
... new jDoctest.Example( "1;" ),
... new jDoctest.Example( "2;", "2" )
... ]);
<jDoctest (3 examples)>
>>> new jDoctest([ new jDoctest.Example( "1;" ) ]);
<jDoctest (1 example)>
It could have the identity. An identity is useful for debugging.
>>> new jDoctest([], "lykit", "", "lykit.js" );
<jDoctest lykit from lykit.js:1 (no examples)>
:param examples: the array of :class:`jDoctest.Example`
:param name: the name of the doctest
:param source: the source code of the doctest
:param fileName: the file name which contains the doctest
:param lineNo: the starting line number of the docstest
*/
this.examples = examples;
this.name = name;
this.source = source;
this.fileName = fileName;
this.lineNo = parseInt( lineNo || 1 );
};
j.prototype = {
toString: function() {
var examples, name = "", from = "";
switch ( this.examples.length ) {
case 0:
examples = "no examples";
break;
case 1:
examples = "1 example";
break;
default:
examples = this.examples.length + " examples";
}
if ( this.name ) {
name = " " + this.name;
}
if ( this.fileName ) {
from = " from " + this.fileName;
if ( this.lineNo ) {
from += ":" + this.lineNo;
}
}
return "<jDoctest" + name + from + " (" + examples + ")>";
}
};
// Exports meta data
$.extend( j, meta );
/***********************************************************************
* Exceptions
***********************************************************************/
j.errors = {
StopRunning: function() {
/**class:jDoctest.errors.StopRunning()
This exception will stop the jDoctest running process.
*/
this.name = "StopRunning";
this.message = "The running process has to stop";
}
};
j.errors.StopRunning.prototype = new Error();
/***********************************************************************
* Front-end
***********************************************************************/
j.testSource = function( fileName, options ) {
/**:jDoctest.testSource( fileName[, options ] )
Tests a JavaScript source file::
jDoctest.testSource( "source-which-contains-docstrings.js" );
The source file should contain some docstrings. A docstring is a
multiline-comment which starts with ``/**`` or a specified doc-prefix.
:param fileName: the file name
:param options: the same as :class:`jDoctest.getMaterials`'s
*/
var materials = this.getMaterials( options ),
parser = materials.parser,
runner = materials.runner;
$.get( fileName, function( src ) {
var doctests = parser.getDoctests( src, fileName );
if ( !options || !options.alreadyLoaded ) {
window.eval.call( window, src );
}
for ( var i = 0; i < doctests.length; i++ ) {
runner.run( doctests[ i ] );
}
}, "text" );
return runner.result;
};
j.testFile = function( fileName, options ) {
/**:jDoctest.testFile( fileName[, options ] )
Load a file and tests its content as a docstring::
jDoctest.testFile( "a-docstring.txt" );
The content of the file is a docstring. :class:`jDoctest.Parser` finds
only examples(not docstrings).
:param fileName: the file name
:param options: the same as :class:`jDoctest.getMaterials`'s
*/
var materials = this.getMaterials( options ),
parser = materials.parser,
runner = materials.runner;
$.get( fileName, function( src ) {
var doctest = new jDoctest( parser.getExamples( src ), src, fileName );
runner.run( doctest );
}, "text" );
return runner.result;
};
j.getMaterials = function( options ) {
/**:jDoctest.getMaterials( options )
Returns a :class:`jDoctest.Parser` and a :class:`jDoctest.Runner` from
``options``.
>>> var pr = jDoctest.getMaterials({
... verbose: true,
... symbols: {
... prompt: "$",
... continued: ">"
... }
... });
>>> var parser = pr.parser;
>>> var runner = pr.runner;
>>> parser.symbols.prompt;
'$'
>>> parser.symbols.continued;
'>'
>>> runner.options.verbose;
true
:param options: :class:`jDoctest.Runner`'s ``options`` parameter. But it
also contains ``symbols`` key for
:class:`jDoctest.Parser`'s ``symbols`` parameter.
*/
options = $.extend( true, {
verbose: false,
symbols: undefined,
onComplete: undefined
}, options );
var result = {},
symbols = options.symbols,
Runner;
delete options[ "symbols" ];
return {
parser: new j.Parser( symbols ),
runner: new j.Runner( result, options )
};
};
j.repr = function( val ) {
/**:jDoctest.repr( val )
Represents a value.
>>> jDoctest.repr( undefined );
>>> jDoctest.repr( [] );
'[]'
>>> jDoctest.repr( [1, 2, 3] );
'[1, 2, 3]'
>>> jDoctest.repr( "Hello, world!" );
'\'Hello, world!\''
>>> jDoctest.repr( "It's my world!" );
'\'It\\\'s my world!\''
>>> jDoctest.repr( ["It's my world!"] );
'[\'It\\\'s my world!\']'
>>> jDoctest.repr( jDoctest.flags.SKIP );
'<jDoctest.flags.SKIP>'
>>> print( jDoctest.repr( "\n\n\n" ) );
'\n\n\n'
:param val: the value
*/
if ( val === undefined ) {
return val;
} else if ( $.isArray( val ) ) {
var reprs = [];
for ( var i = 0; i < val.length; i++ ) {
reprs.push( j.repr( val[ i ] ) );
}
return "[" + reprs.join( ", " ) + "]";
} else if ( typeof val === "string" ) {
val = val.replace( /('|\\)/g, "\\$1" );
val = val.replace( /\n/g, "\\n" );
val = val.replace( /\r/g, "\\r" );
return "'" + val + "'";
}
return String( val );
};
j.blankLineMarker = "<BLANKLINE>";
/***********************************************************************
* Utilities
***********************************************************************/
var _ = {
ffff: "\uffff",
__: " ",
indent: function( indent, text ) {
/**:jDoctest._indent( indent, text )
Adds an indent to each lines.
>>> jDoctest._indent( "abc" );
' abc'
>>> jDoctest._indent( " ", "abc" );
' abc'
>>> print( jDoctest._indent( " ", "abc\ndef" ) );
abc
def
:param indent: a indentation string
:param text: a text which is been indented
*/
if ( text === undefined ) {
text = indent;
indent = _.__;
}
return text.replace( /^/mg, indent );
},
outdent: function( indent, text ) {
/**:jDoctest._outindent( indent, text )
Removes an indent from each lines.
:param indent: a removing indentation string
:param text: a text which is been outdented
*/
indent = new RegExp( "^" + indent, "mg" );
return text.replace( indent, "" );
},
linearize: function( text ) {
/**:jDoctest._linearize( text )
Makes a multiline text to the linear text.
>>> /\n/.exec( jDoctest._linearize( "ab\ncd" ) );
null
:param text: a text
*/
return text.replace( /\n/g, _.ffff );
},
unlinearize: function( line ) {
/**:jDoctest._unlinearize( text )
The inverse function of :func:`jDoctest._linearize`.
>>> /\n/.exec( jDoctest._unlinearize(
... jDoctest._linearize( "ab\ncd" )
... ) ) !== null;
true
:param text: a text
*/
return line.replace( new RegExp( _.ffff, "g" ), "\n" );
},
escapeRegExp: function( text ) {
/**:jDoctest._escapeRegExp( text )
Escapes for the regular expression.
>>> print( jDoctest._escapeRegExp( "/.*+?|" ) );
\/\.\*\+\?\|
:param text: a text
*/
var specials = [
"/", ".", "*", "+", "?", "|", "$",
"(", ")", "[", "]", "{", "}", "\\"
],
r = new RegExp( "(\\" + specials.join( "|\\" ) + ")", "g" );
return text.replace( r, "\\$1" );
},
mockConsole: {
/**:jDoctest._mockConsole
It has methods named ``log``, ``warn``, ``error``, and ``dir``. All
methods do not anything. jDoctest uses it instead of ``window.console``
in IE6 or Firefox without FireBug. Because ``window.console`` object
is not available in there.
>>> jDoctest._mockConsole.log === jDoctest._mockConsole.warn;
true
>>> jDoctest._mockConsole.log === jDoctest._mockConsole.error;
true
>>> jDoctest._mockConsole.log === jDoctest._mockConsole.dir;
true
>>> !!/\{\s*\}/.exec( String( jDoctest._mockConsole.log ) );
true
>>> jDoctest.Runner.prototype.options.console !== undefined;
true
*/
toString: function() {
return "<jDoctest._mockConsole>";
}
}
};
// Use the console locally. If the console is not avaliable, use the mock
// console.
var console, empty = function() {};
_.mockConsole.log = _.mockConsole.warn = empty;
_.mockConsole.error = _.mockConsole.dir = empty;
if ( window.console === undefined ) {
console = _.mockConsole;
} else {
console = window.console;
}
// Exports utilities
for ( var meth in _ ) {
j[ "_" + meth ] = _[ meth ];
}
/***********************************************************************
* Parser
***********************************************************************/
j.Parser = function( symbols ) {
/**class:jDoctest.Parser( symbols )
A parser to catch docstrings and interactive examples.
You could specify doc-prefix or doc-suffix or prompt symbols using
``symbols`` argument:
>>> var myParser = new jDoctest.Parser({
... docPrefix: "/*+",
... docSuffix: "+*" + "/"
... });
``myParser`` has differant symbols. It executes like:
>>> var src = "this is not a docstring.\n" +
... "/*+ this is a docstring +*" + "/\n" +
... "/** this is not a docstring *" + "/\n" +
... "/** this is not a docstring also *" + "/";
>>> var doctests = myParser.getDoctests( src );
>>> doctests.length;
1
:param symbols: the parsing symbols
*/
this.symbols = $.extend( {}, this.symbols, symbols );
this.docStringRegex = new RegExp([
/*
(?:^|\uffff) # start of a line
(\s*) # indent
\/\*\* # docPrefix
(?:
([^\uffff*:]*) # directive
\:\s*
([^\uffff]+) # name
| [^*]
)
(.*?)
\*\/ # docSuffix
*/
"(?:^|" + _.ffff + ")(\\s*)",
_.escapeRegExp( this.symbols.docPrefix ),
"(?:([^" + _.ffff + "*:]*)\\:\\s*([^" + _.ffff + "]+)|[^*])(.*?)",
_.escapeRegExp( this.symbols.docSuffix )
].join( "" ), "gm" );
this.interactionRegex = new RegExp([
//^\s*(>>>.+)(?:\n^\s*(\.\.\..+)$)*
"^\\s*(",
_.escapeRegExp( this.symbols.prompt ),
".+)(?:\\n^\\s*(",
_.escapeRegExp( this.symbols.continued ),
".+)$)*"
].join( "" ), "gm" );
};
j.Parser.prototype = {
symbols: {
docPrefix: "/**",
docSuffix: "*/",
directiveSuffix: ":",
prompt: ">>>",
continued: "..."
},
getExamples: function( docString, lineNo ) {
/**:jDoctest.Parser.prototype.getExamples( docString )
Returns :class:`jDoctest.Example`s from a docstring.
>>> var src = "asdfasdfsdf\n" +
... "sadfasdf\n" +
... "\n" +
... " $ asfsdf;\n" +
... " > 12312;\n" +
... " > function() {\n" +
... " > return '123123';\n" +
... " > }\n" +
... " 123123\n" +
... " $ gggggggg;\n" +
... " 213123\n";
>>> var parser = new jDoctest.Parser({
... prompt: "$",
... continued: ">"
... });
>>> var examples = parser.getExamples( src );
>>> examples.length;
2
>>> print( examples[ 0 ].source );
asfsdf;
12312;
function() {
return '123123';
}
>>> examples[ 0 ].want;
'123123'
>>> examples[ 1 ].source;
'gggggggg;'
>>> examples[ 1 ].want;
'213123'
*/
lineNo = parseInt( lineNo || 1 );
var relLineNo,
line,
docLines = docString.split( "\n" ),
examples = [],
example = {
source: [],
want: []
},
indent,
e = _.escapeRegExp,
R = RegExp,
promptRegex = new R( "^(\\s*)" + e( this.symbols.prompt + " " ) ),
continuedRegex,
wantRegex,
blankRegex = /^\s*$/,
match,
is = {
source: false,
want: false
};
function saveExample( relLineNo ) {
var source, want, exam;
source = example.source.join( "\n" );
if ( example.want.length ) {
want = example.want.join( "\n" );
} else {
want = undefined;
}
exam = new j.Example( source, want, lineNo + relLineNo );
examples.push( exam );
is.source = is.want = false;
example.source = [];
example.want = [];
}
for ( var i = 0; i < docLines.length; i++ ) {
line = docLines[ i ];
if ( match = promptRegex.exec( line ) ) {
// Handles a line which starts with ``>>> ``
if ( is.source || is.want ) {
saveExample( relLineNo );
}
is.source = true;
relLineNo = i;
indent = match[ 1 ];
continuedRegex = new R(
"^" + e( indent + this.symbols.continued + " " )
);
wantRegex = new R( "^" + e( indent ) + "(.+)$" );
line = line.replace( promptRegex, "" );
} else if ( is.source && continuedRegex.exec( line ) ) {
// Handles a line which starts with ``... ``
line = line.replace( continuedRegex, "" );
} else if ( is.source || is.want ) {
if ( match = wantRegex.exec( line ) ) {
// Handles an output
is.want = true;
is.source = false;
line = match[ 1 ];
} else if ( blankRegex.exec( line ) ) {
// Handles a blank line
saveExample( relLineNo );
}
}
if ( is.source ) {
example.source.push( line );
} else if ( is.want ) {
example.want.push( line );
}
}
if ( is.source || is.want ) {
saveExample( relLineNo );
}
return examples;
},
getDoctests: function( source, fileName ) {
/**:jDoctest.Parser.prototype.getDoctests( source )
Parses a JavaScript source and returns docstring list.
>>> var parser = new jDoctest.Parser({
... docPrefix: "/*+",
... docSuffix: "+*" + "/"
... });
>>> var doctests = parser.getDoctests(
... "/*+ Hello, world! +*" + "/"
... );
>>> doctests.length;
1
>>> doctests[ 0 ];
<jDoctest (no examples)>
*/
var doctests = [],
doctest,
docStrings = [],
docString,
docLines,
examples,
match,
indent,
name,
l;
// Find docstrings
source = _.linearize( source );
while ( match = this.docStringRegex.exec( source ) ) {
docString = _.outdent( match[ 1 ], _.unlinearize( match[ 4 ] ) );
l = source.slice( 0, match.index ).split( _.ffff ).length + 1;
docStrings[ l ] = [ match[ 3 ], docString ];
}
// Make :class:`jDoctest` instances
for ( l in docStrings ) {
name = docStrings[ l ][ 0 ];
docString = docStrings[ l ][ 1 ];
examples = this.getExamples( docString, l );
doctest = new jDoctest( examples, name, docString, fileName, l );
doctests.push( doctest );
}
return doctests;
}
};
/***********************************************************************
* Example
***********************************************************************/
j.Example = function( source, want, lineNo ) {
/**class:jDoctest.Example( source, want[, lineNo ] )
A JavaScript example.
>>> var exam = new jDoctest.Example( "1 + 1;", "2" );
>>> exam;
<jDoctest.Example>
>>> exam.source;
'1 + 1;'
>>> exam.want;
'2'
>>> exam.flags;
[]
>>> var src = "throw new Error(); //doctest: +SKIP";
>>> var flagedExam = new jDoctest.Example( src, undefined );
>>> flagedExam.flags;
[<jDoctest.flags.SKIP>]
*/
this.source = source;
this.want = want;
this.lineNo = lineNo;
var flags = this._findFlags( source );
this.flags = flags.positive;
this.negetiveFlags = flags.negative;
};
j.Example.prototype = {
_OPTION_DIRECTIVE: /\/\/\s*doctest:\s*([^\n\'"]*)$/,
_findFlags: function( source ) {
/**:jDoctest.Example.prototype._findFlags( source )
Returns a flag list from the source code.
>>> var src = "1; //doctest: +SKIP +ELLIPSIS";
>>> var exam = jDoctest.Example.prototype;
>>> var flags = exam._findFlags( src ).positive;
>>> $.inArray( jDoctest.flags.SKIP, flags ) >= 0;
true
>>> $.inArray( jDoctest.flags.ELLIPSIS, flags ) >= 0;
true
>>> $.inArray( jDoctest.flags.ACCEPT_BLANKLINE, flags ) < 0;
true
*/
var match, flags = {
positive: [],
negative: []
};
if ( match = this._OPTION_DIRECTIVE.exec( source ) ) {
var directive = match[ 1 ].split( /\s+/ ),
flagName;
for ( var flagName in j.flags ) {
if ( $.inArray( "+" + flagName, directive ) !== -1 ) {
flags.positive.push( j.flags[ flagName ] );
} else if ( $.inArray( "-" + flagName, directive ) !== -1 ) {
flags.negative.push( j.flags[ flagName ] );
}
}
}
return flags;
},
toString: function() {
return "<jDoctest.Example>";
}
};
/***********************************************************************
* OutputChecker
***********************************************************************/
j.OutputChecker = {
/**attribute:jDoctest.OutputChecker
The default output checker. Every output checkers must have ``checkOutput``
method.
*/
checkOutput: function( want, got, flags ) {
/**:jDoctest.OutputChecker.checkOutput( want, got, flags )
Checks if got output matched to wanted output.
>>> var checker = jDoctest.OutputChecker;
>>> checker.checkOutput( "1", "1" );
true
>>> checker.checkOutput( "2", "1" );
false
If some matching flags in ``flags``, that will be called. And if the
result is a ``true``, it returns ``true`` also. Otherwise it returns
just ``false``.
>>> checker.checkOutput( "a...f", "asdf", [
... jDoctest.flags.ELLIPSIS
... ]);
true
*/
if ( want === got ) {
return true;
}
var flag, flagResult;
for ( var i = 0; flags && i < flags.length; i++ ) {
flag = flags[ i ];
if ( $.isFunction( flag ) ) {
flagResult = flag( want, got );
if ( typeof flagResult === "object" ) {
if ( "want" in flagResult ) {
want = flagResult.want;
}
if ( "got" in flagResult ) {
got = flagResult.got;
}
flagResult = flagResult.matched;
}
if ( flagResult === true ) {
return true;
}
}
}
return false;
}
};
/***********************************************************************
* Runner
***********************************************************************/
j.Runner = function( result, options ) {
/**class:jDoctest.Runner( result[, options ] )
The runner is used to run a doctest.
>>> var result = {}, done = false;
>>> var doctest = new jDoctest([
... new jDoctest.Example( "1;", "1" ),
... new jDoctest.Example( "0; //doctest: +SKIP", "1" ),
... new jDoctest.Example( "0;", "1" ),
... ]);
>>> var runner = new jDoctest.Runner( result, {
... onComplete: function() { done = true; },
... console: jDoctest._mockConsole
... });
It will update ``result`` object which is given. ``result`` is extended to
have arrays named tries, successes, failures, and skips.
>>> result.tries.length;
0
>>> runner.run( doctest );
When all test done ``result``'s arrays is also updated.
>>> wait(function() { return done; });
>>> result.tries.length;
2
>>> result.successes.length;
1
>>> result.failures.length;
1
*/
this.result = $.extend( result || {}, {
tries: [],
successes: [],
failures: [],
skips: []
});
this.options = $.extend( {}, this.options, options );
this.checker = this.options.checker;
this.console = this.options.console;
this.context = $.extend( {}, this.context );
this._tasks = [];
this._running = {
stopped: true,
timer: null,
doctest: null
};
};
j.Runner.prototype = {
options: {
onComplete: undefined,
checker: j.OutputChecker,
verbose: false,
flags: undefined, // It will be filled later
console: console
},
// Reporting functions
reportStart: function( exam ) {
/**:jDoctest.Runner.prototype.reportStart( exam )
Reports before the example runs.
*/
if ( this.options.verbose ) {
var msg = [
"Trying:",
_.indent( exam.source ),
];
if ( exam.want === undefined ) {
msg.push( "Expecting nothing" );
} else {
msg.push( "Expecting:" );
msg.push( _.indent( exam.want ) );
}
this.console.log( msg.join( "\n" ) );
}
},
reportSuccess: function( exam, got ) {
/**:jDoctest.Runner.prototype.reportSuccess( exam, got )
Reports when the example is succeeded.
*/
if ( this.options.verbose ) {
this.console.log( "ok" );
}
},
reportFailure: function( exam, got ) {
/**:jDoctest.Runner.prototype.reportFailure( exam, got )
Reports when the example is failed.
*/
var doctest = this.getCurrentDoctest(),
msg = [
"File " + doctest.fileName + ", line " + exam.lineNo,
"Failed example:",
_.indent( exam.source )
];
if ( exam.want === undefined ) {
msg.push( "Expected nothing" );
} else {
msg.push( "Expected:" );
msg.push( _.indent( exam.want ) );
}
if ( got === undefined ) {
msg.push( "Got nothing" );
} else {
msg.push( "Got:" );
msg.push( _.indent( got ) );
}
msg = msg.join( "\n" );
this.console.error( msg );
},
reportFinally: function() {
/**:jDoctest.Runner.prototype.reportFinally()
Reports when the doctest done.
*/
var msg = "";
if ( this.options.verbose ) {
msg += this.result.successes.length + " passed";
}
if ( this.result.failures.length ) {
if ( this.options.verbose ) {
msg += " and " + this.result.failures.length + " failed.\n";
}
msg += "***Test Failed*** " + this.result.failures.length;
msg += " failures.";
this.console.warn( msg );
} else if ( msg ) {
msg += ".";
this.console.log( msg );
}
},
run: function( doctest ) {
/**:jDoctest.Runner.prototype.run( [ doctest ] )
This method registers a doctest to its task list first. And runs
tasks::
var runner = new jDoctest.Runner();
var doctest = new jDoctest();
runner.run( doctest );
Or::
var runner = new jDoctest.Runner();
var doctest = new jDoctest();
runner.register( doctest );
runner.run();
*/
if ( doctest instanceof jDoctest ) {
this.register( doctest );
}
clearTimeout( this._running.timer );
this._running.timer = setTimeout( $.proxy(function() {
this.progress();
}, this ), 0 );
},
register: function( doctest ) {
/**:jDoctest.Runner.prototype.register( doctest )
Registers the given doctest to the task list.
*/
this._tasks.push( doctest );
for ( var i = 0; i < doctest.examples.length; i++ ) {
this._tasks.push( doctest.examples[ i ] );
}
},
checkExample: function( exam, got ) {
/**:jDoctest.Runner.prototype.checkExample( exam, got )
Checks if the got value equals to the expected value using the own
:class:`OutputChecker` instance. The example will be kept in the
``result`` object.
>>> var runner = new jDoctest.Runner();
>>> var mockExample = { want: "Hello", flags: [] };
>>> runner.checkExample( mockExample, "Hello" );
true
>>> runner.result.successes.length;
1
>>> runner.checkExample( mockExample, "World" );
false
>>> runner.result.failures.length;
1
*/
var flags = this.adjustFlags( exam.flags, exam.negetiveFlags );
this.result.tries.push( exam );
if ( this.checker.checkOutput( exam.want, got, flags ) ) {
this.result.successes.push( exam );
return true;
} else {
this.result.failures.push( exam );
return false;
}
},
runExample: function( exam ) {
/**:jDoctest.Runner.prototype.runExample( exam )
Runs the given example and reports a result. If the example throws a
``StopRunning`` exception, it makes the running to stop.
*/
try {
var got = this.getOutput( exam.source ),
succeeded = this.checkExample( exam, got );
if ( succeeded ) {
this.reportSuccess( exam );
} else {
this.reportFailure( exam, got );
}
} catch ( error ) {
if ( error instanceof j.errors.StopRunning ) {
this.reportSuccess( exam );
this.stop();
} else {
throw error;
}
}
},
runFinally: function() {
/**:jDoctest.Runner.prototype.runFinally()
It will be called after all examples ran.
*/
this.reportFinally();
},
progress: function( justOneStep ) {
/**:jDoctest.Runner.prototype.progress()
Processes the top task and call this method again if the task list is
not empty.
A task could be an instance of :class:`jDoctest` or
:class:`jDoctest.Example`. If the task is an instance of
:class:`jDoctest`, this method just updates the current doctest object.
But the task is an instance of :class:`jDoctest.Example`, it calls
:meth:`jDoctest.Runner.prototype.reportStart` and tests the example.
>>> var runner = new jDoctest.Runner( undefined, {
... onComplete: function() {
... print( "ALL TASKS HAVE PROCESSED" );
... }
... });
>>> var doctest = new jDoctest([
... new jDoctest.Example( "1;", "1" )
... ]);
>>> runner.register( doctest );
>>> runner.getCurrentDoctest();
null
>>> runner.progress();
ALL TASKS HAVE PROCESSED
>>> runner.getCurrentDoctest() instanceof jDoctest;
true
:param justOneStep: if set it to ``true``, this method doesn't go to