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