Thursday, August 16, 2012

Code Coverage for PERL Scripts

Update[10/9/2012] : Sample Code Coverage reports are available here.
manosoftlive.com/blog/cover_db/coverage.html

Code Coverage : Code Coverage is considered as direct measure of quality of code.

For example, Consider we have some 1000 lines of code for some utility, which is thoroughly tested.
We don't know how many exact lines of code has been tested, here comes code coverage handy.

Uses : 
- Helps in determining the test gaps.
- To know what extent of code is covered.
- Creating additional test cases to increase the coverage.

Code Metrics
A large variety of metrics exists, many organisations have formal requirements for structural coverage.

Code Metrics for PERL
Code metrics for other languages like C C++ Java can be easily calculated as the code is instrumented.
Coming to PERL, here the code is interpreted, here is the catch.
There are very few tools to measure code metrics for PERL.
Here I will explain the code coverage for PERL using the Perl module Devel::Cover from CPAN.


Prerequisities
- Unix machine
- PERL installed
- make and gmake to install Devel::Cover


Get/Install Devel::Cover from CPAN
This module can be directly downloaded from CPAN at http://search.cpan.org/~pjcj/Devel-Cover-0.93/
All dependencies should be satisfied before going ahead.
OR

Once you have installed all dependencies, you can see "cover" binary in /usr/bin/ or /usr/local/bin
This is used to calculate coverage and generate HTML reports.

If you have problem with resolving dependencies, try manually installing modules as shown below.



Example and getting code Metrics

Save the below as Sample.pl

Save the below as Sample.pm


If you observer the above code, all i added was one line "use Devel::Cover;" , with which i get code metrics.

Lets see the sample run and results.  

Now a folder is created with name "cover_db", where all the info on runs is saved, now we need to generate reports.

Create HTML reports
"cover" is the utility, with which we can generate HTML reports.
All the HTML reports can be customized.



Once the HTML reports are generated, the work is damn simple, just open the HTML file in browser.
See the details reports generated, hope self readable and self explainable

Update[10/9/2012] : Sample Code Coverage reports are available here.
manosoftlive.com/blog/cover_db/coverage.html


Branch Coverage

Condition Coverage

File Coverage

Subroutine Coverage
Understand More: 
This is just to have quick understanding of PERL code coverage.
To understand more, save the above sample files and play around.
Try running the above code samples with different inputs like
bash# perl Sample.pl 3
bash# perl Sample.pl 2 1
bash# perl Sample.pl 2 2 

Many things can be customized according to your need, see below link to CPAN module

No comments: