t/TEST shouldn't use -M options until we've tested that they work.
[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 map {$_, 1} split /\s+/, $_[0];
208 }
209
210 unless (@ARGV) {
211     # base first, as TEST bails out if that can't run
212     # then comp, to validate that require works
213     # then run, to validate that -M works
214     # then we know we can -MTestInit for everything else, making life simpler
215     foreach my $dir (qw(base comp run cmd io op uni mro)) {
216         _find_tests($dir);
217     }
218     _find_tests("lib") unless $::core;
219     # Config.pm may be broken for make minitest. And this is only a refinement
220     # for skipping tests on non-default builds, so it is allowed to fail.
221     # What we want to to is make a list of extensions which we did not build.
222     my $configsh = '../config.sh';
223     my %skip;
224     if (-f $configsh) {
225         my (%extensions, %known_extensions);
226         open FH, $configsh or die "Can't open $configsh: $!";
227         while (<FH>) {
228             if (/^extensions=['"](.*)['"]$/) {
229                 # Deliberate string interpolation to avoid triggering possible
230                 # $1 resetting bugs.
231                 %extensions = _populate_hash ("$1");
232             }
233             elsif (/^known_extensions=['"](.*)['"]$/) {
234                 %known_extensions = _populate_hash ($1);
235             }
236         }
237         if (%extensions) {
238             if (%known_extensions) {
239                 foreach (keys %known_extensions) {
240                     $skip{$_}++ unless $extensions{$_};
241                 }
242             } else {
243                 warn "No known_extensions line found in $configsh";
244             }
245         } else {
246             warn "No extensions line found in $configsh";
247         }
248     }
249     my $mani = '../MANIFEST';
250     if (open(MANI, $mani)) {
251         while (<MANI>) { # similar code in t/harness
252             if (m!^(ext/(\S+)/+(?:[^/\s]+\.t|test\.pl)|lib/\S+?(?:\.t|test\.pl))\s!) {
253                 my $t = $1;
254                 my $extension = $2;
255                 if (!$::core || $t =~ m!^lib/[a-z]!)
256                 {
257                     if (defined $extension) {
258                         $extension =~ s!/t$!!;
259                         # XXX Do I want to warn that I'm skipping these?
260                         next if $skip{$extension};
261                         my $flat_extension = $extension;
262                         $flat_extension =~ s!-!/!g;
263                         next if $skip{$flat_extension}; # Foo/Bar may live in Foo-Bar
264                     }
265                     my $path = "../$t";
266                     push @ARGV, $path;
267                     $::path_to_name{$path} = $t;
268                 }
269             }
270         }
271         close MANI;
272     } else {
273         warn "$0: cannot open $mani: $!\n";
274     }
275     unless ($::core) {
276         _find_tests('pod');
277         _find_tests('x2p');
278         _find_tests('porting');
279         _find_tests('japh') if $::torture;
280         _find_tests('t/benchmark') if $::benchmark or $ENV{PERL_BENCHMARK};
281     }
282 }
283
284 if ($::deparse) {
285     _testprogs('deparse', '',   @ARGV);
286 }
287 elsif ($::with_utf16) {
288     for my $e (0, 1) {
289         for my $b (0, 1) {
290             print STDERR "# ENDIAN $e BOM $b\n";
291             my @UARGV;
292             for my $a (@ARGV) {
293                 my $u = $a . "." . ($e ? "l" : "b") . "e" . ($b ? "b" : "");
294                 my $f = $e ? "v" : "n";
295                 push @UARGV, $u;
296                 unlink($u);
297                 if (open(A, $a)) {
298                     if (open(U, ">$u")) {
299                         print U pack("$f", 0xFEFF) if $b;
300                         while (<A>) {
301                             print U pack("$f*", unpack("C*", $_));
302                         }
303                         close(U);
304                     }
305                     close(A);
306                 }
307             }
308             _testprogs('perl', '', @UARGV);
309             unlink(@UARGV);
310         }
311     }
312 }
313 else {
314     _testprogs('perl',    '',   @ARGV);
315 }
316
317 sub _testprogs {
318     my ($type, $args, @tests) = @_;
319
320     print <<'EOT' if ($type eq 'deparse');
321 ------------------------------------------------------------------------------
322 TESTING DEPARSER
323 ------------------------------------------------------------------------------
324 EOT
325
326     $::bad_files = 0;
327
328     foreach my $t (@tests) {
329       unless (exists $::path_to_name{$t}) {
330         my $tname = "t/$t";
331         $::path_to_name{$t} = $tname;
332       }
333     }
334     my $maxlen = 0;
335     foreach (@::path_to_name{@tests}) {
336         s/\.\w+\z/./;
337         my $len = length ;
338         $maxlen = $len if $len > $maxlen;
339     }
340     # + 3 : we want three dots between the test name and the "ok"
341     my $dotdotdot = $maxlen + 3 ;
342     my $valgrind = 0;
343     my $total_files = @tests;
344     my $good_files = 0;
345     my $tested_files  = 0;
346     my $totmax = 0;
347     my %failed_tests;
348
349     while (my $test = shift @tests) {
350         my $test_start_time = $show_elapsed_time ? Time::HiRes::time() : 0;
351
352         if ($test =~ /^$/) {
353             next;
354         }
355         if ($type eq 'deparse') {
356             if ($test eq "comp/redef.t") {
357                 # Redefinition happens at compile time
358                 next;
359             }
360             elsif ($test =~ m{lib/Switch/t/}) {
361                 # B::Deparse doesn't support source filtering
362                 next;
363             }
364         }
365         my $te = $::path_to_name{$test} . '.'
366                     x ($dotdotdot - length($::path_to_name{$test}));
367
368         if ($^O ne 'VMS') {  # defer printing on VMS due to piping bug
369             print $te;
370             $te = '';
371         }
372
373         # XXX DAPM %OVER not defined anywhere
374         # $test = $OVER{$test} if exists $OVER{$test};
375
376         my $results = _run_test($test, $type);
377
378         my $failure;
379         my $next = 0;
380         my $seen_leader = 0;
381         my $seen_ok = 0;
382         my $trailing_leader = 0;
383         my $max;
384         my %todo;
385         while (<$results>) {
386             next if /^\s*$/; # skip blank lines
387             if (/^1..$/ && ($^O eq 'VMS')) {
388                 # VMS pipe bug inserts blank lines.
389                 my $l2 = <RESULTS>;
390                 if ($l2 =~ /^\s*$/) {
391                     $l2 = <RESULTS>;
392                 }
393                 $_ = '1..' . $l2;
394             }
395             if ($::verbose) {
396                 print $_;
397             }
398             unless (/^\#/) {
399                 if ($trailing_leader) {
400                     # shouldn't be anything following a postfix 1..n
401                     $failure = 'FAILED--extra output after trailing 1..n';
402                     last;
403                 }
404                 if (/^1\.\.([0-9]+)( todo ([\d ]+))?/) {
405                     if ($seen_leader) {
406                         $failure = 'FAILED--seen duplicate leader';
407                         last;
408                     }
409                     $max = $1;
410                     %todo = map { $_ => 1 } split / /, $3 if $3;
411                     $totmax += $max;
412                     $tested_files++;
413                     if ($seen_ok) {
414                         # 1..n appears at end of file
415                         $trailing_leader = 1;
416                         if ($next != $max) {
417                             $failure = "FAILED--expected $max tests, saw $next";
418                             last;
419                         }
420                     }
421                     else {
422                         $next = 0;
423                     }
424                     $seen_leader = 1;
425                 }
426                 else {
427                     if (/^(not )?ok(?: (\d+))?[^\#]*(\s*\#.*)?/) {
428                         unless ($seen_leader) {
429                             unless ($seen_ok) {
430                                 $next = 0;
431                             }
432                         }
433                         $seen_ok = 1;
434                         $next++;
435                         my($not, $num, $extra, $istodo) = ($1, $2, $3, 0);
436                         $num = $next unless $num;
437
438                         if ($num == $next) {
439
440                             # SKIP is essentially the same as TODO for t/TEST
441                             # this still conforms to TAP:
442                             # http://search.cpan.org/dist/TAP/TAP.pod
443                             $extra and $istodo = $extra =~ /#\s*(?:TODO|SKIP)\b/;
444                             $istodo = 1 if $todo{$num};
445
446                             if( $not && !$istodo ) {
447                                 $failure = "FAILED at test $num";
448                                 last;
449                             }
450                         }
451                         else {
452                             $failure ="FAILED--expected test $next, saw test $num";
453                             last;
454                         }
455                     }
456                     elsif (/^Bail out!\s*(.*)/i) { # magic words
457                         die "FAILED--Further testing stopped" . ($1 ? ": $1\n" : ".\n");
458                     }
459                     else {
460                         # module tests are allowed extra output,
461                         # because Test::Harness allows it
462                         next if $test =~ /^\W*(ext|lib)\b/;
463                         $failure = "FAILED--unexpected output at test $next";
464                         last;
465                     }
466                 }
467             }
468         }
469         close $results;
470
471         if (not defined $failure) {
472             $failure = 'FAILED--no leader found' unless $seen_leader;
473         }
474
475         if ($ENV{PERL_VALGRIND}) {
476             my @valgrind;
477             if (-e $Valgrind_Log) {
478                 if (open(V, $Valgrind_Log)) {
479                     @valgrind = <V>;
480                     close V;
481                 } else {
482                     warn "$0: Failed to open '$Valgrind_Log': $!\n";
483                 }
484             }
485             if ($ENV{VG_OPTS} =~ /cachegrind/) {
486                 if (rename $Valgrind_Log, "$test.valgrind") {
487                     $valgrind++;
488                 } else {
489                     warn "$0: Failed to create '$test.valgrind': $!\n";
490                 }
491             }
492             elsif (@valgrind) {
493                 my $leaks = 0;
494                 my $errors = 0;
495                 for my $i (0..$#valgrind) {
496                     local $_ = $valgrind[$i];
497                     if (/^==\d+== ERROR SUMMARY: (\d+) errors? /) {
498                         $errors += $1;   # there may be multiple error summaries
499                     } elsif (/^==\d+== LEAK SUMMARY:/) {
500                         for my $off (1 .. 4) {
501                             if ($valgrind[$i+$off] =~
502                                 /(?:lost|reachable):\s+\d+ bytes in (\d+) blocks/) {
503                                 $leaks += $1;
504                             }
505                         }
506                     }
507                 }
508                 if ($errors or $leaks) {
509                     if (rename $Valgrind_Log, "$test.valgrind") {
510                         $valgrind++;
511                     } else {
512                         warn "$0: Failed to create '$test.valgrind': $!\n";
513                     }
514                 }
515             } else {
516                 warn "No valgrind output?\n";
517             }
518             if (-e $Valgrind_Log) {
519                 unlink $Valgrind_Log
520                     or warn "$0: Failed to unlink '$Valgrind_Log': $!\n";
521             }
522         }
523         if ($type eq 'deparse') {
524             unlink "./$test.dp";
525         }
526         if ($ENV{PERL_3LOG}) {
527             my $tpp = $test;
528             $tpp =~ s:^\.\./::;
529             $tpp =~ s:/:_:g;
530             $tpp =~ s:\.t$:.3log:;
531             rename("perl.3log", $tpp) ||
532                 die "rename: perl3.log to $tpp: $!\n";
533         }
534         if (not defined $failure and $next != $max) {
535             $failure="FAILED--expected $max tests, saw $next";
536         }
537
538         if( !defined $failure  # don't mask a test failure
539             and $? )
540         {
541             $failure = "FAILED--non-zero wait status: $?";
542         }
543
544         if (defined $failure) {
545             print "${te}$failure\n";
546             $::bad_files++;
547             if ($test =~ /^base/) {
548                 die "Failed a basic test ($test) -- cannot continue.\n";
549             }
550             ++$failed_tests{$test};
551         }
552         else {
553             if ($max) {
554                 my $elapsed;
555                 if ( $show_elapsed_time ) {
556                     $elapsed = sprintf( " %8.0f ms", (Time::HiRes::time() - $test_start_time) * 1000 );
557                 }
558                 else {
559                     $elapsed = "";
560                 }
561                 print "${te}ok$elapsed\n";
562                 $good_files++;
563             }
564             else {
565                 print "${te}skipped\n";
566                 $tested_files -= 1;
567             }
568         }
569     } # while tests
570
571     if ($::bad_files == 0) {
572         if ($good_files) {
573             print "All tests successful.\n";
574             # XXX add mention of 'perlbug -ok' ?
575         }
576         else {
577             die "FAILED--no tests were run for some reason.\n";
578         }
579     }
580     else {
581         my $pct = $tested_files ? sprintf("%.2f", ($tested_files - $::bad_files) / $tested_files * 100) : "0.00";
582         my $s = $::bad_files == 1 ? "" : "s";
583         warn "Failed $::bad_files test$s out of $tested_files, $pct% okay.\n";
584         for my $test ( sort keys %failed_tests ) {
585             print "\t$test\n";
586         }
587         warn <<'SHRDLU_1';
588 ### Since not all tests were successful, you may want to run some of
589 ### them individually and examine any diagnostic messages they produce.
590 ### See the INSTALL document's section on "make test".
591 SHRDLU_1
592         warn <<'SHRDLU_2' if $good_files / $total_files > 0.8;
593 ### You have a good chance to get more information by running
594 ###   ./perl harness
595 ### in the 't' directory since most (>=80%) of the tests succeeded.
596 SHRDLU_2
597         if (eval {require Config; import Config; 1}) {
598             if ($::Config{usedl} && (my $p = $::Config{ldlibpthname})) {
599                 warn <<SHRDLU_3;
600 ### You may have to set your dynamic library search path,
601 ### $p, to point to the build directory:
602 SHRDLU_3
603                 if (exists $ENV{$p} && $ENV{$p} ne '') {
604                     warn <<SHRDLU_4a;
605 ###   setenv $p `pwd`:\$$p; cd t; ./perl harness
606 ###   $p=`pwd`:\$$p; export $p; cd t; ./perl harness
607 ###   export $p=`pwd`:\$$p; cd t; ./perl harness
608 SHRDLU_4a
609                 } else {
610                     warn <<SHRDLU_4b;
611 ###   setenv $p `pwd`; cd t; ./perl harness
612 ###   $p=`pwd`; export $p; cd t; ./perl harness
613 ###   export $p=`pwd`; cd t; ./perl harness
614 SHRDLU_4b
615                 }
616                 warn <<SHRDLU_5;
617 ### for csh-style shells, like tcsh; or for traditional/modern
618 ### Bourne-style shells, like bash, ksh, and zsh, respectively.
619 SHRDLU_5
620             }
621         }
622     }
623     my ($user,$sys,$cuser,$csys) = times;
624     print sprintf("u=%.2f  s=%.2f  cu=%.2f  cs=%.2f  scripts=%d  tests=%d\n",
625         $user,$sys,$cuser,$csys,$tested_files,$totmax);
626     if ($ENV{PERL_VALGRIND}) {
627         my $s = $valgrind == 1 ? '' : 's';
628         print "$valgrind valgrind report$s created.\n", ;
629     }
630 }
631 exit ($::bad_files != 0);
632
633 # ex: set ts=8 sts=4 sw=4 noet: