This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Upgrade to Term::ANSIColor 1.09
[perl5.git] / lib / Test / Harness.pm
CommitLineData
d667a7e6 1# -*- Mode: cperl; cperl-indent-level: 4 -*-
42d29bac 2# $Id: Harness.pm,v 1.85 2004/04/29 03:13:43 andy Exp $
b82fa0b7 3
a0d0e21e
LW
4package Test::Harness;
5
b82fa0b7 6require 5.004;
13287dd5
MS
7use Test::Harness::Straps;
8use Test::Harness::Assert;
a0d0e21e
LW
9use Exporter;
10use Benchmark;
4633a7c4 11use Config;
760ac839
LW
12use strict;
13
e4fc8a1e
RGS
14use vars qw(
15 $VERSION
16 @ISA @EXPORT @EXPORT_OK
17 $Verbose $Switches $Debug
18 $verbose $switches $debug
19 $Have_Devel_Corestack
20 $Curtest
21 $Columns
22 $ML $Last_ML_Print
23 $Strap
24);
25
26=head1 NAME
27
28Test::Harness - Run Perl standard test scripts with statistics
29
30=head1 VERSION
31
42d29bac 32Version 2.42;
e4fc8a1e 33
42d29bac 34 $Header: /home/cvs/test-harness/lib/Test/Harness.pm,v 1.85 2004/04/29 03:13:43 andy Exp $
e4fc8a1e
RGS
35
36=cut
37
42d29bac 38$VERSION = '2.42';
4633a7c4 39
9c5c68c8 40# Backwards compatibility for exportable variable names.
5c0604c3
MS
41*verbose = *Verbose;
42*switches = *Switches;
e4fc8a1e 43*debug = *Debug;
9c5c68c8
MS
44
45$Have_Devel_Corestack = 0;
46
f19ae7a7
JD
47$ENV{HARNESS_ACTIVE} = 1;
48
13287dd5
MS
49END {
50 # For VMS.
51 delete $ENV{HARNESS_ACTIVE};
52}
53
9b0ceca9 54# Some experimental versions of OS/2 build have broken $?
9c5c68c8
MS
55my $Ignore_Exitcode = $ENV{HARNESS_IGNORE_EXITCODE};
56
57my $Files_In_Dir = $ENV{HARNESS_FILELEAK_IN_DIR};
9b0ceca9 58
60af4b93
JH
59my $Ok_Slow = $ENV{HARNESS_OK_SLOW};
60
d5d4ec93 61$Strap = Test::Harness::Straps->new;
17a79f5b 62
9c5c68c8
MS
63@ISA = ('Exporter');
64@EXPORT = qw(&runtests);
65@EXPORT_OK = qw($verbose $switches);
4633a7c4 66
356733da 67$Verbose = $ENV{HARNESS_VERBOSE} || 0;
e4fc8a1e 68$Debug = $ENV{HARNESS_DEBUG} || 0;
9c5c68c8
MS
69$Switches = "-w";
70$Columns = $ENV{HARNESS_COLUMNS} || $ENV{COLUMNS} || 80;
b82fa0b7
MS
71$Columns--; # Some shells have trouble with a full line of text.
72
b82fa0b7
MS
73=head1 SYNOPSIS
74
75 use Test::Harness;
76
77 runtests(@test_files);
78
79=head1 DESCRIPTION
a0d0e21e 80
b82fa0b7
MS
81B<STOP!> If all you want to do is write a test script, consider using
82Test::Simple. Otherwise, read on.
83
84(By using the Test module, you can write test scripts without
85knowing the exact output this module expects. However, if you need to
86know the specifics, read on!)
87
88Perl test scripts print to standard output C<"ok N"> for each single
89test, where C<N> is an increasing sequence of integers. The first line
90output by a standard test script is C<"1..M"> with C<M> being the
91number of tests that should be run within the test
92script. Test::Harness::runtests(@tests) runs all the testscripts
93named as arguments and checks standard output for the expected
94C<"ok N"> strings.
95
96After all tests have been performed, runtests() prints some
97performance statistics that are computed by the Benchmark module.
98
99=head2 The test script output
100
101The following explains how Test::Harness interprets the output of your
102test program.
103
104=over 4
105
106=item B<'1..M'>
107
356733da
MS
108This header tells how many tests there will be. For example, C<1..10>
109means you plan on running 10 tests. This is a safeguard in case your
110test dies quietly in the middle of its run.
111
112It should be the first non-comment line output by your test program.
b82fa0b7 113
356733da
MS
114In certain instances, you may not know how many tests you will
115ultimately be running. In this case, it is permitted for the 1..M
116header to appear as the B<last> line output by your test (again, it
117can be followed by further comments).
b82fa0b7
MS
118
119Under B<no> circumstances should 1..M appear in the middle of your
120output or more than once.
121
122
123=item B<'ok', 'not ok'. Ok?>
124
125Any output from the testscript to standard error is ignored and
126bypassed, thus will be seen by the user. Lines written to standard
127output containing C</^(not\s+)?ok\b/> are interpreted as feedback for
128runtests(). All other lines are discarded.
129
130C</^not ok/> indicates a failed test. C</^ok/> is a successful test.
131
132
133=item B<test numbers>
134
135Perl normally expects the 'ok' or 'not ok' to be followed by a test
136number. It is tolerated if the test numbers after 'ok' are
137omitted. In this case Test::Harness maintains temporarily its own
138counter until the script supplies test numbers again. So the following
139test script
140
141 print <<END;
142 1..6
143 not ok
144 ok
145 not ok
146 ok
147 ok
148 END
149
150will generate
151
152 FAILED tests 1, 3, 6
153 Failed 3/6 tests, 50.00% okay
154
13287dd5 155=item B<test names>
b82fa0b7 156
13287dd5
MS
157Anything after the test number but before the # is considered to be
158the name of the test.
b82fa0b7 159
13287dd5 160 ok 42 this is the name of the test
b82fa0b7 161
13287dd5 162Currently, Test::Harness does nothing with this information.
b82fa0b7
MS
163
164=item B<Skipping tests>
165
166If the standard output line contains the substring C< # Skip> (with
167variations in spacing and case) after C<ok> or C<ok NUMBER>, it is
168counted as a skipped test. If the whole testscript succeeds, the
169count of skipped tests is included in the generated output.
170C<Test::Harness> reports the text after C< # Skip\S*\s+> as a reason
356733da 171for skipping.
b82fa0b7
MS
172
173 ok 23 # skip Insufficient flogiston pressure.
174
175Similarly, one can include a similar explanation in a C<1..0> line
176emitted if the test script is skipped completely:
177
178 1..0 # Skipped: no leverage found
179
180=item B<Todo tests>
181
e4fc8a1e 182If the standard output line contains the substring C< # TODO > after
b82fa0b7
MS
183C<not ok> or C<not ok NUMBER>, it is counted as a todo test. The text
184afterwards is the thing that has to be done before this test will
185succeed.
186
187 not ok 13 # TODO harness the power of the atom
188
e4fc8a1e
RGS
189Note that the TODO must have a space after it.
190
13287dd5
MS
191=begin _deprecated
192
193Alternatively, you can specify a list of what tests are todo as part
194of the test header.
195
196 1..23 todo 5 12 23
197
198This only works if the header appears at the beginning of the test.
199
200This style is B<deprecated>.
201
202=end _deprecated
203
b82fa0b7
MS
204These tests represent a feature to be implemented or a bug to be fixed
205and act as something of an executable "thing to do" list. They are
206B<not> expected to succeed. Should a todo test begin succeeding,
207Test::Harness will report it as a bonus. This indicates that whatever
208you were supposed to do has been done and you should promote this to a
209normal test.
210
211=item B<Bail out!>
212
213As an emergency measure, a test script can decide that further tests
214are useless (e.g. missing dependencies) and testing should stop
215immediately. In that case the test script prints the magic words
216
217 Bail out!
218
219to standard output. Any message after these words will be displayed by
220C<Test::Harness> as the reason why testing is stopped.
221
222=item B<Comments>
223
224Additional comments may be put into the testing output on their own
225lines. Comment lines should begin with a '#', Test::Harness will
226ignore them.
227
228 ok 1
229 # Life is good, the sun is shining, RAM is cheap.
230 not ok 2
231 # got 'Bush' expected 'Gore'
232
233=item B<Anything else>
234
235Any other output Test::Harness sees it will silently ignore B<BUT WE
236PLAN TO CHANGE THIS!> If you wish to place additional output in your
237test script, please use a comment.
238
239=back
240
13287dd5
MS
241=head2 Taint mode
242
e4fc8a1e
RGS
243Test::Harness will honor the C<-T> or C<-t> in the #! line on your
244test files. So if you begin a test with:
13287dd5
MS
245
246 #!perl -T
247
248the test will be run with taint mode on.
249
13287dd5
MS
250=head2 Configuration variables.
251
252These variables can be used to configure the behavior of
253Test::Harness. They are exported on request.
254
255=over 4
256
e4fc8a1e 257=item B<$Test::Harness::Verbose>
13287dd5 258
e4fc8a1e
RGS
259The global variable C<$Test::Harness::Verbose> is exportable and can be
260used to let C<runtests()> display the standard output of the script
261without altering the behavior otherwise. The F<prove> utility's C<-v>
262flag will set this.
13287dd5
MS
263
264=item B<$Test::Harness::switches>
265
e4fc8a1e 266The global variable C<$Test::Harness::switches> is exportable and can be
13287dd5 267used to set perl command line options used for running the test
e4fc8a1e 268script(s). The default value is C<-w>. It overrides C<HARNESS_SWITCHES>.
13287dd5
MS
269
270=back
271
272
b82fa0b7
MS
273=head2 Failure
274
e4fc8a1e 275It will happen: your tests will fail. After you mop up your ego, you
b82fa0b7
MS
276can begin examining the summary report:
277
2fe373ce
MS
278 t/base..............ok
279 t/nonumbers.........ok
280 t/ok................ok
281 t/test-harness......ok
282 t/waterloo..........dubious
b82fa0b7
MS
283 Test returned status 3 (wstat 768, 0x300)
284 DIED. FAILED tests 1, 3, 5, 7, 9, 11, 13, 15, 17, 19
285 Failed 10/20 tests, 50.00% okay
286 Failed Test Stat Wstat Total Fail Failed List of Failed
287 -----------------------------------------------------------------------
288 t/waterloo.t 3 768 20 10 50.00% 1 3 5 7 9 11 13 15 17 19
289 Failed 1/5 test scripts, 80.00% okay. 10/44 subtests failed, 77.27% okay.
290
291Everything passed but t/waterloo.t. It failed 10 of 20 tests and
292exited with non-zero status indicating something dubious happened.
293
294The columns in the summary report mean:
295
296=over 4
297
298=item B<Failed Test>
299
300The test file which failed.
301
302=item B<Stat>
303
304If the test exited with non-zero, this is its exit status.
305
306=item B<Wstat>
307
e4fc8a1e 308The wait status of the test.
b82fa0b7
MS
309
310=item B<Total>
311
312Total number of tests expected to run.
313
314=item B<Fail>
315
316Number which failed, either from "not ok" or because they never ran.
317
318=item B<Failed>
319
320Percentage of the total tests which failed.
321
322=item B<List of Failed>
323
324A list of the tests which failed. Successive failures may be
325abbreviated (ie. 15-20 to indicate that tests 15, 16, 17, 18, 19 and
32620 failed).
327
328=back
329
330
331=head2 Functions
332
333Test::Harness currently only has one function, here it is.
334
335=over 4
336
337=item B<runtests>
338
339 my $allok = runtests(@test_files);
340
341This runs all the given @test_files and divines whether they passed
342or failed based on their output to STDOUT (details above). It prints
343out each individual test which failed along with a summary report and
344a how long it all took.
345
d5d4ec93
MS
346It returns true if everything was ok. Otherwise it will die() with
347one of the messages in the DIAGNOSTICS section.
b82fa0b7
MS
348
349=for _private
0bf5423d 350
b82fa0b7
MS
351This is just _run_all_tests() plus _show_results()
352
353=cut
17a79f5b 354
a0d0e21e
LW
355sub runtests {
356 my(@tests) = @_;
9c5c68c8 357
b82fa0b7
MS
358 local ($\, $,);
359
360 my($tot, $failedtests) = _run_all_tests(@tests);
9c5c68c8
MS
361 _show_results($tot, $failedtests);
362
2fe373ce 363 my $ok = _all_ok($tot);
b82fa0b7 364
13287dd5
MS
365 assert(($ok xor keys %$failedtests),
366 q{ok status jives with $failedtests});
b82fa0b7
MS
367
368 return $ok;
369}
370
371=begin _private
372
2fe373ce
MS
373=item B<_all_ok>
374
375 my $ok = _all_ok(\%tot);
376
377Tells you if this test run is overall successful or not.
378
379=cut
380
381sub _all_ok {
382 my($tot) = shift;
383
384 return $tot->{bad} == 0 && ($tot->{max} || $tot->{skipped}) ? 1 : 0;
385}
386
b82fa0b7
MS
387=item B<_globdir>
388
389 my @files = _globdir $dir;
390
391Returns all the files in a directory. This is shorthand for backwards
392compatibility on systems where glob() doesn't work right.
393
394=cut
395
396sub _globdir {
397 opendir DIRH, shift;
398 my @f = readdir DIRH;
399 closedir DIRH;
400
401 return @f;
9c5c68c8
MS
402}
403
b82fa0b7
MS
404=item B<_run_all_tests>
405
406 my($total, $failed) = _run_all_tests(@test_files);
407
e4fc8a1e
RGS
408Runs all the given C<@test_files> (as C<runtests()>) but does it
409quietly (no report). $total is a hash ref summary of all the tests
410run. Its keys and values are this:
b82fa0b7
MS
411
412 bonus Number of individual todo tests unexpectedly passed
413 max Number of individual tests ran
414 ok Number of individual tests passed
415 sub_skipped Number of individual tests skipped
2fe373ce 416 todo Number of individual todo tests
b82fa0b7
MS
417
418 files Number of test files ran
419 good Number of test files passed
420 bad Number of test files failed
421 tests Number of test files originally given
422 skipped Number of test files skipped
423
e4fc8a1e
RGS
424If C<< $total->{bad} == 0 >> and C<< $total->{max} > 0 >>, you've
425got a successful test.
b82fa0b7
MS
426
427$failed is a hash ref of all the test scripts which failed. Each key
428is the name of a test script, each value is another hash representing
429how that script failed. Its keys are these:
9c5c68c8 430
b82fa0b7
MS
431 name Name of the test which failed
432 estat Script's exit value
433 wstat Script's wait status
434 max Number of individual tests
435 failed Number which failed
436 percent Percentage of tests which failed
437 canon List of tests which failed (as string).
438
e4fc8a1e 439C<$failed> should be empty if everything passed.
b82fa0b7
MS
440
441B<NOTE> Currently this function is still noisy. I'm working on it.
442
443=cut
444
308957f5 445#'#
b82fa0b7 446sub _run_all_tests {
9c5c68c8 447 my(@tests) = @_;
a0d0e21e 448 local($|) = 1;
9c5c68c8
MS
449 my(%failedtests);
450
451 # Test-wide totals.
452 my(%tot) = (
453 bonus => 0,
454 max => 0,
455 ok => 0,
456 files => 0,
457 bad => 0,
458 good => 0,
459 tests => scalar @tests,
460 sub_skipped => 0,
2fe373ce 461 todo => 0,
9c5c68c8 462 skipped => 0,
2fe373ce 463 bench => 0,
9c5c68c8 464 );
774d564b 465
76df5e8f
DM
466 my @dir_files;
467 @dir_files = _globdir $Files_In_Dir if defined $Files_In_Dir;
a0d0e21e 468 my $t_start = new Benchmark;
9c5c68c8 469
13287dd5 470 my $width = _leader_width(@tests);
b82fa0b7 471 foreach my $tfile (@tests) {
e4fc8a1e
RGS
472 if ( $Test::Harness::Debug ) {
473 print "# Running: ", $Strap->_command_line($tfile), "\n";
474 }
475
5c0604c3 476 $Last_ML_Print = 0; # so each test prints at least once
7a315204 477 my($leader, $ml) = _mk_leader($tfile, $width);
308957f5 478 local $ML = $ml;
e4fc8a1e 479
b82fa0b7 480 print $leader;
9c5c68c8 481
356733da
MS
482 $tot{files}++;
483
308957f5 484 $Strap->{_seen_header} = 0;
0be28027 485 my %results = $Strap->analyze_file($tfile) or
e4fc8a1e 486 do { warn $Strap->{error}, "\n"; next };
308957f5 487
9c5c68c8 488 # state of the current test.
308957f5
JH
489 my @failed = grep { !$results{details}[$_-1]{ok} }
490 1..@{$results{details}};
9c5c68c8 491 my %test = (
308957f5
JH
492 ok => $results{ok},
493 'next' => $Strap->{'next'},
494 max => $results{max},
495 failed => \@failed,
496 bonus => $results{bonus},
497 skipped => $results{skip},
a72fde19 498 skip_reason => $results{skip_reason},
c0bb2de7 499 skip_all => $Strap->{skip_all},
9c5c68c8
MS
500 ml => $ml,
501 );
502
308957f5
JH
503 $tot{bonus} += $results{bonus};
504 $tot{max} += $results{max};
505 $tot{ok} += $results{ok};
506 $tot{todo} += $results{todo};
507 $tot{sub_skipped} += $results{skip};
9c5c68c8 508
308957f5 509 my($estatus, $wstatus) = @results{qw(exit wait)};
b82fa0b7 510
a72fde19 511 if ($results{passing}) {
2fe373ce
MS
512 if ($test{max} and $test{skipped} + $test{bonus}) {
513 my @msg;
514 push(@msg, "$test{skipped}/$test{max} skipped: $test{skip_reason}")
515 if $test{skipped};
516 push(@msg, "$test{bonus}/$test{max} unexpectedly succeeded")
517 if $test{bonus};
f0008e52 518 print "$test{ml}ok\n ".join(', ', @msg)."\n";
2fe373ce
MS
519 } elsif ($test{max}) {
520 print "$test{ml}ok\n";
d5d4ec93 521 } elsif (defined $test{skip_all} and length $test{skip_all}) {
c0bb2de7 522 print "skipped\n all skipped: $test{skip_all}\n";
2fe373ce
MS
523 $tot{skipped}++;
524 } else {
0be28027 525 print "skipped\n all skipped: no reason given\n";
2fe373ce
MS
526 $tot{skipped}++;
527 }
528 $tot{good}++;
529 }
b82fa0b7 530 else {
a72fde19
JH
531 # List unrun tests as failures.
532 if ($test{'next'} <= $test{max}) {
533 push @{$test{failed}}, $test{'next'}..$test{max};
534 }
535 # List overruns as failures.
536 else {
537 my $details = $results{details};
538 foreach my $overrun ($test{max}+1..@$details)
539 {
540 next unless ref $details->[$overrun-1];
541 push @{$test{failed}}, $overrun
b82fa0b7 542 }
a72fde19
JH
543 }
544
545 if ($wstatus) {
546 $failedtests{$tfile} = _dubious_return(\%test, \%tot,
547 $estatus, $wstatus);
548 $failedtests{$tfile}{name} = $tfile;
549 }
550 elsif($results{seen}) {
c4b2e1b6 551 if (@{$test{failed}} and $test{max}) {
60e33a80 552 my ($txt, $canon) = _canonfailed($test{max},$test{skipped},
b82fa0b7
MS
553 @{$test{failed}});
554 print "$test{ml}$txt";
555 $failedtests{$tfile} = { canon => $canon,
556 max => $test{max},
557 failed => scalar @{$test{failed}},
558 name => $tfile,
559 percent => 100*(scalar @{$test{failed}})/$test{max},
560 estat => '',
561 wstat => '',
562 };
563 } else {
564 print "Don't know which tests failed: got $test{ok} ok, ".
565 "expected $test{max}\n";
566 $failedtests{$tfile} = { canon => '??',
567 max => $test{max},
568 failed => '??',
569 name => $tfile,
570 percent => undef,
571 estat => '',
572 wstat => '',
573 };
574 }
575 $tot{bad}++;
a72fde19 576 } else {
b82fa0b7
MS
577 print "FAILED before any test output arrived\n";
578 $tot{bad}++;
579 $failedtests{$tfile} = { canon => '??',
580 max => '??',
581 failed => '??',
582 name => $tfile,
583 percent => undef,
584 estat => '',
585 wstat => '',
586 };
587 }
588 }
589
2fe373ce
MS
590 if (defined $Files_In_Dir) {
591 my @new_dir_files = _globdir $Files_In_Dir;
592 if (@new_dir_files != @dir_files) {
593 my %f;
594 @f{@new_dir_files} = (1) x @new_dir_files;
595 delete @f{@dir_files};
596 my @f = sort keys %f;
597 print "LEAKED FILES: @f\n";
598 @dir_files = @new_dir_files;
599 }
600 }
a0d0e21e 601 }
9c5c68c8 602 $tot{bench} = timediff(new Benchmark, $t_start);
d667a7e6 603
13287dd5 604 $Strap->_restore_PERL5LIB;
9c5c68c8
MS
605
606 return(\%tot, \%failedtests);
607}
608
b82fa0b7
MS
609=item B<_mk_leader>
610
7a315204 611 my($leader, $ml) = _mk_leader($test_file, $width);
b82fa0b7 612
e4fc8a1e 613Generates the 't/foo........' $leader for the given C<$test_file> as well
b82fa0b7 614as a similar version which will overwrite the current line (by use of
e4fc8a1e 615\r and such). C<$ml> may be empty if Test::Harness doesn't think you're
2fe373ce
MS
616on TTY.
617
e4fc8a1e 618The C<$width> is the width of the "yada/blah.." string.
b82fa0b7
MS
619
620=cut
621
622sub _mk_leader {
2fe373ce
MS
623 my($te, $width) = @_;
624 chomp($te);
b695f709 625 $te =~ s/\.\w+$/./;
b82fa0b7 626
356733da 627 if ($^O eq 'VMS') { $te =~ s/^.*\.t\./\[.t./s; }
b82fa0b7 628 my $blank = (' ' x 77);
7a315204 629 my $leader = "$te" . '.' x ($width - length($te));
b82fa0b7
MS
630 my $ml = "";
631
632 $ml = "\r$blank\r$leader"
633 if -t STDOUT and not $ENV{HARNESS_NOTTY} and not $Verbose;
634
635 return($leader, $ml);
636}
637
13287dd5
MS
638=item B<_leader_width>
639
640 my($width) = _leader_width(@test_files);
641
642Calculates how wide the leader should be based on the length of the
643longest test name.
644
645=cut
646
647sub _leader_width {
648 my $maxlen = 0;
649 my $maxsuflen = 0;
650 foreach (@_) {
651 my $suf = /\.(\w+)$/ ? $1 : '';
652 my $len = length;
653 my $suflen = length $suf;
654 $maxlen = $len if $len > $maxlen;
655 $maxsuflen = $suflen if $suflen > $maxsuflen;
656 }
356733da
MS
657 # + 3 : we want three dots between the test name and the "ok"
658 return $maxlen + 3 - $maxsuflen;
13287dd5
MS
659}
660
9c5c68c8
MS
661
662sub _show_results {
663 my($tot, $failedtests) = @_;
664
665 my $pct;
666 my $bonusmsg = _bonusmsg($tot);
667
2fe373ce
MS
668 if (_all_ok($tot)) {
669 print "All tests successful$bonusmsg.\n";
670 } elsif (!$tot->{tests}){
671 die "FAILED--no tests were run for some reason.\n";
672 } elsif (!$tot->{max}) {
673 my $blurb = $tot->{tests}==1 ? "script" : "scripts";
674 die "FAILED--$tot->{tests} test $blurb could be run, ".
9c5c68c8 675 "alas--no output ever seen\n";
c07a80fd 676 } else {
2fe373ce
MS
677 $pct = sprintf("%.2f", $tot->{good} / $tot->{tests} * 100);
678 my $percent_ok = 100*$tot->{ok}/$tot->{max};
679 my $subpct = sprintf " %d/%d subtests failed, %.2f%% okay.",
680 $tot->{max} - $tot->{ok}, $tot->{max},
681 $percent_ok;
0a931e4a 682
9c5c68c8 683 my($fmt_top, $fmt) = _create_fmts($failedtests);
0a931e4a 684
2fe373ce
MS
685 # Now write to formats
686 for my $script (sort keys %$failedtests) {
687 $Curtest = $failedtests->{$script};
688 write;
689 }
690 if ($tot->{bad}) {
691 $bonusmsg =~ s/^,\s*//;
692 print "$bonusmsg.\n" if $bonusmsg;
693 die "Failed $tot->{bad}/$tot->{tests} test scripts, $pct% okay.".
9c5c68c8 694 "$subpct\n";
2fe373ce 695 }
c07a80fd 696 }
f0a9308e 697
9c5c68c8
MS
698 printf("Files=%d, Tests=%d, %s\n",
699 $tot->{files}, $tot->{max}, timestr($tot->{bench}, 'nop'));
700}
701
702
308957f5
JH
703my %Handlers = ();
704$Strap->{callback} = sub {
705 my($self, $line, $type, $totals) = @_;
706 print $line if $Verbose;
9c5c68c8 707
308957f5
JH
708 my $meth = $Handlers{$type};
709 $meth->($self, $line, $type, $totals) if $meth;
710};
9c5c68c8 711
9c5c68c8 712
308957f5
JH
713$Handlers{header} = sub {
714 my($self, $line, $type, $totals) = @_;
9c5c68c8 715
308957f5 716 warn "Test header seen more than once!\n" if $self->{_seen_header};
9c5c68c8 717
308957f5 718 $self->{_seen_header}++;
9c5c68c8 719
308957f5
JH
720 warn "1..M can only appear at the beginning or end of tests\n"
721 if $totals->{seen} &&
722 $totals->{max} < $totals->{seen};
723};
13287dd5 724
308957f5
JH
725$Handlers{test} = sub {
726 my($self, $line, $type, $totals) = @_;
9c5c68c8 727
308957f5
JH
728 my $curr = $totals->{seen};
729 my $next = $self->{'next'};
730 my $max = $totals->{max};
731 my $detail = $totals->{details}[-1];
b82fa0b7 732
308957f5 733 if( $detail->{ok} ) {
5c0604c3 734 _print_ml_less("ok $curr/$max");
356733da 735
308957f5 736 if( $detail->{type} eq 'skip' ) {
a72fde19
JH
737 $totals->{skip_reason} = $detail->{reason}
738 unless defined $totals->{skip_reason};
739 $totals->{skip_reason} = 'various reasons'
740 if $totals->{skip_reason} ne $detail->{reason};
308957f5 741 }
b82fa0b7
MS
742 }
743 else {
308957f5 744 _print_ml("NOK $curr");
b82fa0b7 745 }
b82fa0b7 746
308957f5
JH
747 if( $curr > $next ) {
748 print "Test output counter mismatch [test $curr]\n";
749 }
750 elsif( $curr < $next ) {
751 print "Confused test output: test $curr answered after ".
752 "test ", $next - 1, "\n";
753 }
b82fa0b7 754
308957f5 755};
2fe373ce 756
308957f5
JH
757$Handlers{bailout} = sub {
758 my($self, $line, $type, $totals) = @_;
9c5c68c8 759
308957f5
JH
760 die "FAILED--Further testing stopped" .
761 ($self->{bailout_reason} ? ": $self->{bailout_reason}\n" : ".\n");
762};
356733da 763
9c5c68c8 764
308957f5
JH
765sub _print_ml {
766 print join '', $ML, @_ if $ML;
9c5c68c8
MS
767}
768
769
5c0604c3
MS
770# For slow connections, we save lots of bandwidth by printing only once
771# per second.
772sub _print_ml_less {
60af4b93 773 if( !$Ok_Slow || $Last_ML_Print != time ) {
5c0604c3
MS
774 _print_ml(@_);
775 $Last_ML_Print = time;
776 }
777}
778
9c5c68c8
MS
779sub _bonusmsg {
780 my($tot) = @_;
781
782 my $bonusmsg = '';
783 $bonusmsg = (" ($tot->{bonus} subtest".($tot->{bonus} > 1 ? 's' : '').
2fe373ce
MS
784 " UNEXPECTEDLY SUCCEEDED)")
785 if $tot->{bonus};
9c5c68c8
MS
786
787 if ($tot->{skipped}) {
2fe373ce 788 $bonusmsg .= ", $tot->{skipped} test"
9c5c68c8 789 . ($tot->{skipped} != 1 ? 's' : '');
2fe373ce
MS
790 if ($tot->{sub_skipped}) {
791 $bonusmsg .= " and $tot->{sub_skipped} subtest"
792 . ($tot->{sub_skipped} != 1 ? 's' : '');
793 }
794 $bonusmsg .= ' skipped';
9c5c68c8
MS
795 }
796 elsif ($tot->{sub_skipped}) {
2fe373ce
MS
797 $bonusmsg .= ", $tot->{sub_skipped} subtest"
798 . ($tot->{sub_skipped} != 1 ? 's' : '')
799 . " skipped";
9c5c68c8
MS
800 }
801
802 return $bonusmsg;
803}
804
9c5c68c8
MS
805# Test program go boom.
806sub _dubious_return {
807 my($test, $tot, $estatus, $wstatus) = @_;
808 my ($failed, $canon, $percent) = ('??', '??');
809
810 printf "$test->{ml}dubious\n\tTest returned status $estatus ".
811 "(wstat %d, 0x%x)\n",
812 $wstatus,$wstatus;
813 print "\t\t(VMS status is $estatus)\n" if $^O eq 'VMS';
814
60e33a80 815 if (_corestatus($wstatus)) { # until we have a wait module
9c5c68c8
MS
816 if ($Have_Devel_Corestack) {
817 Devel::CoreStack::stack($^X);
818 } else {
819 print "\ttest program seems to have generated a core\n";
820 }
821 }
822
823 $tot->{bad}++;
824
825 if ($test->{max}) {
b82fa0b7 826 if ($test->{'next'} == $test->{max} + 1 and not @{$test->{failed}}) {
9c5c68c8
MS
827 print "\tafter all the subtests completed successfully\n";
828 $percent = 0;
2fe373ce 829 $failed = 0; # But we do not set $canon!
9c5c68c8
MS
830 }
831 else {
b82fa0b7 832 push @{$test->{failed}}, $test->{'next'}..$test->{max};
9c5c68c8 833 $failed = @{$test->{failed}};
60e33a80 834 (my $txt, $canon) = _canonfailed($test->{max},$test->{skipped},@{$test->{failed}});
9c5c68c8
MS
835 $percent = 100*(scalar @{$test->{failed}})/$test->{max};
836 print "DIED. ",$txt;
837 }
838 }
839
840 return { canon => $canon, max => $test->{max} || '??',
841 failed => $failed,
66fd8cb9 842 percent => $percent,
9c5c68c8
MS
843 estat => $estatus, wstat => $wstatus,
844 };
845}
846
847
9c5c68c8
MS
848sub _create_fmts {
849 my($failedtests) = @_;
850
b82fa0b7
MS
851 my $failed_str = "Failed Test";
852 my $middle_str = " Stat Wstat Total Fail Failed ";
9c5c68c8
MS
853 my $list_str = "List of Failed";
854
855 # Figure out our longest name string for formatting purposes.
856 my $max_namelen = length($failed_str);
857 foreach my $script (keys %$failedtests) {
858 my $namelen = length $failedtests->{$script}->{name};
859 $max_namelen = $namelen if $namelen > $max_namelen;
860 }
861
862 my $list_len = $Columns - length($middle_str) - $max_namelen;
863 if ($list_len < length($list_str)) {
864 $list_len = length($list_str);
865 $max_namelen = $Columns - length($middle_str) - $list_len;
866 if ($max_namelen < length($failed_str)) {
867 $max_namelen = length($failed_str);
868 $Columns = $max_namelen + length($middle_str) + $list_len;
869 }
870 }
871
872 my $fmt_top = "format STDOUT_TOP =\n"
b82fa0b7 873 . sprintf("%-${max_namelen}s", $failed_str)
9c5c68c8 874 . $middle_str
2fe373ce
MS
875 . $list_str . "\n"
876 . "-" x $Columns
877 . "\n.\n";
9c5c68c8
MS
878
879 my $fmt = "format STDOUT =\n"
2fe373ce 880 . "@" . "<" x ($max_namelen - 1)
b82fa0b7 881 . " @>> @>>>> @>>>> @>>> ^##.##% "
2fe373ce
MS
882 . "^" . "<" x ($list_len - 1) . "\n"
883 . '{ $Curtest->{name}, $Curtest->{estat},'
884 . ' $Curtest->{wstat}, $Curtest->{max},'
885 . ' $Curtest->{failed}, $Curtest->{percent},'
886 . ' $Curtest->{canon}'
887 . "\n}\n"
888 . "~~" . " " x ($Columns - $list_len - 2) . "^"
889 . "<" x ($list_len - 1) . "\n"
890 . '$Curtest->{canon}'
891 . "\n.\n";
9c5c68c8
MS
892
893 eval $fmt_top;
894 die $@ if $@;
895 eval $fmt;
896 die $@ if $@;
897
898 return($fmt_top, $fmt);
899}
900
b82fa0b7
MS
901{
902 my $tried_devel_corestack;
9c5c68c8 903
60e33a80 904 sub _corestatus {
b82fa0b7 905 my($st) = @_;
c0ee6f5c 906
a72fde19
JH
907 my $did_core;
908 eval { # we may not have a WCOREDUMP
356733da 909 local $^W = 0; # *.ph files are often *very* noisy
a72fde19
JH
910 require 'wait.ph';
911 $did_core = WCOREDUMP($st);
356733da 912 };
a72fde19
JH
913 if( $@ ) {
914 $did_core = $st & 0200;
915 }
c0ee6f5c 916
b82fa0b7
MS
917 eval { require Devel::CoreStack; $Have_Devel_Corestack++ }
918 unless $tried_devel_corestack++;
c0ee6f5c 919
356733da 920 return $did_core;
b82fa0b7 921 }
c0ee6f5c 922}
923
60e33a80 924sub _canonfailed ($$@) {
89d3b7e2 925 my($max,$skipped,@failed) = @_;
6c31b336
A
926 my %seen;
927 @failed = sort {$a <=> $b} grep !$seen{$_}++, @failed;
c07a80fd 928 my $failed = @failed;
929 my @result = ();
930 my @canon = ();
931 my $min;
932 my $last = $min = shift @failed;
760ac839 933 my $canon;
c07a80fd 934 if (@failed) {
2fe373ce
MS
935 for (@failed, $failed[-1]) { # don't forget the last one
936 if ($_ > $last+1 || $_ == $last) {
937 if ($min == $last) {
938 push @canon, $last;
939 } else {
940 push @canon, "$min-$last";
941 }
942 $min = $_;
943 }
944 $last = $_;
945 }
946 local $" = ", ";
947 push @result, "FAILED tests @canon\n";
948 $canon = join ' ', @canon;
a0d0e21e 949 } else {
2fe373ce
MS
950 push @result, "FAILED test $last\n";
951 $canon = $last;
a0d0e21e 952 }
c07a80fd 953
954 push @result, "\tFailed $failed/$max tests, ";
e93c2686
JH
955 if ($max) {
956 push @result, sprintf("%.2f",100*(1-$failed/$max)), "% okay";
957 } else {
958 push @result, "?% okay";
959 }
89d3b7e2
IZ
960 my $ender = 's' x ($skipped > 1);
961 my $good = $max - $failed - $skipped;
e93c2686
JH
962 if ($skipped) {
963 my $skipmsg = " (less $skipped skipped test$ender: $good okay, ";
964 if ($max) {
965 my $goodper = sprintf("%.2f",100*($good/$max));
966 $skipmsg .= "$goodper%)";
967 } else {
968 $skipmsg .= "?%)";
969 }
970 push @result, $skipmsg;
971 }
89d3b7e2 972 push @result, "\n";
760ac839
LW
973 my $txt = join "", @result;
974 ($txt, $canon);
a0d0e21e
LW
975}
976
b82fa0b7 977=end _private
9c5c68c8 978
b82fa0b7 979=back
d667a7e6 980
b82fa0b7 981=cut
9c5c68c8 982
9c5c68c8 983
b82fa0b7
MS
9841;
985__END__
9c5c68c8
MS
986
987
cb1a09d0
AD
988=head1 EXPORT
989
e8df9912 990C<&runtests> is exported by Test::Harness by default.
cb1a09d0 991
e4fc8a1e 992C<$verbose>, C<$switches> and C<$debug> are exported upon request.
9c5c68c8 993
cb1a09d0
AD
994=head1 DIAGNOSTICS
995
996=over 4
997
998=item C<All tests successful.\nFiles=%d, Tests=%d, %s>
999
1000If all tests are successful some statistics about the performance are
1001printed.
1002
6c31b336
A
1003=item C<FAILED tests %s\n\tFailed %d/%d tests, %.2f%% okay.>
1004
1005For any single script that has failing subtests statistics like the
1006above are printed.
1007
1008=item C<Test returned status %d (wstat %d)>
1009
9c5c68c8
MS
1010Scripts that return a non-zero exit status, both C<$? E<gt>E<gt> 8>
1011and C<$?> are printed in a message similar to the above.
6c31b336
A
1012
1013=item C<Failed 1 test, %.2f%% okay. %s>
cb1a09d0 1014
6c31b336 1015=item C<Failed %d/%d tests, %.2f%% okay. %s>
cb1a09d0
AD
1016
1017If not all tests were successful, the script dies with one of the
1018above messages.
1019
308957f5 1020=item C<FAILED--Further testing stopped: %s>
d667a7e6
A
1021
1022If a single subtest decides that further testing will not make sense,
1023the script dies with this message.
1024
cb1a09d0
AD
1025=back
1026
9b0ceca9
IZ
1027=head1 ENVIRONMENT
1028
37ce32a7
MS
1029=over 4
1030
356733da 1031=item C<HARNESS_ACTIVE>
37ce32a7 1032
356733da
MS
1033Harness sets this before executing the individual tests. This allows
1034the tests to determine if they are being executed through the harness
1035or by any other means.
37ce32a7 1036
356733da 1037=item C<HARNESS_COLUMNS>
9b0ceca9 1038
356733da
MS
1039This value will be used for the width of the terminal. If it is not
1040set then it will default to C<COLUMNS>. If this is not set, it will
1041default to 80. Note that users of Bourne-sh based shells will need to
1042C<export COLUMNS> for this module to use that variable.
0d0c0d42 1043
b82fa0b7 1044=item C<HARNESS_COMPILE_TEST>
9636a016 1045
37ce32a7
MS
1046When true it will make harness attempt to compile the test using
1047C<perlcc> before running it.
1048
b82fa0b7
MS
1049B<NOTE> This currently only works when sitting in the perl source
1050directory!
1051
e4fc8a1e
RGS
1052=item C<HARNESS_DEBUG>
1053
1054If true, Test::Harness will print debugging information about itself as
1055it runs the tests. This is different from C<HARNESS_VERBOSE>, which prints
1056the output from the test being run. Setting C<$Test::Harness::Debug> will
1057override this, or you can use the C<-d> switch in the F<prove> utility.
1058
b82fa0b7 1059=item C<HARNESS_FILELEAK_IN_DIR>
37ce32a7
MS
1060
1061When set to the name of a directory, harness will check after each
1062test whether new files appeared in that directory, and report them as
17a79f5b
IZ
1063
1064 LEAKED FILES: scr.tmp 0 my.db
1065
1066If relative, directory name is with respect to the current directory at
1067the moment runtests() was called. Putting absolute path into
13287dd5 1068C<HARNESS_FILELEAK_IN_DIR> may give more predictable results.
17a79f5b 1069
356733da
MS
1070=item C<HARNESS_IGNORE_EXITCODE>
1071
1072Makes harness ignore the exit status of child processes when defined.
1073
1074=item C<HARNESS_NOTTY>
1075
1076When set to a true value, forces it to behave as though STDOUT were
1077not a console. You may need to set this if you don't want harness to
1078output more frequent progress messages using carriage returns. Some
1079consoles may not handle carriage returns properly (which results in a
1080somewhat messy output).
1081
60af4b93
JH
1082=item C<HARNESS_OK_SLOW>
1083
e4fc8a1e
RGS
1084If true, the C<ok> messages are printed out only every second. This
1085reduces output and may help increase testing speed over slow
1086connections, or with very large numbers of tests.
1087
1088=item C<HARNESS_PERL>
1089
1090Usually your tests will be run by C<$^X>, the currently-executing Perl.
1091However, you may want to have it run by a different executable, such as
1092a threading perl, or a different version.
1093
1094If you're using the F<prove> utility, you can use the C<--perl> switch.
60af4b93 1095
b82fa0b7 1096=item C<HARNESS_PERL_SWITCHES>
37ce32a7
MS
1097
1098Its value will be prepended to the switches used to invoke perl on
b82fa0b7 1099each test. For example, setting C<HARNESS_PERL_SWITCHES> to C<-W> will
37ce32a7
MS
1100run all tests with all warnings enabled.
1101
356733da 1102=item C<HARNESS_VERBOSE>
37ce32a7 1103
356733da 1104If true, Test::Harness will output the verbose results of running
e4fc8a1e
RGS
1105its tests. Setting C<$Test::Harness::verbose> will override this,
1106or you can use the C<-v> switch in the F<prove> utility.
37ce32a7
MS
1107
1108=back
0a931e4a 1109
b82fa0b7
MS
1110=head1 EXAMPLE
1111
1112Here's how Test::Harness tests itself
1113
1114 $ cd ~/src/devel/Test-Harness
1115 $ perl -Mblib -e 'use Test::Harness qw(&runtests $verbose);
1116 $verbose=0; runtests @ARGV;' t/*.t
1117 Using /home/schwern/src/devel/Test-Harness/blib
1118 t/base..............ok
1119 t/nonumbers.........ok
1120 t/ok................ok
1121 t/test-harness......ok
1122 All tests successful.
1123 Files=4, Tests=24, 2 wallclock secs ( 0.61 cusr + 0.41 csys = 1.02 CPU)
f19ae7a7 1124
cb1a09d0
AD
1125=head1 SEE ALSO
1126
42d29bac 1127The included F<prove> utility for running test scripts from the command line,
b82fa0b7
MS
1128L<Test> and L<Test::Simple> for writing test scripts, L<Benchmark> for
1129the underlying timing routines, L<Devel::CoreStack> to generate core
1130dumps from failed tests and L<Devel::Cover> for test coverage
1131analysis.
c07a80fd 1132
1133=head1 AUTHORS
1134
1135Either Tim Bunce or Andreas Koenig, we don't know. What we know for
1136sure is, that it was inspired by Larry Wall's TEST script that came
b876d4a6 1137with perl distributions for ages. Numerous anonymous contributors
cf2ab31a
JH
1138exist. Andreas Koenig held the torch for many years, and then
1139Michael G Schwern.
b82fa0b7 1140
cf2ab31a 1141Current maintainer is Andy Lester C<< <andy@petdance.com> >>.
b82fa0b7 1142
a72fde19
JH
1143=head1 LICENSE
1144
1145This program is free software; you can redistribute it and/or
1146modify it under the same terms as Perl itself.
1147
cf2ab31a 1148See L<http://www.perl.com/perl/misc/Artistic.html>
a72fde19 1149
b82fa0b7
MS
1150=head1 TODO
1151
1152Provide a way of running tests quietly (ie. no printing) for automated
1153validation of tests. This will probably take the form of a version
1154of runtests() which rather than printing its output returns raw data
356733da 1155on the state of the tests. (Partially done in Test::Harness::Straps)
b82fa0b7 1156
cf2ab31a
JH
1157Document the format.
1158
b82fa0b7
MS
1159Fix HARNESS_COMPILE_TEST without breaking its core usage.
1160
1161Figure a way to report test names in the failure summary.
37ce32a7 1162
b82fa0b7 1163Rework the test summary so long test names are not truncated as badly.
308957f5 1164(Partially done with new skip test styles)
b82fa0b7 1165
b82fa0b7
MS
1166Deal with VMS's "not \nok 4\n" mistake.
1167
1168Add option for coverage analysis.
1169
cf2ab31a
JH
1170Trap STDERR.
1171
1172Implement Straps total_results()
1173
1174Remember exit code
1175
1176Completely redo the print summary code.
1177
1178Implement Straps callbacks. (experimentally implemented)
1179
1180Straps->analyze_file() not taint clean, don't know if it can be
1181
1182Fix that damned VMS nit.
1183
1184HARNESS_TODOFAIL to display TODO failures
1185
1186Add a test for verbose.
1187
1188Change internal list of test results to a hash.
1189
1190Fix stats display when there's an overrun.
1191
1192Fix so perls with spaces in the filename work.
1193
b82fa0b7 1194=for _private
cf2ab31a 1195
b82fa0b7
MS
1196Keeping whittling away at _run_all_tests()
1197
1198=for _private
cf2ab31a 1199
b82fa0b7 1200Clean up how the summary is printed. Get rid of those damned formats.
cb1a09d0
AD
1201
1202=head1 BUGS
1203
356733da 1204HARNESS_COMPILE_TEST currently assumes it's run from the Perl source
b82fa0b7
MS
1205directory.
1206
e4fc8a1e
RGS
1207Please use the CPAN bug ticketing system at L<http://rt.cpan.org/>.
1208You can also mail bugs, fixes and enhancements to
1209C<< <bug-test-harness@rt.cpan.org> >>.
1210
1211=head1 AUTHORS
1212
1213Original code by Michael G Schwern, maintained by Andy Lester.
1214
1215=head1 COPYRIGHT
1216
1217Copyright 2003 by Michael G Schwern C<< <schwern@pobox.com> >>,
1218 Andy Lester C<< <andy@petdance.com> >>.
1219
1220This program is free software; you can redistribute it and/or
1221modify it under the same terms as Perl itself.
1222
1223See L<http://www.perl.com/perl/misc/Artistic.html>.
1224
cb1a09d0 1225=cut