This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Remove cpan/Term-UI
[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 current
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 # "not absolute" is the default, as it saves some fakery within TestInit
27 # which can perturb tests, and takes CPU. Working with the upstream author of
28 # any of these, to figure out how to remove them from this list, considered
29 # "a good thing".
30 my %abs = (
31            '../cpan/Archive-Tar' => 1,
32            '../cpan/AutoLoader' => 1,
33            '../cpan/CPAN' => 1,
34            '../cpan/Class-ISA' => 1,
35            '../cpan/Devel-PPPort' => 1,
36            '../cpan/Encode' => 1,
37            '../cpan/ExtUtils-Constant' => 1,
38            '../cpan/ExtUtils-MakeMaker' => 1,
39            '../cpan/File-Fetch' => 1,
40            '../cpan/IPC-Cmd' => 1,
41            '../cpan/IPC-SysV' => 1,
42            '../cpan/Locale-Codes' => 1,
43            '../cpan/Log-Message' => 1,
44            '../cpan/Module-Build' => 1,
45            '../cpan/Module-Load' => 1,
46            '../cpan/Module-Load-Conditional' => 1,
47            '../cpan/Object-Accessor' => 1,
48            '../cpan/Package-Constants' => 1,
49            '../cpan/Parse-CPAN-Meta' => 1,
50            '../cpan/Pod-Simple' => 1,
51            '../cpan/Test-Simple' => 1,
52            '../cpan/podlators' => 1,
53            '../dist/Cwd' => 1,
54            '../dist/ExtUtils-Command' => 1,
55            '../dist/ExtUtils-Install' => 1,
56            '../dist/ExtUtils-Manifest' => 1,
57            '../dist/ExtUtils-ParseXS' => 1,
58            '../dist/Tie-File' => 1,
59           );
60
61 my %temp_no_core =
62     ('../cpan/B-Debug' => 1,
63      '../cpan/Compress-Raw-Bzip2' => 1,
64      '../cpan/Compress-Raw-Zlib' => 1,
65      '../cpan/Devel-PPPort' => 1,
66      '../cpan/Getopt-Long' => 1,
67      '../cpan/IO-Compress' => 1,
68      '../cpan/MIME-Base64' => 1,
69      '../cpan/parent' => 1,
70      '../cpan/Parse-CPAN-Meta' => 1,
71      '../cpan/Pod-Simple' => 1,
72      '../cpan/podlators' => 1,
73      '../cpan/Test-Simple' => 1,
74      '../cpan/Tie-RefHash' => 1,
75      '../cpan/Unicode-Collate' => 1,
76      '../cpan/Unicode-Normalize' => 1,
77     );
78
79 # delete env vars that may influence the results
80 # but allow override via *_TEST env var if wanted
81 # (e.g. PERL5OPT_TEST=-d:NYTProf)
82 my @bad_env_vars = qw(
83     PERL5LIB PERLLIB PERL5OPT
84     PERL_YAML_BACKEND PERL_JSON_BACKEND
85 );
86
87 for my $envname (@bad_env_vars) {
88     my $override = $ENV{"${envname}_TEST"};
89     if (defined $override) {
90         warn "$0: $envname=$override\n";
91         $ENV{$envname} = $override;
92     }
93     else {
94         delete $ENV{$envname};
95     }
96 }
97
98 if ($::do_nothing) {
99     return 1;
100 }
101
102 # Location to put the Valgrind log.
103 our $Valgrind_Log;
104
105 $| = 1;
106
107 # for testing TEST only
108 #BEGIN { require '../lib/strict.pm'; "strict"->import() };
109 #BEGIN { require '../lib/warnings.pm'; "warnings"->import() };
110
111 # remove empty elements due to insertion of empty symbols via "''p1'" syntax
112 @ARGV = grep($_,@ARGV) if $^O eq 'VMS';
113 our $show_elapsed_time = $ENV{HARNESS_TIMER} || 0;
114
115 # Cheesy version of Getopt::Std.  We can't replace it with that, because we
116 # can't rely on require working.
117 {
118     my @argv = ();
119     foreach my $idx (0..$#ARGV) {
120         push( @argv, $ARGV[$idx] ), next unless $ARGV[$idx] =~ /^-(\S+)$/;
121         $::benchmark = 1 if $1 eq 'benchmark';
122         $::core    = 1 if $1 eq 'core';
123         $::verbose = 1 if $1 eq 'v';
124         $::torture = 1 if $1 eq 'torture';
125         $::with_utf8 = 1 if $1 eq 'utf8';
126         $::with_utf16 = 1 if $1 eq 'utf16';
127         $::taintwarn = 1 if $1 eq 'taintwarn';
128         if ($1 =~ /^deparse(,.+)?$/) {
129             $::deparse = 1;
130             $::deparse_opts = $1;
131         }
132     }
133     @ARGV = @argv;
134 }
135
136 chdir 't' if -f 't/TEST';
137 if (-f 'TEST' && -f 'harness' && -d '../lib') {
138     @INC = '../lib';
139 }
140
141 die "You need to run \"make test\" first to set things up.\n"
142   unless -e 'perl' or -e 'perl.exe' or -e 'perl.pm';
143
144 if ($ENV{PERL_3LOG}) { # Tru64 third(1) tool, see perlhack
145     unless (-x 'perl.third') {
146         unless (-x '../perl.third') {
147             die "You need to run \"make perl.third first.\n";
148         }
149         else {
150             print "Symlinking ../perl.third as perl.third...\n";
151             die "Failed to symlink: $!\n"
152                 unless symlink("../perl.third", "perl.third");
153             die "Symlinked but no executable perl.third: $!\n"
154                 unless -x 'perl.third';
155         }
156     }
157 }
158
159 # check leakage for embedders
160 $ENV{PERL_DESTRUCT_LEVEL} = 2 unless exists $ENV{PERL_DESTRUCT_LEVEL};
161 # check existence of all symbols
162 $ENV{PERL_DL_NONLAZY} = 1 unless exists $ENV{PERL_DL_NONLAZY};
163
164 $ENV{EMXSHELL} = 'sh';        # For OS/2
165
166 if ($show_elapsed_time) { require Time::HiRes }
167 my %timings = (); # testname => [@et] pairs if $show_elapsed_time.
168
169 my %skip = (
170             '.' => 1,
171             '..' => 1,
172             'CVS' => 1,
173             'RCS' => 1,
174             'SCCS' => 1,
175             '.svn' => 1,
176            );
177
178 # Roll your own File::Find!
179 sub _find_tests { our @found=(); push @ARGV, _find_files('\.t$', $_[0]) }
180 sub _find_files {
181     my($patt, @dirs) = @_;
182     for my $dir (@dirs) {
183         opendir DIR, $dir or die "Trouble opening $dir: $!";
184         foreach my $f (sort { $a cmp $b } readdir DIR) {
185             next if $skip{$f};
186
187             my $fullpath = "$dir/$f";
188             
189             if (-d $fullpath) {
190                 _find_files($patt, $fullpath);
191             } elsif ($f =~ /$patt/) {
192                 push @found, $fullpath;
193             }
194         }
195     }
196     @found;
197 }
198
199
200 # Scan the text of the test program to find switches and special options
201 # we might need to apply.
202 sub _scan_test {
203     my($test, $type) = @_;
204
205     open(my $script, "<", $test) or die "Can't read $test.\n";
206     my $first_line = <$script>;
207
208     $first_line =~ tr/\0//d if $::with_utf16;
209
210     my $switch = "";
211     if ($first_line =~ /#!.*\bperl.*\s-\w*([tT])/) {
212         $switch = "-$1";
213     } else {
214         if ($::taintwarn) {
215             # not all tests are expected to pass with this option
216             $switch = '-t';
217         } else {
218             $switch = '';
219         }
220     }
221
222     my $file_opts = "";
223     if ($type eq 'deparse') {
224         # Look for #line directives which change the filename
225         while (<$script>) {
226             $file_opts = $file_opts . ",-f$3$4"
227               if /^#\s*line\s+(\d+)\s+((\w+)|"([^"]+)")/;
228         }
229     }
230
231     close $script;
232
233     my $perl = './perl';
234     my $lib  = '../lib';
235     my $run_dir;
236     my $return_dir;
237
238     $test =~ /^(.+)\/[^\/]+/;
239     my $dir = $1;
240     my $testswitch = $dir_to_switch{$dir};
241     if (!defined $testswitch) {
242         if ($test =~ s!^(\.\./(cpan|dist|ext)/[^/]+)/t!t!) {
243             $run_dir = $1;
244             $return_dir = '../../t';
245             $lib = '../../lib';
246             $perl = '../../t/perl';
247             $testswitch = "-I../.. -MTestInit=U2T";
248             if ($2 eq 'cpan' || $2 eq 'dist') {
249                 if($abs{$run_dir}) {
250                     $testswitch = $testswitch . ',A';
251                 }
252                 if ($temp_no_core{$run_dir}) {
253                     $testswitch = $testswitch . ',NC';
254                 }
255             }
256         } elsif ($test =~ m!^\.\./lib!) {
257             $testswitch = '-I.. -MTestInit=U1'; # -T will remove . from @INC
258         } else {
259             $testswitch = '-I.. -MTestInit';  # -T will remove . from @INC
260         }
261     }
262
263     my $utf8 = ($::with_utf8 || $::with_utf16) ? "-I$lib -Mutf8" : '';
264
265     my %options = (
266         perl => $perl,
267         lib => $lib,
268         test => $test,
269         run_dir => $run_dir,
270         return_dir => $return_dir,
271         testswitch => $testswitch,
272         utf8 => $utf8,
273         file => $file_opts,
274         switch => $switch,
275     );
276
277     return \%options;
278 }
279
280 sub _cmd {
281     my($options, $type) = @_;
282
283     my $test = $options->{test};
284
285     my $cmd;
286     if ($type eq 'deparse') {
287         my $perl = "$options->{perl} $options->{testswitch}";
288         my $lib = $options->{lib};
289
290         $cmd = (
291           "$perl $options->{switch} -I$lib -MO=-qq,Deparse,-sv1.,".
292           "-l$::deparse_opts$options->{file} ".
293           "$test > $test.dp ".
294           "&& $perl $options->{switch} -I$lib $test.dp"
295         );
296     }
297     elsif ($type eq 'perl') {
298         my $perl = $options->{perl};
299         my $redir = $^O eq 'VMS' ? '2>&1' : '';
300
301         if ($ENV{PERL_VALGRIND}) {
302             my $perl_supp = $options->{return_dir} ? "$options->{return_dir}/perl.supp" : "perl.supp";
303             my $valgrind_exe = $ENV{VALGRIND} // 'valgrind';
304             my $vg_opts = $ENV{VG_OPTS}
305               // '--log-fd=3 '
306                   . "--suppressions=$perl_supp --leak-check=yes "
307                   . "--leak-resolution=high --show-reachable=yes "
308                   . "--num-callers=50 --track-origins=yes";
309             $perl = "$valgrind_exe $vg_opts $perl";
310             $redir = "3>$Valgrind_Log";
311             if ($options->{run_dir}) {
312                 $Valgrind_Log = "$options->{run_dir}/$Valgrind_Log";
313             }
314         }
315
316         my $args = "$options->{testswitch} $options->{switch} $options->{utf8}";
317         $cmd = $perl . _quote_args($args) . " $test $redir";
318     }
319     return $cmd;
320 }
321
322 sub _before_fork {
323     my ($options) = @_;
324
325     if ($options->{run_dir}) {
326         my $run_dir = $options->{run_dir};
327         chdir $run_dir or die "Can't chdir to '$run_dir': $!";
328     }
329
330     return;
331 }
332
333 sub _after_fork {
334     my ($options) = @_;
335
336     if ($options->{return_dir}) {
337         my $return_dir = $options->{return_dir};
338         chdir $return_dir
339            or die "Can't chdir from '$options->{run_dir}' to '$return_dir': $!";
340     }
341
342     return;
343 }
344
345 sub _run_test {
346     my ($test, $type) = @_;
347
348     my $options = _scan_test($test, $type);
349     # $test might have changed if we're in ext/Foo, so don't use it anymore
350     # from now on. Use $options->{test} instead.
351
352     _before_fork($options);
353
354     my $cmd = _cmd($options, $type);
355
356     open(my $results, "$cmd |") or print "can't run '$cmd': $!.\n";
357
358     _after_fork($options);
359
360     # Our environment may force us to use UTF-8, but we can't be sure that
361     # anything we're reading from will be generating (well formed) UTF-8
362     # This may not be the best way - possibly we should unset ${^OPEN} up
363     # top?
364     binmode $results;
365
366     return $results;
367 }
368
369 sub _quote_args {
370     my ($args) = @_;
371     my $argstring = '';
372
373     foreach (split(/\s+/,$args)) {
374        # In VMS protect with doublequotes because otherwise
375        # DCL will lowercase -- unless already doublequoted.
376        $_ = q(").$_.q(") if ($^O eq 'VMS') && !/^\"/ && length($_) > 0;
377        $argstring = $argstring . ' ' . $_;
378     }
379     return $argstring;
380 }
381
382 sub _populate_hash {
383     return unless defined $_[0];
384     return map {$_, 1} split /\s+/, $_[0];
385 }
386
387 sub _tests_from_manifest {
388     my ($extensions, $known_extensions) = @_;
389     my %skip;
390     my %extensions = _populate_hash($extensions);
391     my %known_extensions = _populate_hash($known_extensions);
392
393     foreach (keys %known_extensions) {
394         $skip{$_} = 1 unless $extensions{$_};
395     }
396
397     my @results;
398     my $mani = '../MANIFEST';
399     if (open(MANI, $mani)) {
400         while (<MANI>) {
401             if (m!^((?:cpan|dist|ext)/(\S+)/+(?:[^/\s]+\.t|test\.pl)|lib/\S+?(?:\.t|test\.pl))\s!) {
402                 my $t = $1;
403                 my $extension = $2;
404                 if (!$::core || $t =~ m!^lib/[a-z]!) {
405                     if (defined $extension) {
406                         $extension =~ s!/t(:?/\S+)*$!!;
407                         # XXX Do I want to warn that I'm skipping these?
408                         next if $skip{$extension};
409                         my $flat_extension = $extension;
410                         $flat_extension =~ s!-!/!g;
411                         next if $skip{$flat_extension}; # Foo/Bar may live in Foo-Bar
412                     }
413                     my $path = "../$t";
414                     push @results, $path;
415                     $::path_to_name{$path} = $t;
416                 }
417             }
418         }
419         close MANI;
420     } else {
421         warn "$0: cannot open $mani: $!\n";
422     }
423     return @results;
424 }
425
426 unless (@ARGV) {
427     # base first, as TEST bails out if that can't run
428     # then comp, to validate that require works
429     # then run, to validate that -M works
430     # then we know we can -MTestInit for everything else, making life simpler
431     foreach my $dir (qw(base comp run cmd io re opbasic op uni mro)) {
432         _find_tests($dir);
433     }
434     unless ($::core) {
435         _find_tests('porting');
436         _find_tests("lib"); 
437     }
438     # Config.pm may be broken for make minitest. And this is only a refinement
439     # for skipping tests on non-default builds, so it is allowed to fail.
440     # What we want to to is make a list of extensions which we did not build.
441     my $configsh = '../config.sh';
442     my ($extensions, $known_extensions);
443     if (-f $configsh) {
444         open FH, $configsh or die "Can't open $configsh: $!";
445         while (<FH>) {
446             if (/^extensions=['"](.*)['"]$/) {
447                 $extensions = $1;
448             }
449             elsif (/^known_extensions=['"](.*)['"]$/) {
450                 $known_extensions = $1;
451             }
452         }
453         if (!defined $known_extensions) {
454             warn "No known_extensions line found in $configsh";
455         }
456         if (!defined $extensions) {
457             warn "No extensions line found in $configsh";
458         }
459     }
460     # The "complex" constructions of list return from a subroutine, and push of
461     # a list, might fail if perl is really hosed, but they aren't needed for
462     # make minitest, and the building of extensions will likely also fail if
463     # something is that badly wrong.
464     push @ARGV, _tests_from_manifest($extensions, $known_extensions);
465     unless ($::core) {
466         _find_tests('x2p');
467         _find_tests('japh') if $::torture;
468         _find_tests('t/benchmark') if $::benchmark or $ENV{PERL_BENCHMARK};
469         _find_tests('bigmem') if $ENV{PERL_TEST_MEMORY};
470     }
471 }
472
473 if ($::deparse) {
474     _testprogs('deparse', '',   @ARGV);
475 }
476 elsif ($::with_utf16) {
477     for my $e (0, 1) {
478         for my $b (0, 1) {
479             print STDERR "# ENDIAN $e BOM $b\n";
480             my @UARGV;
481             for my $a (@ARGV) {
482                 my $u = $a . "." . ($e ? "l" : "b") . "e" . ($b ? "b" : "");
483                 my $f = $e ? "v" : "n";
484                 push @UARGV, $u;
485                 unlink($u);
486                 if (open(A, $a)) {
487                     if (open(U, ">$u")) {
488                         print U pack("$f", 0xFEFF) if $b;
489                         while (<A>) {
490                             print U pack("$f*", unpack("C*", $_));
491                         }
492                         close(U);
493                     }
494                     close(A);
495                 }
496             }
497             _testprogs('perl', '', @UARGV);
498             unlink(@UARGV);
499         }
500     }
501 }
502 else {
503     _testprogs('perl',    '',   @ARGV);
504 }
505
506 sub _testprogs {
507     my ($type, $args, @tests) = @_;
508
509     print <<'EOT' if ($type eq 'deparse');
510 ------------------------------------------------------------------------------
511 TESTING DEPARSER
512 ------------------------------------------------------------------------------
513 EOT
514
515     $::bad_files = 0;
516
517     foreach my $t (@tests) {
518       unless (exists $::path_to_name{$t}) {
519         my $tname = "t/$t";
520         $::path_to_name{$t} = $tname;
521       }
522     }
523     my $maxlen = 0;
524     foreach (@::path_to_name{@tests}) {
525         s/\.\w+\z/ /; # space gives easy doubleclick to select fname
526         my $len = length ;
527         $maxlen = $len if $len > $maxlen;
528     }
529     # + 3 : we want three dots between the test name and the "ok"
530     my $dotdotdot = $maxlen + 3 ;
531     my $grind_ct = 0;           # count of non-empty valgrind reports
532     my $total_files = @tests;
533     my $good_files = 0;
534     my $tested_files  = 0;
535     my $totmax = 0;
536     my %failed_tests;
537     my $toolnm;         # valgrind, cachegrind, perf
538
539     while (my $test = shift @tests) {
540         my ($test_start_time, @starttimes) = 0;
541         if ($show_elapsed_time) {
542             $test_start_time = Time::HiRes::time();
543             # times() reports usage by TEST, but we want usage of each
544             # testprog it calls, so record accumulated times now,
545             # subtract them out afterwards.  Ideally, we'd take times
546             # in BEGIN/END blocks (giving better visibility of self vs
547             # children of each testprog), but that would require some
548             # IPC to send results back here, or a completely different
549             # collection scheme (Storable isn't tuned for incremental use)
550             @starttimes = times;
551         }
552         if ($test =~ /^$/) {
553             next;
554         }
555         if ($type eq 'deparse') {
556             if ($test eq "comp/redef.t") {
557                 # Redefinition happens at compile time
558                 next;
559             }
560             elsif ($test =~ m{lib/Switch/t/}) {
561                 # B::Deparse doesn't support source filtering
562                 next;
563             }
564         }
565         my $te = $::path_to_name{$test} . '.'
566                     x ($dotdotdot - length($::path_to_name{$test})) .' ';
567
568         if ($^O ne 'VMS') {  # defer printing on VMS due to piping bug
569             print $te;
570             $te = '';
571         }
572
573         (local $Valgrind_Log = "$test.valgrind-current") =~ s/^.*\///;
574         my $results = _run_test($test, $type);
575
576         my $failure;
577         my $next = 0;
578         my $seen_leader = 0;
579         my $seen_ok = 0;
580         my $trailing_leader = 0;
581         my $max;
582         my %todo;
583         while (<$results>) {
584             next if /^\s*$/; # skip blank lines
585             if (/^1..$/ && ($^O eq 'VMS')) {
586                 # VMS pipe bug inserts blank lines.
587                 my $l2 = <$results>;
588                 if ($l2 =~ /^\s*$/) {
589                     $l2 = <$results>;
590                 }
591                 $_ = '1..' . $l2;
592             }
593             if ($::verbose) {
594                 print $_;
595             }
596             unless (/^\#/) {
597                 if ($trailing_leader) {
598                     # shouldn't be anything following a postfix 1..n
599                     $failure = 'FAILED--extra output after trailing 1..n';
600                     last;
601                 }
602                 if (/^1\.\.([0-9]+)( todo ([\d ]+))?/) {
603                     if ($seen_leader) {
604                         $failure = 'FAILED--seen duplicate leader';
605                         last;
606                     }
607                     $max = $1;
608                     %todo = map { $_ => 1 } split / /, $3 if $3;
609                     $totmax = $totmax + $max;
610                     $tested_files = $tested_files + 1;
611                     if ($seen_ok) {
612                         # 1..n appears at end of file
613                         $trailing_leader = 1;
614                         if ($next != $max) {
615                             $failure = "FAILED--expected $max tests, saw $next";
616                             last;
617                         }
618                     }
619                     else {
620                         $next = 0;
621                     }
622                     $seen_leader = 1;
623                 }
624                 else {
625                     if (/^(not )?ok(?: (\d+))?[^\#]*(\s*\#.*)?/) {
626                         unless ($seen_leader) {
627                             unless ($seen_ok) {
628                                 $next = 0;
629                             }
630                         }
631                         $seen_ok = 1;
632                         $next = $next + 1;
633                         my($not, $num, $extra, $istodo) = ($1, $2, $3, 0);
634                         $num = $next unless $num;
635
636                         if ($num == $next) {
637
638                             # SKIP is essentially the same as TODO for t/TEST
639                             # this still conforms to TAP:
640                             # http://testanything.org/wiki/index.php/TAP_specification
641                             $extra and $istodo = $extra =~ /#\s*(?:TODO|SKIP)\b/;
642                             $istodo = 1 if $todo{$num};
643
644                             if( $not && !$istodo ) {
645                                 $failure = "FAILED at test $num";
646                                 last;
647                             }
648                         }
649                         else {
650                             $failure ="FAILED--expected test $next, saw test $num";
651                             last;
652                         }
653                     }
654                     elsif (/^Bail out!\s*(.*)/i) { # magic words
655                         die "FAILED--Further testing stopped" . ($1 ? ": $1\n" : ".\n");
656                     }
657                     else {
658                         # module tests are allowed extra output,
659                         # because Test::Harness allows it
660                         next if $test =~ /^\W*(cpan|dist|ext|lib)\b/;
661                         $failure = "FAILED--unexpected output at test $next";
662                         last;
663                     }
664                 }
665             }
666         }
667         close $results;
668
669         if (not defined $failure) {
670             $failure = 'FAILED--no leader found' unless $seen_leader;
671         }
672
673         if ($ENV{PERL_VALGRIND}) {
674             $toolnm = $ENV{VALGRIND};
675             $toolnm =~ s|.*/||;  # keep basename
676             my @valgrind;       # gets content of file
677             if (-e $Valgrind_Log) {
678                 if (open(V, $Valgrind_Log)) {
679                     @valgrind = <V>;
680                     close V;
681                 } else {
682                     warn "$0: Failed to open '$Valgrind_Log': $!\n";
683                 }
684             }
685             if ($ENV{VG_OPTS} =~ /(cachegrind)/ or $toolnm =~ /(perf)/) {
686                 $toolnm = $1;
687                 if ($toolnm eq 'perf') {
688                     # append perfs subcommand, not just stat
689                     my ($sub) = split /\s/, $ENV{VG_OPTS};
690                     $toolnm .= "-$sub";
691                 }
692                 if (rename $Valgrind_Log, "$test.$toolnm") {
693                     $grind_ct++;
694                 } else {
695                     warn "$0: Failed to create '$test.$toolnm': $!\n";
696                 }
697             }
698             elsif (@valgrind) {
699                 my $leaks = 0;
700                 my $errors = 0;
701                 for my $i (0..$#valgrind) {
702                     local $_ = $valgrind[$i];
703                     if (/^==\d+== ERROR SUMMARY: (\d+) errors? /) {
704                         $errors = $errors + $1;   # there may be multiple error summaries
705                     } elsif (/^==\d+== LEAK SUMMARY:/) {
706                         for my $off (1 .. 4) {
707                             if ($valgrind[$i+$off] =~
708                                 /(?:lost|reachable):\s+\d+ bytes in (\d+) blocks/) {
709                                 $leaks = $leaks + $1;
710                             }
711                         }
712                     }
713                 }
714                 if ($errors or $leaks) {
715                     if (rename $Valgrind_Log, "$test.valgrind") {
716                         $grind_ct = $grind_ct + 1;
717                     } else {
718                         warn "$0: Failed to create '$test.valgrind': $!\n";
719                     }
720                 }
721             } else {
722                 warn "No valgrind output?\n";
723             }
724             if (-e $Valgrind_Log) {
725                 unlink $Valgrind_Log
726                     or warn "$0: Failed to unlink '$Valgrind_Log': $!\n";
727             }
728         }
729         if ($type eq 'deparse') {
730             unlink "./$test.dp";
731         }
732         if ($ENV{PERL_3LOG}) {
733             my $tpp = $test;
734             $tpp =~ s:^\.\./::;
735             $tpp =~ s:/:_:g;
736             $tpp =~ s:\.t$:.3log:;
737             rename("perl.3log", $tpp) ||
738                 die "rename: perl3.log to $tpp: $!\n";
739         }
740         if (not defined $failure and $next != $max) {
741             $failure="FAILED--expected $max tests, saw $next";
742         }
743
744         if( !defined $failure  # don't mask a test failure
745             and $? )
746         {
747             $failure = "FAILED--non-zero wait status: $?";
748         }
749
750         if (defined $failure) {
751             print "${te}$failure\n";
752             $::bad_files = $::bad_files + 1;
753             if ($test =~ /^base/) {
754                 die "Failed a basic test ($test) -- cannot continue.\n";
755             }
756             $failed_tests{$test} = 1;
757         }
758         else {
759             if ($max) {
760                 my ($elapsed, $etms) = ("", 0);
761                 if ( $show_elapsed_time ) {
762                     $etms = (Time::HiRes::time() - $test_start_time) * 1000;
763                     $elapsed = sprintf(" %8.0f ms", $etms);
764
765                     my (@endtimes) = times;
766                     $endtimes[$_] -= $starttimes[$_] for 0..$#endtimes;
767                     splice @endtimes, 0, 2;    # drop self/harness times
768                     $_ *= 1000 for @endtimes;  # and scale to ms
769                     $timings{$test} = [$etms,@endtimes];
770                     $elapsed .= sprintf(" %5.0f ms", $_) for @endtimes;
771                 }
772                 print "${te}ok$elapsed\n";
773                 $good_files = $good_files + 1;
774             }
775             else {
776                 print "${te}skipped\n";
777                 $tested_files = $tested_files - 1;
778             }
779         }
780     } # while tests
781
782     if ($::bad_files == 0) {
783         if ($good_files) {
784             print "All tests successful.\n";
785             # XXX add mention of 'perlbug -ok' ?
786         }
787         else {
788             die "FAILED--no tests were run for some reason.\n";
789         }
790     }
791     else {
792         my $pct = $tested_files ? sprintf("%.2f", ($tested_files - $::bad_files) / $tested_files * 100) : "0.00";
793         my $s = $::bad_files == 1 ? "" : "s";
794         warn "Failed $::bad_files test$s out of $tested_files, $pct% okay.\n";
795         for my $test ( sort keys %failed_tests ) {
796             print "\t$test\n";
797         }
798         warn <<'SHRDLU_1';
799 ### Since not all tests were successful, you may want to run some of
800 ### them individually and examine any diagnostic messages they produce.
801 ### See the INSTALL document's section on "make test".
802 SHRDLU_1
803         warn <<'SHRDLU_2' if $good_files / $total_files > 0.8;
804 ### You have a good chance to get more information by running
805 ###   ./perl harness
806 ### in the 't' directory since most (>=80%) of the tests succeeded.
807 SHRDLU_2
808         if (eval {require Config; import Config; 1}) {
809             if ($::Config{usedl} && (my $p = $::Config{ldlibpthname})) {
810                 warn <<SHRDLU_3;
811 ### You may have to set your dynamic library search path,
812 ### $p, to point to the build directory:
813 SHRDLU_3
814                 if (exists $ENV{$p} && $ENV{$p} ne '') {
815                     warn <<SHRDLU_4a;
816 ###   setenv $p `pwd`:\$$p; cd t; ./perl harness
817 ###   $p=`pwd`:\$$p; export $p; cd t; ./perl harness
818 ###   export $p=`pwd`:\$$p; cd t; ./perl harness
819 SHRDLU_4a
820                 } else {
821                     warn <<SHRDLU_4b;
822 ###   setenv $p `pwd`; cd t; ./perl harness
823 ###   $p=`pwd`; export $p; cd t; ./perl harness
824 ###   export $p=`pwd`; cd t; ./perl harness
825 SHRDLU_4b
826                 }
827                 warn <<SHRDLU_5;
828 ### for csh-style shells, like tcsh; or for traditional/modern
829 ### Bourne-style shells, like bash, ksh, and zsh, respectively.
830 SHRDLU_5
831             }
832         }
833     }
834     my ($user,$sys,$cuser,$csys) = times;
835     my $tot = sprintf("u=%.2f  s=%.2f  cu=%.2f  cs=%.2f  scripts=%d  tests=%d",
836                       $user,$sys,$cuser,$csys,$tested_files,$totmax);
837     print "$tot\n";
838     if ($good_files) {
839         if (-d $show_elapsed_time) {
840             # HARNESS_TIMER = <a-directory>.  Save timings etc to
841             # storable file there.  NB: the test cds to ./t/, so
842             # relative path must account for that, ie ../../perf
843             # points to dir next to source tree.
844             require Storable;
845             my @dt = localtime;
846             $dt[5] += 1900; $dt[4] += 1; # fix year, month
847             my $fn = "$show_elapsed_time/".join('-', @dt[5,4,3,2,1]).".ttimes";
848             Storable::store({ perf => \%timings,
849                               gather_conf_platform_info(),
850                               total => $tot,
851                             }, $fn);
852             print "wrote storable file: $fn\n";
853         }
854     }
855     if ($ENV{PERL_VALGRIND}) {
856         my $s = $grind_ct == 1 ? '' : 's';
857         print "$grind_ct valgrind report$s created.\n", ;
858         if ($toolnm eq 'cachegrind') {
859             # cachegrind leaves a lot of cachegrind.out.$pid litter
860             # around the tree, find and delete them
861             unlink _find_files('cachegrind.out.\d+$',
862                              qw ( ../t ../cpan ../ext ../dist/ ));
863         }
864     }
865 }
866 exit ($::bad_files != 0);
867
868 # Collect platform, config data that should allow comparing
869 # performance data between different machines.  With enough data,
870 # and/or clever statistical analysis, it should be possible to
871 # determine the effect of config choices, more memory, etc
872
873 sub gather_conf_platform_info {
874     # currently rather quick & dirty, and subject to change
875     # for both content and format.
876     require Config;
877     my (%conf, @platform) = ();
878     $conf{$_} = $Config::Config{$_} for
879         grep /cc|git|config_arg\d+/, keys %Config::Config;
880     if (-f '/proc/cpuinfo') {
881         open my $fh, '/proc/cpuinfo' or warn "$!: /proc/cpuinfo\n";
882         @platform = grep /name|cpu/, <$fh>;
883         chomp $_ for @platform;
884     }
885     unshift @platform, $^O;
886
887     return (
888         conf => \%conf,
889         platform => {cpu => \@platform,
890                      mem => [ grep s/\s+/ /,
891                               grep chomp, `free` ],
892                      load => [ grep chomp, `uptime` ],
893         },
894         host => (grep chomp, `hostname -f`),
895         version => '0.03', # bump for conf, platform, or data collection changes
896         );
897 }
898
899 # ex: set ts=8 sts=4 sw=4 noet: