⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 harness.pm

📁 SinFP是一种新的识别对方计算机操作系统类型的工具
💻 PM
📖 第 1 页 / 共 2 页
字号:
# -*- Mode: cperl; cperl-indent-level: 4 -*-package Test::Harness;require 5.00405;use Test::Harness::Straps;use Test::Harness::Assert;use Exporter;use Benchmark;use Config;use strict;use vars qw(    $VERSION     @ISA @EXPORT @EXPORT_OK     $Verbose $Switches $Debug    $verbose $switches $debug    $Curtest    $Columns     $Timer    $ML $Last_ML_Print    $Strap    $has_time_hires);BEGIN {    eval "use Time::HiRes 'time'";    $has_time_hires = !$@;}=head1 NAMETest::Harness - Run Perl standard test scripts with statistics=head1 VERSIONVersion 2.56=cut$VERSION = "2.56";# Backwards compatibility for exportable variable names.*verbose  = *Verbose;*switches = *Switches;*debug    = *Debug;$ENV{HARNESS_ACTIVE} = 1;$ENV{HARNESS_VERSION} = $VERSION;END {    # For VMS.    delete $ENV{HARNESS_ACTIVE};    delete $ENV{HARNESS_VERSION};}# Some experimental versions of OS/2 build have broken $?my $Ignore_Exitcode = $ENV{HARNESS_IGNORE_EXITCODE};my $Files_In_Dir = $ENV{HARNESS_FILELEAK_IN_DIR};$Strap = Test::Harness::Straps->new;sub strap { return $Strap };@ISA = ('Exporter');@EXPORT    = qw(&runtests);@EXPORT_OK = qw($verbose $switches);$Verbose  = $ENV{HARNESS_VERBOSE} || 0;$Debug    = $ENV{HARNESS_DEBUG} || 0;$Switches = "-w";$Columns  = $ENV{HARNESS_COLUMNS} || $ENV{COLUMNS} || 80;$Columns--;             # Some shells have trouble with a full line of text.$Timer    = $ENV{HARNESS_TIMER} || 0;=head1 SYNOPSIS  use Test::Harness;  runtests(@test_files);=head1 DESCRIPTIONB<STOP!> If all you want to do is write a test script, considerusing Test::Simple.  Test::Harness is the module that reads theoutput from Test::Simple, Test::More and other modules based onTest::Builder.  You don't need to know about Test::Harness to usethose modules.Test::Harness runs tests and expects output from the test in acertain format.  That format is called TAP, the Test AnythingProtocol.  It is defined in L<Test::Harness::TAP>.C<Test::Harness::runtests(@tests)> runs all the testscripts namedas arguments and checks standard output for the expected stringsin TAP format.The F<prove> utility is a thin wrapper around Test::Harness.=head2 Taint modeTest::Harness will honor the C<-T> or C<-t> in the #! line on yourtest files.  So if you begin a test with:    #!perl -Tthe test will be run with taint mode on.=head2 Configuration variables.These variables can be used to configure the behavior ofTest::Harness.  They are exported on request.=over 4=item C<$Test::Harness::Verbose>The package variable C<$Test::Harness::Verbose> is exportable and can beused to let C<runtests()> display the standard output of the scriptwithout altering the behavior otherwise.  The F<prove> utility's C<-v>flag will set this.=item C<$Test::Harness::switches>The package variable C<$Test::Harness::switches> is exportable and can beused to set perl command line options used for running the testscript(s). The default value is C<-w>. It overrides C<HARNESS_SWITCHES>.=item C<$Test::Harness::Timer>If set to true, and C<Time::HiRes> is available, print elapsed secondsafter each test file.=back=head2 FailureWhen tests fail, analyze the summary report:  t/base..............ok  t/nonumbers.........ok  t/ok................ok  t/test-harness......ok  t/waterloo..........dubious          Test returned status 3 (wstat 768, 0x300)  DIED. FAILED tests 1, 3, 5, 7, 9, 11, 13, 15, 17, 19          Failed 10/20 tests, 50.00% okay  Failed Test  Stat Wstat Total Fail  Failed  List of Failed  -----------------------------------------------------------------------  t/waterloo.t    3   768    20   10  50.00%  1 3 5 7 9 11 13 15 17 19  Failed 1/5 test scripts, 80.00% okay. 10/44 subtests failed, 77.27% okay.Everything passed but F<t/waterloo.t>.  It failed 10 of 20 tests andexited with non-zero status indicating something dubious happened.The columns in the summary report mean:=over 4=item B<Failed Test>The test file which failed.=item B<Stat>If the test exited with non-zero, this is its exit status.=item B<Wstat>The wait status of the test.=item B<Total>Total number of tests expected to run.=item B<Fail>Number which failed, either from "not ok" or because they never ran.=item B<Failed>Percentage of the total tests which failed.=item B<List of Failed>A list of the tests which failed.  Successive failures may beabbreviated (ie. 15-20 to indicate that tests 15, 16, 17, 18, 19 and20 failed).=back=head2 FunctionsTest::Harness currently only has one function, here it is.=over 4=item B<runtests>  my $allok = runtests(@test_files);This runs all the given I<@test_files> and divines whether they passedor failed based on their output to STDOUT (details above).  It printsout each individual test which failed along with a summary report anda how long it all took.It returns true if everything was ok.  Otherwise it will C<die()> withone of the messages in the DIAGNOSTICS section.=cutsub runtests {    my(@tests) = @_;    local ($\, $,);    my($tot, $failedtests) = _run_all_tests(@tests);    _show_results($tot, $failedtests);    my $ok = _all_ok($tot);    assert(($ok xor keys %$failedtests),            q{ok status jives with $failedtests});    return $ok;}=begin _private=item B<_all_ok>  my $ok = _all_ok(\%tot);Tells you if this test run is overall successful or not.=cutsub _all_ok {    my($tot) = shift;    return $tot->{bad} == 0 && ($tot->{max} || $tot->{skipped}) ? 1 : 0;}=item B<_globdir>  my @files = _globdir $dir;Returns all the files in a directory.  This is shorthand for backwardscompatibility on systems where C<glob()> doesn't work right.=cutsub _globdir {     opendir DIRH, shift;     my @f = readdir DIRH;     closedir DIRH;     return @f;}=item B<_run_all_tests>  my($total, $failed) = _run_all_tests(@test_files);Runs all the given C<@test_files> (as C<runtests()>) but does itquietly (no report).  $total is a hash ref summary of all the testsrun.  Its keys and values are this:    bonus           Number of individual todo tests unexpectedly passed    max             Number of individual tests ran    ok              Number of individual tests passed    sub_skipped     Number of individual tests skipped    todo            Number of individual todo tests    files           Number of test files ran    good            Number of test files passed    bad             Number of test files failed    tests           Number of test files originally given    skipped         Number of test files skippedIf C<< $total->{bad} == 0 >> and C<< $total->{max} > 0 >>, you'vegot a successful test.$failed is a hash ref of all the test scripts which failed.  Each keyis the name of a test script, each value is another hash representinghow that script failed.  Its keys are these:    name        Name of the test which failed    estat       Script's exit value    wstat       Script's wait status    max         Number of individual tests    failed      Number which failed    percent     Percentage of tests which failed    canon       List of tests which failed (as string).C<$failed> should be empty if everything passed.B<NOTE> Currently this function is still noisy.  I'm working on it.=cut# Turns on autoflush for the handle passedsub _autoflush {    my $flushy_fh = shift;    my $old_fh = select $flushy_fh;    $| = 1;    select $old_fh;}sub _run_all_tests {    my @tests = @_;    _autoflush(\*STDOUT);    _autoflush(\*STDERR);    my(%failedtests);    # Test-wide totals.    my(%tot) = (                bonus    => 0,                max      => 0,                ok       => 0,                files    => 0,                bad      => 0,                good     => 0,                tests    => scalar @tests,                sub_skipped  => 0,                todo     => 0,                skipped  => 0,                bench    => 0,               );    my @dir_files;    @dir_files = _globdir $Files_In_Dir if defined $Files_In_Dir;    my $run_start_time = new Benchmark;    my $width = _leader_width(@tests);    foreach my $tfile (@tests) {        $Last_ML_Print = 0;  # so each test prints at least once        my($leader, $ml) = _mk_leader($tfile, $width);        local $ML = $ml;        print $leader;        $tot{files}++;        $Strap->{_seen_header} = 0;        if ( $Test::Harness::Debug ) {            print "# Running: ", $Strap->_command_line($tfile), "\n";        }        my $test_start_time = $Timer ? time : 0;        my %results = $Strap->analyze_file($tfile) or          do { warn $Strap->{error}, "\n";  next };        my $elapsed;        if ( $Timer ) {            $elapsed = time - $test_start_time;            if ( $has_time_hires ) {                $elapsed = sprintf( " %8.3fs", $elapsed );            }            else {                $elapsed = sprintf( " %8ss", $elapsed ? $elapsed : "<1" );            }        }        else {            $elapsed = "";        }        # state of the current test.        my @failed = grep { !$results{details}[$_-1]{ok} }                     1..@{$results{details}};        my %test = (                    ok          => $results{ok},                    'next'      => $Strap->{'next'},                    max         => $results{max},                    failed      => \@failed,                    bonus       => $results{bonus},                    skipped     => $results{skip},                    skip_reason => $results{skip_reason},                    skip_all    => $Strap->{skip_all},                    ml          => $ml,                   );        $tot{bonus}       += $results{bonus};        $tot{max}         += $results{max};        $tot{ok}          += $results{ok};        $tot{todo}        += $results{todo};        $tot{sub_skipped} += $results{skip};        my($estatus, $wstatus) = @results{qw(exit wait)};        if ($results{passing}) {            # XXX Combine these first two            if ($test{max} and $test{skipped} + $test{bonus}) {                my @msg;                push(@msg, "$test{skipped}/$test{max} skipped: $test{skip_reason}")                    if $test{skipped};                push(@msg, "$test{bonus}/$test{max} unexpectedly succeeded")                    if $test{bonus};                print "$test{ml}ok$elapsed\n        ".join(', ', @msg)."\n";            }            elsif ( $test{max} ) {                print "$test{ml}ok$elapsed\n";            }            elsif ( defined $test{skip_all} and length $test{skip_all} ) {                print "skipped\n        all skipped: $test{skip_all}\n";                $tot{skipped}++;            }            else {                print "skipped\n        all skipped: no reason given\n";                $tot{skipped}++;            }            $tot{good}++;        }        else {            # List unrun tests as failures.            if ($test{'next'} <= $test{max}) {                push @{$test{failed}}, $test{'next'}..$test{max};            }            # List overruns as failures.            else {                my $details = $results{details};                foreach my $overrun ($test{max}+1..@$details) {                    next unless ref $details->[$overrun-1];                    push @{$test{failed}}, $overrun                }            }            if ($wstatus) {                $failedtests{$tfile} = _dubious_return(\%test, \%tot,                                                        $estatus, $wstatus);                $failedtests{$tfile}{name} = $tfile;            }            elsif($results{seen}) {                if (@{$test{failed}} and $test{max}) {                    my ($txt, $canon) = _canonfailed($test{max},$test{skipped},                                                    @{$test{failed}});                    print "$test{ml}$txt";                    $failedtests{$tfile} = { canon   => $canon,                                             max     => $test{max},                                             failed  => scalar @{$test{failed}},                                             name    => $tfile,                                              percent => 100*(scalar @{$test{failed}})/$test{max},                                             estat   => '',                                             wstat   => '',                                           };                }                else {                    print "Don't know which tests failed: got $test{ok} ok, ".                          "expected $test{max}\n";                    $failedtests{$tfile} = { canon   => '??',                                             max     => $test{max},                                             failed  => '??',                                             name    => $tfile,                                              percent => undef,                                             estat   => '',                                              wstat   => '',                                           };                }                $tot{bad}++;            }            else {                print "FAILED before any test output arrived\n";                $tot{bad}++;                $failedtests{$tfile} = { canon       => '??',                                         max         => '??',                                         failed      => '??',                                         name        => $tfile,                                         percent     => undef,                                         estat       => '',                                          wstat       => '',                                       };            }        }        if (defined $Files_In_Dir) {            my @new_dir_files = _globdir $Files_In_Dir;            if (@new_dir_files != @dir_files) {                my %f;                @f{@new_dir_files} = (1) x @new_dir_files;                delete @f{@dir_files};                my @f = sort keys %f;                print "LEAKED FILES: @f\n";                @dir_files = @new_dir_files;            }        }    } # foreach test    $tot{bench} = timediff(new Benchmark, $run_start_time);    $Strap->_restore_PERL5LIB;    return(\%tot, \%failedtests);}=item B<_mk_leader>  my($leader, $ml) = _mk_leader($test_file, $width);Generates the 't/foo........' leader for the given C<$test_file> as wellas a similar version which will overwrite the current line (by use of\r and such).  C<$ml> may be empty if Test::Harness doesn't think you'reon TTY.The C<$width> is the width of the "yada/blah.." string.=cutsub _mk_leader {    my($te, $width) = @_;    chomp($te);    $te =~ s/\.\w+$/./;    if ($^O eq 'VMS') {        $te =~ s/^.*\.t\./\[.t./s;    }    my $leader = "$te" . '.' x ($width - length($te));    my $ml = "";    if ( -t STDOUT and not $ENV{HARNESS_NOTTY} and not $Verbose ) {        $ml = "\r" . (' ' x 77) . "\r$leader"    }    return($leader, $ml);}=item B<_leader_width>  my($width) = _leader_width(@test_files);Calculates how wide the leader should be based on the length of thelongest test name.=cutsub _leader_width {    my $maxlen = 0;    my $maxsuflen = 0;    foreach (@_) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -