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