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