Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Design

Perl Testing


Use In Practice

Many tools have been created and integrated with the Perl core to make testing easy. A basic test skeleton can be created with the all-purpose h2xs program that has come with all versions of Perl 5. (If you want to be on the leading edge, the CPAN module ExtUtils::ModuleMaker is better.) h2xs is best used when you're developing a module, because it creates the skeleton for that at the same time. The command:


h2xs -Xan Store::Inventory

creates a tree under a subdirectory Store-Inventory (or Store/Inventory prior to Perl 5.8.1) with a stub for the Store::Inventory module, and a subdirectory t with an initial test file. (Old versions of Perl created a test.pl test file instead.) In fact, as soon as you create a makefile from the skeleton instructions that h2xs made, via:


perl Makefile.PL

you can immediately type make test and see that first test run. You now have a test that passes (it verifies that the module skeleton loads) and you haven't even written any code yet.

The output of make test looks different from that of a standalone test file, however. That's because make test aggregates test files using another key core module, Test::Harness. Reading the output of all the ok() calls to tabulate their successes would be tedious. Test::Harness exports a function, runtests(), used by make test to run all the test files in the t directory. runtests() intercepts their output and tallies the ok/not ok results, presenting a running count and a statistical summary. The output of runtests() looks familiar to anyone who has built Perl from source, because the make test stage of building Perl uses the same testing mechanism. This is where the first line of output from an individual test ("1..N") comes in. This tells runtests() how many tests it should expect to see output for.

You can now develop your module following the Test First principle. First you write a unit test, then you write a method to satisfy the requirement of the test. With a little work the end-to-end tests can be the actual requirements document for the application. Listings Two and Three are a sample test file and module file, respectively.

Listing Two

use Test::More tests => 11;
use Test::Exception;

BEGIN { use_ok('Store::Inventory') };

my $stock = Store::Inventory->new;

isa_ok($stock, 'Store::Inventory');

my $total;
while (<DATA>)
{
  my ($name, $price, $count) = split;
  my $item = Store::Item->new(name => $name, price => $price, count => $count);
  isa_ok($item, 'Store::Item');
  lives_ok { $stock->add_item($item) } 'Added item';
  is($stock->total_assets, $total += $count * $price);
}
lives_ok { $stock->sell('cornflakes') };
is($stock->total_assets, $total -= 2.99);
throws_ok { $stock->sell('hedgehogs') }
          qr/No hedgehogs in stock/, "Can't sell what we don't have";
__END__
cornflakes 2.99 250
bananas    0.39 400

Listing Three

package Store::Inventory;
use strict;
use warnings;

use Class::Struct;
use List::Util 'sum';

struct(items => '%');

sub add_item {
  my ($self, $item) = @_;
  $self->items->{$item->name} = $item;
}
sub total_assets { 
  my $self = shift;
  return sum(map $_->count * $_->price => values %{ $self->items });
}
sub sell {
  my ($self, $name) = @_;
  my $item = $self->items->{$name}
    or die "No $name in stock\n";
  $item->sell;
}
package Store::Item;
use Class::Struct;
struct(name => '$', count => '$', price => '$');
sub sell {
  my $self = shift;
  $self->count($self->count - 1);
}
1;

Segregating tests into multiple files within the t directory can be used either to make the sizes of each file more manageable, or as a guide to partitioning the tests. You could define setup and teardown procedures in each file if you wanted to make each one effectively a single independent unit test; it's up to you. In true Perl fashion, you have enough rope either to hang yourself or to make a lasso.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.