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