3c16180ddce63b8dd8be719310472bf9decd21f3
[p5sagit/p5-mst-13.2.git] / t / TEST
1 #!./perl
2
3 # This is written in a peculiar style, since we're trying to avoid
4 # most of the constructs we'll be testing for.  (This comment is
5 # probably obsolete on the avoidance side, though still currrent
6 # on the peculiarity side.)
7
8 # t/TEST and t/harness need to share code. The logical way to do this would be
9 # to have the common code in a file both require or use. However, t/TEST needs
10 # to still work, to generate test results, even if require isn't working, so
11 # we cannot do that. t/harness has no such restriction, so it is quite
12 # acceptable to have it require t/TEST.
13
14 # In which case, we need to stop t/TEST actually running tests, as all
15 # t/harness needs are its subroutines.
16
17
18 # directories with special sets of test switches
19 my %dir_to_switch =
20     (base => '',
21      comp => '',
22      run => '',
23      '../ext/File-Glob/t' => '-I.. -MTestInit', # FIXME - tests assume t/
24      );
25
26 my %temp_no_core =
27     ('../ext/B-Debug' => 1,
28      '../ext/Compress-Raw-Bzip2' => 1,
29      '../ext/Compress-Raw-Zlib' => 1,
30      '../ext/Devel-PPPort' => 1,
31      '../ext/Encode' => 1,
32      '../ext/IO-Compress' => 1,
33      '../ext/IPC-SysV' => 1,
34      '../ext/MIME-Base64' => 1,
35      '../ext/Time-HiRes' => 1,
36      '../ext/Unicode-Normalize' => 1,
37     );
38
39 if ($::do_nothing) {
40     return 1;
41 }
42
43 # Location to put the Valgrind log.
44 my $Valgrind_Log = 'current.valgrind';
45
46 $| = 1;
47
48 # for testing TEST only
49 #BEGIN { require '../lib/strict.pm'; "strict"->import() };
50 #BEGIN { require '../lib/warnings.pm'; "warnings"->import() };
51
52 delete $ENV{PERL5LIB};
53 delete $ENV{PERLLIB};
54 delete $ENV{PERL5OPT};
55
56 # remove empty elements due to insertion of empty symbols via "''p1'" syntax
57 @ARGV = grep($_,@ARGV) if $^O eq 'VMS';
58 our $show_elapsed_time = $ENV{HARNESS_TIMER} || 0;
59
60 # Cheesy version of Getopt::Std.  We can't replace it with that, because we
61 # can't rely on require working.
62 {
63     my @argv = ();
64     foreach my $idx (0..$#ARGV) {
65         push( @argv, $ARGV[$idx] ), next unless $ARGV[$idx] =~ /^-(\S+)$/;
66         $::benchmark = 1 if $1 eq 'benchmark';
67         $::core    = 1 if $1 eq 'core';
68         $::verbose = 1 if $1 eq 'v';
69         $::torture = 1 if $1 eq 'torture';
70         $::with_utf8 = 1 if $1 eq 'utf8';
71         $::with_utf16 = 1 if $1 eq 'utf16';
72         $::taintwarn = 1 if $1 eq 'taintwarn';
73         $ENV{PERL_CORE_MINITEST} = 1 if $1 eq 'minitest';
74         if ($1 =~ /^deparse(,.+)?$/) {
75             $::deparse = 1;
76             $::deparse_opts = $1;
77         }
78     }
79     @ARGV = @argv;
80 }
81
82 chdir 't' if -f 't/TEST';
83
84 die "You need to run \"make test\" first to set things up.\n"
85   unless -e 'perl' or -e 'perl.exe' or -e 'perl.pm';
86
87 if ($ENV{PERL_3LOG}) { # Tru64 third(1) tool, see perlhack
88     unless (-x 'perl.third') {
89         unless (-x '../perl.third') {
90             die "You need to run \"make perl.third first.\n";
91         }
92         else {
93             print "Symlinking ../perl.third as perl.third...\n";
94             die "Failed to symlink: $!\n"
95                 unless symlink("../perl.third", "perl.third");
96             die "Symlinked but no executable perl.third: $!\n"
97                 unless -x 'perl.third';
98         }
99     }
100 }
101
102 # check leakage for embedders
103 $ENV{PERL_DESTRUCT_LEVEL} = 2 unless exists $ENV{PERL_DESTRUCT_LEVEL};
104
105 $ENV{EMXSHELL} = 'sh';        # For OS/2
106
107 if ($show_elapsed_time) { require Time::HiRes }
108
109 my %skip = (
110             '.' => 1,
111             '..' => 1,
112             'CVS' => 1,
113             'RCS' => 1,
114             'SCCS' => 1,
115             '.svn' => 1,
116            );
117
118 # Roll your own File::Find!
119 sub _find_tests {
120     my($dir) = @_;
121     opendir DIR, $dir or die "Trouble opening $dir: $!";
122     foreach my $f (sort { $a cmp $b } readdir DIR) {
123         next if $skip{$f};
124
125         my $fullpath = "$dir/$f";
126
127         if (-d $fullpath) {
128             _find_tests($fullpath);
129         } elsif ($f =~ /\.t$/) {
130             push @ARGV, $fullpath;
131         }
132     }
133 }
134
135
136 # Scan the text of the test program to find switches and special options
137 # we might need to apply.
138 sub _scan_test {
139     my($test, $type) = @_;
140
141     open(my $script, "<", $test) or die "Can't read $test.\n";
142     my $first_line = <$script>;
143
144     $first_line =~ tr/\0//d if $::with_utf16;
145
146     my $switch = "";
147     if ($first_line =~ /#!.*\bperl.*\s-\w*([tT])/) {
148         $switch = qq{"-$1"};
149     } else {
150         if ($::taintwarn) {
151             # not all tests are expected to pass with this option
152             $switch = '"-t"';
153         } else {
154             $switch = '';
155         }
156     }
157
158     my $file_opts = "";
159     if ($type eq 'deparse') {
160         # Look for #line directives which change the filename
161         while (<$script>) {
162             $file_opts .= ",-f$3$4"
163               if /^#\s*line\s+(\d+)\s+((\w+)|"([^"]+)")/;
164         }
165     }
166
167     return { file => $file_opts, switch => $switch };
168 }
169                   
170 sub _run_test {
171     my($harness, $test, $type) = @_;
172     if (!defined $type) {
173         # To conform to the interface expected by exec in TAP::Harness
174         $type = 'perl';
175     }
176
177     my $options = _scan_test($test, $type);
178     my $return_dir;
179
180     my $perl = './perl';
181     my $lib  = '../lib';
182     $test =~ /^(.+)\/[^\/]+/;
183     my $dir = $1;
184     my $ext_dir;
185
186     my $testswitch = $dir_to_switch{$dir};
187     if (!defined $testswitch) {
188         if ($test =~ s!^(\.\./ext/[^/]+)/t!t!) {
189             $ext_dir = $1;
190             $return_dir = '../../t';
191             $lib = '../../lib';
192             $perl = '../../t/perl';
193             $testswitch = "-I../.. -MTestInit=U2T,A";
194             if ($temp_no_core{$ext_dir}) {
195                 $testswitch = $testswitch . ',NC';
196             }
197             chdir $ext_dir or die "Can't chdir to '$ext_dir': $!";
198         } else {
199             $testswitch = '-I.. -MTestInit';  # -T will remove . from @INC
200         }
201     }
202
203     my $utf8 = $::with_utf8 ? '-I$lib -Mutf8' : '';
204
205     my $results;
206     if ($type eq 'deparse') {
207         my $deparse_cmd =
208           "$perl $testswitch $options->{switch} -I$lib -MO=-qq,Deparse,-sv1.,".
209           "-l$::deparse_opts$options->{file} ".
210           "$test > $test.dp ".
211           "&& $perl $testswitch $options->{switch} -I$lib $test.dp |";
212         open($results, $deparse_cmd)
213           or print "can't deparse '$deparse_cmd': $!.\n";
214     }
215     elsif ($type eq 'perl') {
216         my $redir = $^O eq 'VMS' ? '2>&1' : '';
217
218         if ($ENV{PERL_VALGRIND}) {
219             my $valgrind = $ENV{VALGRIND} // 'valgrind';
220             my $vg_opts = $ENV{VG_OPTS}
221               //  "--suppressions=perl.supp --leak-check=yes "
222                 . "--leak-resolution=high --show-reachable=yes "
223                   . "--num-callers=50"; 
224             $perl = "$valgrind --log-fd=3 $vg_opts $perl";
225             $redir = "3>$Valgrind_Log";
226         }
227
228         my $run = $perl . _quote_args("$testswitch $options->{switch} $utf8")
229           . " $test $redir|";
230         open($results, $run) or print "can't run '$run': $!.\n";
231     }
232
233     if ($return_dir) {
234         chdir $return_dir
235             or die "Can't chdir from '$ext_dir' to '$return_dir': $!";
236     }
237
238     # Our environment may force us to use UTF-8, but we can't be sure that
239     # anything we're reading from will be generating (well formed) UTF-8
240     # This may not be the best way - possibly we should unset ${^OPEN} up
241     # top?
242     binmode $results;
243
244     return $results;
245 }
246
247 sub _quote_args {
248     my ($args) = @_;
249     my $argstring = '';
250
251     foreach (split(/\s+/,$args)) {
252        # In VMS protect with doublequotes because otherwise
253        # DCL will lowercase -- unless already doublequoted.
254        $_ = q(").$_.q(") if ($^O eq 'VMS') && !/^\"/ && length($_) > 0;
255        $argstring .= ' ' . $_;
256     }
257     return $argstring;
258 }
259
260 sub _populate_hash {
261     return unless defined $_[0];
262     return map {$_, 1} split /\s+/, $_[0];
263 }
264
265 sub _tests_from_manifest {
266     my ($extensions, $known_extensions) = @_;
267     my %skip;
268     my %extensions = _populate_hash($extensions);
269     my %known_extensions = _populate_hash($known_extensions);
270
271     foreach (keys %known_extensions) {
272         $skip{$_}++ unless $extensions{$_};
273     }
274
275     my @results;
276     my $mani = '../MANIFEST';
277     if (open(MANI, $mani)) {
278         while (<MANI>) {
279             if (m!^(ext/(\S+)/+(?:[^/\s]+\.t|test\.pl)|lib/\S+?(?:\.t|test\.pl))\s!) {
280                 my $t = $1;
281                 my $extension = $2;
282                 if (!$::core || $t =~ m!^lib/[a-z]!) {
283                     if (defined $extension) {
284                         $extension =~ s!/t$!!;
285                         # XXX Do I want to warn that I'm skipping these?
286                         next if $skip{$extension};
287                         my $flat_extension = $extension;
288                         $flat_extension =~ s!-!/!g;
289                         next if $skip{$flat_extension}; # Foo/Bar may live in Foo-Bar
290                     }
291                     my $path = "../$t";
292                     push @results, $path;
293                     $::path_to_name{$path} = $t;
294                 }
295             }
296         }
297         close MANI;
298     } else {
299         warn "$0: cannot open $mani: $!\n";
300     }
301     return @results;
302 }
303
304 unless (@ARGV) {
305     # base first, as TEST bails out if that can't run
306     # then comp, to validate that require works
307     # then run, to validate that -M works
308     # then we know we can -MTestInit for everything else, making life simpler
309     foreach my $dir (qw(base comp run cmd io op uni mro)) {
310         _find_tests($dir);
311     }
312     _find_tests("lib") unless $::core;
313     # Config.pm may be broken for make minitest. And this is only a refinement
314     # for skipping tests on non-default builds, so it is allowed to fail.
315     # What we want to to is make a list of extensions which we did not build.
316     my $configsh = '../config.sh';
317     my ($extensions, $known_extensions);
318     if (-f $configsh) {
319         open FH, $configsh or die "Can't open $configsh: $!";
320         while (<FH>) {
321             if (/^extensions=['"](.*)['"]$/) {
322                 $extensions = $1;
323             }
324             elsif (/^known_extensions=['"](.*)['"]$/) {
325                 $known_extensions = $1;
326             }
327         }
328         if (!defined $known_extensions) {
329             warn "No known_extensions line found in $configsh";
330         }
331         if (!defined $extensions) {
332             warn "No extensions line found in $configsh";
333         }
334     }
335     # The "complex" constructions of list return from a subroutine, and push of
336     # a list, might fail if perl is really hosed, but they aren't needed for
337     # make minitest, and the building of extensions will likely also fail if
338     # something is that badly wrong.
339     push @ARGV, _tests_from_manifest($extensions, $known_extensions);
340     unless ($::core) {
341         _find_tests('pod');
342         _find_tests('x2p');
343         _find_tests('porting');
344         _find_tests('japh') if $::torture;
345         _find_tests('t/benchmark') if $::benchmark or $ENV{PERL_BENCHMARK};
346     }
347 }
348
349 if ($::deparse) {
350     _testprogs('deparse', '',   @ARGV);
351 }
352 elsif ($::with_utf16) {
353     for my $e (0, 1) {
354         for my $b (0, 1) {
355             print STDERR "# ENDIAN $e BOM $b\n";
356             my @UARGV;
357             for my $a (@ARGV) {
358                 my $u = $a . "." . ($e ? "l" : "b") . "e" . ($b ? "b" : "");
359                 my $f = $e ? "v" : "n";
360                 push @UARGV, $u;
361                 unlink($u);
362                 if (open(A, $a)) {
363                     if (open(U, ">$u")) {
364                         print U pack("$f", 0xFEFF) if $b;
365                         while (<A>) {
366                             print U pack("$f*", unpack("C*", $_));
367                         }
368                         close(U);
369                     }
370                     close(A);
371                 }
372             }
373             _testprogs('perl', '', @UARGV);
374             unlink(@UARGV);
375         }
376     }
377 }
378 else {
379     _testprogs('perl',    '',   @ARGV);
380 }
381
382 sub _testprogs {
383     my ($type, $args, @tests) = @_;
384
385     print <<'EOT' if ($type eq 'deparse');
386 ------------------------------------------------------------------------------
387 TESTING DEPARSER
388 ------------------------------------------------------------------------------
389 EOT
390
391     $::bad_files = 0;
392
393     foreach my $t (@tests) {
394       unless (exists $::path_to_name{$t}) {
395         my $tname = "t/$t";
396         $::path_to_name{$t} = $tname;
397       }
398     }
399     my $maxlen = 0;
400     foreach (@::path_to_name{@tests}) {
401         s/\.\w+\z/./;
402         my $len = length ;
403         $maxlen = $len if $len > $maxlen;
404     }
405     # + 3 : we want three dots between the test name and the "ok"
406     my $dotdotdot = $maxlen + 3 ;
407     my $valgrind = 0;
408     my $total_files = @tests;
409     my $good_files = 0;
410     my $tested_files  = 0;
411     my $totmax = 0;
412     my %failed_tests;
413
414     while (my $test = shift @tests) {
415         my $test_start_time = $show_elapsed_time ? Time::HiRes::time() : 0;
416
417         if ($test =~ /^$/) {
418             next;
419         }
420         if ($type eq 'deparse') {
421             if ($test eq "comp/redef.t") {
422                 # Redefinition happens at compile time
423                 next;
424             }
425             elsif ($test =~ m{lib/Switch/t/}) {
426                 # B::Deparse doesn't support source filtering
427                 next;
428             }
429         }
430         my $te = $::path_to_name{$test} . '.'
431                     x ($dotdotdot - length($::path_to_name{$test}));
432
433         if ($^O ne 'VMS') {  # defer printing on VMS due to piping bug
434             print $te;
435             $te = '';
436         }
437
438         my $results = _run_test(undef, $test, $type);
439
440         my $failure;
441         my $next = 0;
442         my $seen_leader = 0;
443         my $seen_ok = 0;
444         my $trailing_leader = 0;
445         my $max;
446         my %todo;
447         while (<$results>) {
448             next if /^\s*$/; # skip blank lines
449             if (/^1..$/ && ($^O eq 'VMS')) {
450                 # VMS pipe bug inserts blank lines.
451                 my $l2 = <RESULTS>;
452                 if ($l2 =~ /^\s*$/) {
453                     $l2 = <RESULTS>;
454                 }
455                 $_ = '1..' . $l2;
456             }
457             if ($::verbose) {
458                 print $_;
459             }
460             unless (/^\#/) {
461                 if ($trailing_leader) {
462                     # shouldn't be anything following a postfix 1..n
463                     $failure = 'FAILED--extra output after trailing 1..n';
464                     last;
465                 }
466                 if (/^1\.\.([0-9]+)( todo ([\d ]+))?/) {
467                     if ($seen_leader) {
468                         $failure = 'FAILED--seen duplicate leader';
469                         last;
470                     }
471                     $max = $1;
472                     %todo = map { $_ => 1 } split / /, $3 if $3;
473                     $totmax += $max;
474                     $tested_files++;
475                     if ($seen_ok) {
476                         # 1..n appears at end of file
477                         $trailing_leader = 1;
478                         if ($next != $max) {
479                             $failure = "FAILED--expected $max tests, saw $next";
480                             last;
481                         }
482                     }
483                     else {
484                         $next = 0;
485                     }
486                     $seen_leader = 1;
487                 }
488                 else {
489                     if (/^(not )?ok(?: (\d+))?[^\#]*(\s*\#.*)?/) {
490                         unless ($seen_leader) {
491                             unless ($seen_ok) {
492                                 $next = 0;
493                             }
494                         }
495                         $seen_ok = 1;
496                         $next++;
497                         my($not, $num, $extra, $istodo) = ($1, $2, $3, 0);
498                         $num = $next unless $num;
499
500                         if ($num == $next) {
501
502                             # SKIP is essentially the same as TODO for t/TEST
503                             # this still conforms to TAP:
504                             # http://search.cpan.org/dist/TAP/TAP.pod
505                             $extra and $istodo = $extra =~ /#\s*(?:TODO|SKIP)\b/;
506                             $istodo = 1 if $todo{$num};
507
508                             if( $not && !$istodo ) {
509                                 $failure = "FAILED at test $num";
510                                 last;
511                             }
512                         }
513                         else {
514                             $failure ="FAILED--expected test $next, saw test $num";
515                             last;
516                         }
517                     }
518                     elsif (/^Bail out!\s*(.*)/i) { # magic words
519                         die "FAILED--Further testing stopped" . ($1 ? ": $1\n" : ".\n");
520                     }
521                     else {
522                         # module tests are allowed extra output,
523                         # because Test::Harness allows it
524                         next if $test =~ /^\W*(ext|lib)\b/;
525                         $failure = "FAILED--unexpected output at test $next";
526                         last;
527                     }
528                 }
529             }
530         }
531         close $results;
532
533         if (not defined $failure) {
534             $failure = 'FAILED--no leader found' unless $seen_leader;
535         }
536
537         if ($ENV{PERL_VALGRIND}) {
538             my @valgrind;
539             if (-e $Valgrind_Log) {
540                 if (open(V, $Valgrind_Log)) {
541                     @valgrind = <V>;
542                     close V;
543                 } else {
544                     warn "$0: Failed to open '$Valgrind_Log': $!\n";
545                 }
546             }
547             if ($ENV{VG_OPTS} =~ /cachegrind/) {
548                 if (rename $Valgrind_Log, "$test.valgrind") {
549                     $valgrind++;
550                 } else {
551                     warn "$0: Failed to create '$test.valgrind': $!\n";
552                 }
553             }
554             elsif (@valgrind) {
555                 my $leaks = 0;
556                 my $errors = 0;
557                 for my $i (0..$#valgrind) {
558                     local $_ = $valgrind[$i];
559                     if (/^==\d+== ERROR SUMMARY: (\d+) errors? /) {
560                         $errors += $1;   # there may be multiple error summaries
561                     } elsif (/^==\d+== LEAK SUMMARY:/) {
562                         for my $off (1 .. 4) {
563                             if ($valgrind[$i+$off] =~
564                                 /(?:lost|reachable):\s+\d+ bytes in (\d+) blocks/) {
565                                 $leaks += $1;
566                             }
567                         }
568                     }
569                 }
570                 if ($errors or $leaks) {
571                     if (rename $Valgrind_Log, "$test.valgrind") {
572                         $valgrind++;
573                     } else {
574                         warn "$0: Failed to create '$test.valgrind': $!\n";
575                     }
576                 }
577             } else {
578                 warn "No valgrind output?\n";
579             }
580             if (-e $Valgrind_Log) {
581                 unlink $Valgrind_Log
582                     or warn "$0: Failed to unlink '$Valgrind_Log': $!\n";
583             }
584         }
585         if ($type eq 'deparse') {
586             unlink "./$test.dp";
587         }
588         if ($ENV{PERL_3LOG}) {
589             my $tpp = $test;
590             $tpp =~ s:^\.\./::;
591             $tpp =~ s:/:_:g;
592             $tpp =~ s:\.t$:.3log:;
593             rename("perl.3log", $tpp) ||
594                 die "rename: perl3.log to $tpp: $!\n";
595         }
596         if (not defined $failure and $next != $max) {
597             $failure="FAILED--expected $max tests, saw $next";
598         }
599
600         if( !defined $failure  # don't mask a test failure
601             and $? )
602         {
603             $failure = "FAILED--non-zero wait status: $?";
604         }
605
606         if (defined $failure) {
607             print "${te}$failure\n";
608             $::bad_files++;
609             if ($test =~ /^base/) {
610                 die "Failed a basic test ($test) -- cannot continue.\n";
611             }
612             ++$failed_tests{$test};
613         }
614         else {
615             if ($max) {
616                 my $elapsed;
617                 if ( $show_elapsed_time ) {
618                     $elapsed = sprintf( " %8.0f ms", (Time::HiRes::time() - $test_start_time) * 1000 );
619                 }
620                 else {
621                     $elapsed = "";
622                 }
623                 print "${te}ok$elapsed\n";
624                 $good_files++;
625             }
626             else {
627                 print "${te}skipped\n";
628                 $tested_files -= 1;
629             }
630         }
631     } # while tests
632
633     if ($::bad_files == 0) {
634         if ($good_files) {
635             print "All tests successful.\n";
636             # XXX add mention of 'perlbug -ok' ?
637         }
638         else {
639             die "FAILED--no tests were run for some reason.\n";
640         }
641     }
642     else {
643         my $pct = $tested_files ? sprintf("%.2f", ($tested_files - $::bad_files) / $tested_files * 100) : "0.00";
644         my $s = $::bad_files == 1 ? "" : "s";
645         warn "Failed $::bad_files test$s out of $tested_files, $pct% okay.\n";
646         for my $test ( sort keys %failed_tests ) {
647             print "\t$test\n";
648         }
649         warn <<'SHRDLU_1';
650 ### Since not all tests were successful, you may want to run some of
651 ### them individually and examine any diagnostic messages they produce.
652 ### See the INSTALL document's section on "make test".
653 SHRDLU_1
654         warn <<'SHRDLU_2' if $good_files / $total_files > 0.8;
655 ### You have a good chance to get more information by running
656 ###   ./perl harness
657 ### in the 't' directory since most (>=80%) of the tests succeeded.
658 SHRDLU_2
659         if (eval {require Config; import Config; 1}) {
660             if ($::Config{usedl} && (my $p = $::Config{ldlibpthname})) {
661                 warn <<SHRDLU_3;
662 ### You may have to set your dynamic library search path,
663 ### $p, to point to the build directory:
664 SHRDLU_3
665                 if (exists $ENV{$p} && $ENV{$p} ne '') {
666                     warn <<SHRDLU_4a;
667 ###   setenv $p `pwd`:\$$p; cd t; ./perl harness
668 ###   $p=`pwd`:\$$p; export $p; cd t; ./perl harness
669 ###   export $p=`pwd`:\$$p; cd t; ./perl harness
670 SHRDLU_4a
671                 } else {
672                     warn <<SHRDLU_4b;
673 ###   setenv $p `pwd`; cd t; ./perl harness
674 ###   $p=`pwd`; export $p; cd t; ./perl harness
675 ###   export $p=`pwd`; cd t; ./perl harness
676 SHRDLU_4b
677                 }
678                 warn <<SHRDLU_5;
679 ### for csh-style shells, like tcsh; or for traditional/modern
680 ### Bourne-style shells, like bash, ksh, and zsh, respectively.
681 SHRDLU_5
682             }
683         }
684     }
685     my ($user,$sys,$cuser,$csys) = times;
686     print sprintf("u=%.2f  s=%.2f  cu=%.2f  cs=%.2f  scripts=%d  tests=%d\n",
687         $user,$sys,$cuser,$csys,$tested_files,$totmax);
688     if ($ENV{PERL_VALGRIND}) {
689         my $s = $valgrind == 1 ? '' : 's';
690         print "$valgrind valgrind report$s created.\n", ;
691     }
692 }
693 exit ($::bad_files != 0);
694
695 # ex: set ts=8 sts=4 sw=4 noet: