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