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