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

📄 harness.pm

📁 SinFP是一种新的识别对方计算机操作系统类型的工具
💻 PM
📖 第 1 页 / 共 2 页
字号:
        my $suf    = /\.(\w+)$/ ? $1 : '';        my $len    = length;        my $suflen = length $suf;        $maxlen    = $len    if $len    > $maxlen;        $maxsuflen = $suflen if $suflen > $maxsuflen;    }    # + 3 : we want three dots between the test name and the "ok"    return $maxlen + 3 - $maxsuflen;}sub _show_results {    my($tot, $failedtests) = @_;    my $pct;    my $bonusmsg = _bonusmsg($tot);    if (_all_ok($tot)) {        print "All tests successful$bonusmsg.\n";    }    elsif (!$tot->{tests}){        die "FAILED--no tests were run for some reason.\n";    }    elsif (!$tot->{max}) {        my $blurb = $tot->{tests}==1 ? "script" : "scripts";        die "FAILED--$tot->{tests} test $blurb could be run, ".            "alas--no output ever seen\n";    }    else {        $pct = sprintf("%.2f", $tot->{good} / $tot->{tests} * 100);        my $percent_ok = 100*$tot->{ok}/$tot->{max};        my $subpct = sprintf " %d/%d subtests failed, %.2f%% okay.",                              $tot->{max} - $tot->{ok}, $tot->{max},                               $percent_ok;        my($fmt_top, $fmt) = _create_fmts($failedtests);        # Now write to formats        for my $script (sort keys %$failedtests) {          $Curtest = $failedtests->{$script};          write;        }        if ($tot->{bad}) {            $bonusmsg =~ s/^,\s*//;            print "$bonusmsg.\n" if $bonusmsg;            die "Failed $tot->{bad}/$tot->{tests} test scripts, $pct% okay.".                "$subpct\n";        }    }    printf("Files=%d, Tests=%d, %s\n",           $tot->{files}, $tot->{max}, timestr($tot->{bench}, 'nop'));}my %Handlers = (    header => \&header_handler,    test => \&test_handler,    bailout => \&bailout_handler,);$Strap->{callback} = \&strap_callback;sub strap_callback {    my($self, $line, $type, $totals) = @_;    print $line if $Verbose;    my $meth = $Handlers{$type};    $meth->($self, $line, $type, $totals) if $meth;};sub header_handler {    my($self, $line, $type, $totals) = @_;    warn "Test header seen more than once!\n" if $self->{_seen_header};    $self->{_seen_header}++;    warn "1..M can only appear at the beginning or end of tests\n"      if $totals->{seen} &&          $totals->{max}  < $totals->{seen};};sub test_handler {    my($self, $line, $type, $totals) = @_;    my $curr = $totals->{seen};    my $next = $self->{'next'};    my $max  = $totals->{max};    my $detail = $totals->{details}[-1];    if( $detail->{ok} ) {        _print_ml_less("ok $curr/$max");        if( $detail->{type} eq 'skip' ) {            $totals->{skip_reason} = $detail->{reason}              unless defined $totals->{skip_reason};            $totals->{skip_reason} = 'various reasons'              if $totals->{skip_reason} ne $detail->{reason};        }    }    else {        _print_ml("NOK $curr");    }    if( $curr > $next ) {        print "Test output counter mismatch [test $curr]\n";    }    elsif( $curr < $next ) {        print "Confused test output: test $curr answered after ".              "test ", $next - 1, "\n";    }};sub bailout_handler {    my($self, $line, $type, $totals) = @_;    die "FAILED--Further testing stopped" .      ($self->{bailout_reason} ? ": $self->{bailout_reason}\n" : ".\n");};sub _print_ml {    print join '', $ML, @_ if $ML;}# Print updates only once per second.sub _print_ml_less {    my $now = CORE::time;    if ( $Last_ML_Print != $now ) {        _print_ml(@_);        $Last_ML_Print = $now;    }}sub _bonusmsg {    my($tot) = @_;    my $bonusmsg = '';    $bonusmsg = (" ($tot->{bonus} subtest".($tot->{bonus} > 1 ? 's' : '').               " UNEXPECTEDLY SUCCEEDED)")        if $tot->{bonus};    if ($tot->{skipped}) {        $bonusmsg .= ", $tot->{skipped} test"                     . ($tot->{skipped} != 1 ? 's' : '');        if ($tot->{sub_skipped}) {            $bonusmsg .= " and $tot->{sub_skipped} subtest"                         . ($tot->{sub_skipped} != 1 ? 's' : '');        }        $bonusmsg .= ' skipped';    }    elsif ($tot->{sub_skipped}) {        $bonusmsg .= ", $tot->{sub_skipped} subtest"                     . ($tot->{sub_skipped} != 1 ? 's' : '')                     . " skipped";    }    return $bonusmsg;}# Test program go boom.sub _dubious_return {    my($test, $tot, $estatus, $wstatus) = @_;    my ($failed, $canon, $percent) = ('??', '??');    printf "$test->{ml}dubious\n\tTest returned status $estatus ".           "(wstat %d, 0x%x)\n",           $wstatus,$wstatus;    print "\t\t(VMS status is $estatus)\n" if $^O eq 'VMS';    $tot->{bad}++;    if ($test->{max}) {        if ($test->{'next'} == $test->{max} + 1 and not @{$test->{failed}}) {            print "\tafter all the subtests completed successfully\n";            $percent = 0;            $failed = 0;        # But we do not set $canon!        }        else {            push @{$test->{failed}}, $test->{'next'}..$test->{max};            $failed = @{$test->{failed}};            (my $txt, $canon) = _canonfailed($test->{max},$test->{skipped},@{$test->{failed}});            $percent = 100*(scalar @{$test->{failed}})/$test->{max};            print "DIED. ",$txt;        }    }    return { canon => $canon,  max => $test->{max} || '??',             failed => $failed,              percent => $percent,             estat => $estatus, wstat => $wstatus,           };}sub _create_fmts {    my($failedtests) = @_;    my $failed_str = "Failed Test";    my $middle_str = " Stat Wstat Total Fail  Failed  ";    my $list_str = "List of Failed";    # Figure out our longest name string for formatting purposes.    my $max_namelen = length($failed_str);    foreach my $script (keys %$failedtests) {        my $namelen = length $failedtests->{$script}->{name};        $max_namelen = $namelen if $namelen > $max_namelen;    }    my $list_len = $Columns - length($middle_str) - $max_namelen;    if ($list_len < length($list_str)) {        $list_len = length($list_str);        $max_namelen = $Columns - length($middle_str) - $list_len;        if ($max_namelen < length($failed_str)) {            $max_namelen = length($failed_str);            $Columns = $max_namelen + length($middle_str) + $list_len;        }    }    my $fmt_top = "format STDOUT_TOP =\n"                  . sprintf("%-${max_namelen}s", $failed_str)                  . $middle_str                  . $list_str . "\n"                  . "-" x $Columns                  . "\n.\n";    my $fmt = "format STDOUT =\n"              . "@" . "<" x ($max_namelen - 1)              . "  @>> @>>>> @>>>> @>>> ^##.##%  "              . "^" . "<" x ($list_len - 1) . "\n"              . '{ $Curtest->{name}, $Curtest->{estat},'              . '  $Curtest->{wstat}, $Curtest->{max},'              . '  $Curtest->{failed}, $Curtest->{percent},'              . '  $Curtest->{canon}'              . "\n}\n"              . "~~" . " " x ($Columns - $list_len - 2) . "^"              . "<" x ($list_len - 1) . "\n"              . '$Curtest->{canon}'              . "\n.\n";    eval $fmt_top;    die $@ if $@;    eval $fmt;    die $@ if $@;    return($fmt_top, $fmt);}sub _canonfailed ($$@) {    my($max,$skipped,@failed) = @_;    my %seen;    @failed = sort {$a <=> $b} grep !$seen{$_}++, @failed;    my $failed = @failed;    my @result = ();    my @canon = ();    my $min;    my $last = $min = shift @failed;    my $canon;    if (@failed) {        for (@failed, $failed[-1]) { # don't forget the last one            if ($_ > $last+1 || $_ == $last) {                push @canon, ($min == $last) ? $last : "$min-$last";                $min = $_;            }            $last = $_;        }        local $" = ", ";        push @result, "FAILED tests @canon\n";        $canon = join ' ', @canon;    }    else {        push @result, "FAILED test $last\n";        $canon = $last;    }    push @result, "\tFailed $failed/$max tests, ";    if ($max) {	push @result, sprintf("%.2f",100*(1-$failed/$max)), "% okay";    }    else {	push @result, "?% okay";    }    my $ender = 's' x ($skipped > 1);    if ($skipped) {        my $good = $max - $failed - $skipped;	my $skipmsg = " (less $skipped skipped test$ender: $good okay, ";	if ($max) {	    my $goodper = sprintf("%.2f",100*($good/$max));	    $skipmsg .= "$goodper%)";        }        else {	    $skipmsg .= "?%)";	}	push @result, $skipmsg;    }    push @result, "\n";    my $txt = join "", @result;    ($txt, $canon);}=end _private=back=cut1;__END__=head1 EXPORTC<&runtests> is exported by Test::Harness by default.C<$verbose>, C<$switches> and C<$debug> are exported upon request.=head1 DIAGNOSTICS=over 4=item C<All tests successful.\nFiles=%d,  Tests=%d, %s>If all tests are successful some statistics about the performance areprinted.=item C<FAILED tests %s\n\tFailed %d/%d tests, %.2f%% okay.>For any single script that has failing subtests statistics like theabove are printed.=item C<Test returned status %d (wstat %d)>Scripts that return a non-zero exit status, both C<$? E<gt>E<gt> 8>and C<$?> are printed in a message similar to the above.=item C<Failed 1 test, %.2f%% okay. %s>=item C<Failed %d/%d tests, %.2f%% okay. %s>If not all tests were successful, the script dies with one of theabove messages.=item C<FAILED--Further testing stopped: %s>If a single subtest decides that further testing will not make sense,the script dies with this message.=back=head1 ENVIRONMENT VARIABLES THAT TEST::HARNESS SETSTest::Harness sets these before executing the individual tests.=over 4=item C<HARNESS_ACTIVE>This is set to a true value.  It allows the tests to determine if theyare being executed through the harness or by any other means.=item C<HARNESS_VERSION>This is the version of Test::Harness.=back=head1 ENVIRONMENT VARIABLES THAT AFFECT TEST::HARNESS=over 4=item C<HARNESS_COLUMNS>This value will be used for the width of the terminal. If it is notset then it will default to C<COLUMNS>. If this is not set, it willdefault to 80. Note that users of Bourne-sh based shells will need toC<export COLUMNS> for this module to use that variable.=item C<HARNESS_COMPILE_TEST>When true it will make harness attempt to compile the test usingC<perlcc> before running it.B<NOTE> This currently only works when sitting in the perl sourcedirectory!=item C<HARNESS_DEBUG>If true, Test::Harness will print debugging information about itself asit runs the tests.  This is different from C<HARNESS_VERBOSE>, which printsthe output from the test being run.  Setting C<$Test::Harness::Debug> willoverride this, or you can use the C<-d> switch in the F<prove> utility.=item C<HARNESS_FILELEAK_IN_DIR>When set to the name of a directory, harness will check after eachtest whether new files appeared in that directory, and report them as  LEAKED FILES: scr.tmp 0 my.dbIf relative, directory name is with respect to the current directory atthe moment runtests() was called.  Putting absolute path into C<HARNESS_FILELEAK_IN_DIR> may give more predictable results.=item C<HARNESS_IGNORE_EXITCODE>Makes harness ignore the exit status of child processes when defined.=item C<HARNESS_NOTTY>When set to a true value, forces it to behave as though STDOUT werenot a console.  You may need to set this if you don't want harness tooutput more frequent progress messages using carriage returns.  Someconsoles may not handle carriage returns properly (which results in asomewhat messy output).=item C<HARNESS_PERL>Usually your tests will be run by C<$^X>, the currently-executing Perl.However, you may want to have it run by a different executable, such asa threading perl, or a different version.If you're using the F<prove> utility, you can use the C<--perl> switch.=item C<HARNESS_PERL_SWITCHES>Its value will be prepended to the switches used to invoke perl oneach test.  For example, setting C<HARNESS_PERL_SWITCHES> to C<-W> willrun all tests with all warnings enabled.=item C<HARNESS_VERBOSE>If true, Test::Harness will output the verbose results of runningits tests.  Setting C<$Test::Harness::verbose> will override this,or you can use the C<-v> switch in the F<prove> utility.=back=head1 EXAMPLEHere's how Test::Harness tests itself  $ cd ~/src/devel/Test-Harness  $ perl -Mblib -e 'use Test::Harness qw(&runtests $verbose);    $verbose=0; runtests @ARGV;' t/*.t  Using /home/schwern/src/devel/Test-Harness/blib  t/base..............ok  t/nonumbers.........ok  t/ok................ok  t/test-harness......ok  All tests successful.  Files=4, Tests=24, 2 wallclock secs ( 0.61 cusr + 0.41 csys = 1.02 CPU)=head1 SEE ALSOThe included F<prove> utility for running test scripts from the command line,L<Test> and L<Test::Simple> for writing test scripts, L<Benchmark> forthe underlying timing routines, and L<Devel::Cover> for test coverageanalysis.=head1 TODOProvide a way of running tests quietly (ie. no printing) for automatedvalidation of tests.  This will probably take the form of a versionof runtests() which rather than printing its output returns raw dataon the state of the tests.  (Partially done in Test::Harness::Straps)Document the format.Fix HARNESS_COMPILE_TEST without breaking its core usage.Figure a way to report test names in the failure summary.Rework the test summary so long test names are not truncated as badly.(Partially done with new skip test styles)Add option for coverage analysis.Trap STDERR.Implement Straps total_results()Remember exit codeCompletely redo the print summary code.Implement Straps callbacks.  (experimentally implemented)Straps->analyze_file() not taint clean, don't know if it can beFix that damned VMS nit.HARNESS_TODOFAIL to display TODO failuresAdd a test for verbose.Change internal list of test results to a hash.Fix stats display when there's an overrun.Fix so perls with spaces in the filename work.Keeping whittling away at _run_all_tests()Clean up how the summary is printed.  Get rid of those damned formats.=head1 BUGSHARNESS_COMPILE_TEST currently assumes it's run from the Perl sourcedirectory.Please use the CPAN bug ticketing system at L<http://rt.cpan.org/>.You can also mail bugs, fixes and enhancements to C<< <bug-test-harness >> at C<< rt.cpan.org> >>.=head1 AUTHORSEither Tim Bunce or Andreas Koenig, we don't know. What we know forsure is, that it was inspired by Larry Wall's TEST script that camewith perl distributions for ages. Numerous anonymous contributorsexist.  Andreas Koenig held the torch for many years, and thenMichael G Schwern.Current maintainer is Andy Lester C<< <andy at petdance.com> >>.=head1 COPYRIGHTCopyright 2002-2005by Michael G Schwern C<< <schwern at pobox.com> >>,Andy Lester C<< <andy at petdance.com> >>.This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.See L<http://www.perl.com/perl/misc/Artistic.html>.=cut

⌨️ 快捷键说明

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