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