Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 549 lines (419 sloc) 14.073 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
# Copyright 2001, Paul Johnson (pjcj@cpan.org)

# This software is free. It is licensed under the same terms as Perl itself.

# The latest version of this software should be available from my homepage:
# http://www.pjcj.net

package Devel::Cover;

use strict;
use warnings;

use DynaLoader ();

use Devel::Cover::DB 0.08;
use Devel::Cover::Inc 0.08;

our @ISA = qw( DynaLoader );
our $VERSION = "0.08";

use B qw( class ppname main_root main_start main_cv svref_2object OPf_KIDS );
# use B::Debug;

my $Covering = 1;

my $DB = "cover_db";
my $Details = 0;
my $Merge = 1;
my @Ignore;
my @Inc;
my $Indent = 0;
my @Select;
my $Summary = 1;

my %Cover;
our $Cv; # gets localised
my @Todo;
my %Done;

BEGIN { @Inc = @Devel::Cover::Inc::Inc }
# BEGIN { $^P = 0x02 | 0x04 | 0x100 }
BEGIN { $^P = 0x04 | 0x100 }

END { report() }

sub import
{
    my $class = shift;
    @Inc = () if "@_" =~ /-inc /;
    while (@_)
    {
        local $_ = shift;
        /^-db/ && do { $DB = shift; next };
        /^-details/ && do { $Details = shift; next };
        /^-merge/ && do { $Merge = shift; next };
        /^-indent/ && do { $Indent = shift; next };
        /^-summary/ && do { $Summary = shift; next };
        /^-ignore/ && do { push @Ignore, shift while $_[0] !~ /^-/; next };
        /^[-+]inc/ && do { push @Inc, shift while $_[0] !~ /^-/; next };
        /^-select/ && do { push @Select, shift while $_[0] !~ /^-/; next };
        warn __PACKAGE__ . ": Unknown option $_ ignored\n";
    }
}

sub cover
{
    ($Covering) = @_;
    set_cover($Covering > 0);
}

sub report
{
    return unless $Covering > 0;
    cover(-1);
    # print "Processing cover data\n@Inc\n";
    $Cv = main_cv;
    get_subs("main");

    # This array should hold the top level of each package, ie all code
    # which is not part of a subroutine. main_root gets us the main
    # root (!), but TODO: something similar for other packages.
    my @roots = (main_root);

    INC:
    while (my ($name, $file) = each %INC)
    {
        # print "test $name => $file\n";
        for (@Select) { next INC if $file !~ /$_/ }
        for (@Ignore) { next INC if $file =~ /$_/ }
        for (@Inc) { next INC if $file =~ /^\Q$_/ }
        # print "use $name => $file\n";
        $name =~ s/\.pm$//;
        $name =~ s/\//::/g;
        push @roots, get_subs($name);
    }
    walk_sub($Cv, main_start);
    @Todo = sort {$a->[0] <=> $b->[0]} @Todo;

    for (@roots)
    {
        walk_topdown($_) unless null($_);
    }

    for my $sub (@Todo)
    {
        my $name = $sub->[1]->SAFENAME;
        # print "$name\n";
        local $Cv = $sub->[1]->CV;
        walk_topdown($Cv->ROOT);
    }

    for my $file (sort keys %Cover)
    {
        for (@Inc) { delete $Cover{$file}, last if $file =~ /^\Q$_/ }
    }

    my $cover = Devel::Cover::DB->new(cover => \%Cover);
    my $existing;
    eval { $existing = Devel::Cover::DB->new(db => $DB) if $Merge };
    $cover->merge($existing) if $existing;
    $cover->indent($Indent);
    $cover->write($DB);
    $cover->print_summary if $Summary;
    $cover->print_details if $Details;
}

my ($F, $L) = ("", 0);
# my $Level = 0;

sub get_location
{
    my ($op) = @_;

    $F = $op->file;
    $L = $op->line;

    # If there's an eval, get the real filename. Enabled from $^P & 0x100.

    ($F, $L) = ($1, $2) if $F =~/^\(eval \d+\)\[(.*):(\d+)\]/;
}

sub walk_topdown
{
    my ($op) = @_;
    my $class = class($op);
    my $cover = coverage()->{pack "I*", $$op};

    # $Level++;

    # Statement coverage.

    if ($class eq "COP")
    {
        get_location($op);
        push @{$Cover{$F}{statement}{$L}}, $cover || 0;
    }
    elsif (!null($op) &&
           $op->name eq "null"
           && ppname($op->targ) eq "pp_nextstate")
    {
        # If the current op is null, but it was nextstate, we can still
        # get at the file and line number, but we need to get dirty.

        $cover = coverage()->{pack "I*", ${$op->sibling}};
        my $o = $op;
        bless $o, "B::COP";
        get_location($o);
        push @{$Cover{$F}{statement}{$L}}, $cover || 0;
    }

    # print " " x ($Level * 2), "$F:$L ", $op->name, ":$class\n";

    # Condition coverage.

    if ($op->can("flags") && ($op->flags & OPf_KIDS))
    {
        my $c;
        for (my $kid = $op->first; $$kid; $kid = $kid->sibling)
        {
            my $cov = walk_topdown($kid);
            push @$c, $cov || 0 if $class eq "LOGOP";
        }
        push @{$Cover{$F}{condition}{$L}}, $c if $c;
    }

    if ($class eq "PMOP" && ${$op->pmreplroot})
    {
        walk_topdown($op->pmreplroot);
    }

    # $Level--;

    $class eq "LISTOP" ? undef : $cover
}

sub find_first
{
    my ($op) = @_;
    my $c = coverage()->{pack "I*", $$op};
    return $c if defined $c;
    for (my $kid = $op->first; $$kid; $kid = $kid->sibling)
    {
        if ($op->can("flags") && ($op->flags & OPf_KIDS))
        {
            my $c = find_first($kid);
            return $c if defined $c;
        }
    }
    undef
}

sub get_subs
{
    my $pack = shift;
    # print "package $pack\n";

    my $stash;
    { no strict 'refs'; $stash = svref_2object(\%{$pack . "::"}) }
    my %stash = $stash->ARRAY;

    my $cv_outside;

    while (my ($key, $val) = each %stash)
    {
        if (class($val) eq "GV" && class($val->CV) ne "SPECIAL")
        {
            next if $Done{$$val}++;

            my $cv = $val->CV;
            todo($val, $cv);
            walk_sub($cv);

            # Trying to find the code in packages which is outside
            # subroutines. TODO: make it work.
            unless ($cv_outside)
            {
                do
                {
                    $cv = $cv->OUTSIDE
                } while class($cv) eq "CV";
                unless (null($cv))
                {
                    # $cv_outside = $cv;
                }
            }
        }
    }

    $cv_outside || ()
}

sub null
{
    class(shift) eq "NULL";
}

sub is_state
{
    my $name = $_[0]->name;
    $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
}

sub todo
{
    my($gv, $cv) = @_;
    my $seq = (!null($cv->START) && is_state($cv->START))
        ? $cv->START->cop_seq
        : 0;
    push @Todo, [$seq, $gv];
}

sub walk_sub
{
    my $cv = shift;
    local $Cv = $cv;
    my $op = $cv->ROOT;
    $op = shift if null($op);
    walk_tree($op) if $op && !null($op);
}

sub walk_tree
{
    my ($op) = @_;

    if ($op->name eq "gv")
    {
        my $gv = class($op) eq "PADOP"
                     ? (($Cv->PADLIST->ARRAY)[1]->ARRAY)[$op->padix]
                     : $op->gv;
        if ($op->next->name eq "entersub")
        {
            return if $Done{$$gv}++;
            return if class($gv->CV) eq "SPECIAL";
            todo($gv, $gv->CV);
            walk_sub($gv->CV);
        }
    }

    if ($op->flags & OPf_KIDS)
    {
        for (my $kid = $op->first; !null($kid); $kid = $kid->sibling)
        {
            walk_tree($kid);
        }
    }
}

bootstrap Devel::Cover $VERSION;

1

__END__

=head1 NAME

Devel::Cover - Code coverage metrics for Perl

=head1 SYNOPSIS

perl -MDevel::Cover prog args
perl -MDevel::Cover=-db,cover_db,-indent,1,-details,1 prog args

=head1 DESCRIPTION

This module provides code coverage metrics for Perl.

If you can't guess by the version number this is an alpha release.

Code coverage data are collected using a plugable runops function which
counts how many times each op is executed. These data are then mapped
back to reality using the B compiler modules.

At the moment, only statement coverage and condition coverage
information is reported. Coverage data for other metrics are collected,
but not reported. Coverage data for some metrics are not yet collected.

You may find that the results don't match your expectations. I would
imagine that at least one of them is wrong.

Requirements:
Perl 5.6.1 or 5.7.1.
The ability to compile XS extensions.

=head1 OPTIONS

-db cover_db - Store results in coverage db (default cover_db).
-details val - Print detailed information iff val is true (default off).
-inc path - Set prefixes of files to ignore (default @INC).
+inc path - Append to prefixes of files to ignore.
-ignore RE - Ignore files matching RE.
-indent indent - Set indentation level to indent. See Data::Dumper for details.
-merge val - Merge databases, for multiple test benches (default on).
-select RE - Only report on files matching RE.
-summary val - Print summary information iff val is true (default on).

=head1 TUTORIAL

Here's part of a message I sent to perl-qa about code coverage metrics.

=head2 1.0 Introduction

It is wise to remember the following quote from Dijkstra, who said:

Testing never proves the absence of faults, it only shows their presence.

In particular, code coverage is just one weapon in the software engineer's
testing arsenal.

Any discussion of code coverage metrics is hampered by the fact that
many authors use different terms to describe the same kind of coverage.
Here, I shall provide only a brief introduction to some of the most
common metrics.

=head2 2.0 Metrics

=head2 2.1 Statement coverage

This is the most basic form of code coverage. A statement is covered if
it is executed. Note that statement != line of code. Multiple
statements on a single line can confuse issues - the reporting if
nothing else.

Where there are sequences of statements without branches it is not
necessary to count the execution of every statement, just one will
suffice, but people often like the count of every line to be reported,
especially in summary statistics. However it is not clear to me that
this is actually useful.

This type of coverage is fairly weak in that even with 100% statement
coverage there may still be serious problems in a program which could be
discovered through other types of metric.

It can be quite difficult to achieve 100% statement coverage. There may
be sections of code designed to deal with error conditions, or rarely
occurring events such as a signal received during a certain section of
code. There may also be code that should never be executed:

if ($param > 20)
{
die "This should never happen!";
}

It can be useful to mark such code in some way and flag an error if it
is executed.

Statement coverage, or something very similar, can be called statement
execution, line, block, basic block or segment coverage. I tend to
favour block coverage which does not attempt to extend its results to
each statement.

=head2 2.2 Branch coverage

The goal of branch coverage is to ensure that whenever a program can
jump, it jumps to all possible destinations. The most simple example is
a complete if statement:

if ($x)
{
print "a";
}
else
{
print "b";
}

In such a simple example statement coverage is as powerful, but branch
coverage should also allow for the case where the else part is missing:

if ($x)
{
print "a";
}

Full coverage is only achieved here if $x is true on one occasion and
false on another.

100% branch coverage implies 100% statement coverage.

Branch coverage is also called decision or all edges coverage.

=head2 2.3 Path coverage

There are classes of errors that branch coverage cannot detect, such as:

$h = undef;
if ($x)
{
$h = { a => 1 };
}
if ($y)
{
print $h->{a};
}

100% branch coverage can be achieved by setting ($x, $y) to (1, 1) and then
to (0, 0). But if we have (0, 1) then things go bang.

The purpose of path coverage is to ensure that all paths through the
program are taken. In any reasonably sized program there will be an
enormous number of paths through the program and so in practice the
paths can be limited to a single subroutine, if the subroutine is not
too big, or simply to two consecutive branches.

In the above example there are four paths which correspond to the truth
table for $x and $y. To achieve 100% path coverage they must all be
taken. Note that missing elses count as paths.

In some cases it may be impossible to achieve 100% path coverage:

a if $x;
b;
c if $x;

50% path coverage is the best you can get here.

Loops also contribute to paths, and pose their own problems which I'll
ignore for now.

100% path coverage implies 100% branch coverage.

Path coverage and some of its close cousins, are also known as
predicate, basis path and LCSAJ (Linear Code Sequence and Jump)
coverage.

=head2 2.4 Expression coverage

When a boolean expression is evaluated it can be useful to ensure that
all the terms in the expression are exercised. For example:

a if $x || $y

The expression should be exercised with ($x, $y) set to (0, 0) (required
for branch coverage), (0, 1) and (1, 0) (to ensure that $x and $y are
independent) and possibly with (1, 1).

Expression coverage gets complicated, and difficult to achieve, as the
expression gets complicated.

Expressions which are not directly a part of a branching construct
should also be covered:

$z = $x || $y;
a if $z;

Expression coverage is also known as condition, condition-decision and
multiple decision coverage.

=head2 3.0 Other considerations

In order to get people to actually use code coverage it needs to be
simple to use. It should also be simple to understand the results and
to rectify any problems thrown up. Finally, if the overhead is too
great it won't get used either.

So there's a basic tutorial on code coverage, or at least my version of
it. Typing a few of these terms into google will probably provide a
basis for future research.

=head1 ACKNOWLEDGEMENTS

Some code and ideas cribbed from:

Devel::OpProf
B::Concise
B::Deparse

=head1 SEE ALSO

Data::Dumper
B

=head1 BUGS

Huh?

=head1 VERSION

Version 0.08 - 18th May 2001

=head1 LICENCE

Copyright 2001, Paul Johnson (pjcj@cpan.org)

This software is free. It is licensed under the same terms as Perl itself.

The latest version of this software should be available from my homepage:
http://www.pjcj.net

=cut
Something went wrong with that request. Please try again.