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