View Christos Tranoris's profile on LinkedIn


Visit The Model Driven Software Network

Who's online

There are currently 0 users and 0 guests online.

Recent comments

Syndicate

Syndicate content

Code coverage in perl

Maybe sometimes you wonder if your unit tests during your TDD cover all your code. Well, in perl there is a module called Devel::Coverage which does what you expect. If it is not installed yet in your system just install it by typing (e.g. in your Linux box):

#sudo apt-get install libdevel-cover-per
#sudo apt-get install libpod-coverage-perl

Create a small perl program, like the following one:

#!/usr/bin/perl
if( $ARGV[0] ) {
print "$ARGV[0] \n";
}else{
print "no arguments \n";
}

Save it for example like test.pl and issue:

#perl -MDevel::Cover=-coverage,statement,branch,
condition test.pl

You will get something like the following results:

---------- ------ ------ ------ ------ 
File stmt bran cond total
---------- ------ ------ ------ ------
test.pl 66.7 50.0 n/a 60.0 
Total 66.7 50.0 n/a 60.0
---------- ------ ------ ------ ------

Until now you got the point. Only 66,7% of our code is executed. Additionally, a directory called cover_db has been created.

Now, issue:

#sudo coverdb

Under the cover_db directory there is a file cover_db/coverage.html This file has nice results of what is going on:

file stmt bran cond total
test.pl 66.7 50.0 n/a 60.0
Total 66.7 50.0 n/a 60.0

Now click on the test.pl link. You will get a view line by line what went wrong:

File Coverage

File: test.pl
Coverage: 60.0%
 

line stmt bran cond code
1       #!/usr/bin/perl
2  
3
1
50
  if( $ARGV[0] )
4
0
    { print "$ARGV[0] \n";
5       }else{
6
1
            print "no arguments \n";
7       }

You see that the if statement covered only 50%.

Now this time get back and run the following:

# perl -MDevel::Cover=-coverage,statement,branch,
condition test.pl myArgument

again you will get the same results as above. Issue now

# sudo cover

and have a look again on coverage.html of test.pl

file stmt bran cond total
test.pl 100.0 100.0 n/a 100.0
Total 100.0 100.0 n/a 100.0

and in the test.pl file:

File: test.pl
Coverage: 100.0%

 

line stmt bran cond code
1       #!/usr/bin/perl
2  
3
2
100
  if( $ARGV[0] )
4
1
    { print "$ARGV[0] \n";
5       }else{
6
1
            print "no arguments \n";
7       }

It's clear now that after 2 runs we actually managed a 100% code coverage and a 100% on the branch condition The nice thing about this html output is that for really large programs the hyperlinks are quite useful. So, at a glance you now immediatelly what went wrong!

Try to introduce code coverage to you TDD programming. Run it occasionally so you know that you have covered everything!

This topic also supplements my other topic on TDD.

Probe further:

Have a look on http://cpan.uwinnipeg.ca/htdocs/Devel-Cover/Devel/Cover.html

 and on wikipedia

Posted in Submitted by tranoris on November 20, 2007 - 00:02.