Section 8.6. Keeping Tests and Code Together


8.6. Keeping Tests and Code Together

Putting your tests in a separate file is the usual and traditional way to write a test suite. However, as with documentation, it's easier to keep your tests updated if they're right there alongside your code. The Test::Inline and Pod::Tests modules help you do this.

The weird thing about Test::Inline is that it doesn't actually do anything. It contains no code, only documentation on how to write inline tests. Inline tests are written as ordinary Pod, Perl's plain old documentation format, designed to go alongside the Pod for the subroutines you're implementing.

Test::Inline explains how you can add testing blocks to the documentation of your modules, like so:

     =head2 keywords        my @keywords = keywords($text);     This is a very simple algorithm which removes stopwords from a     summarized version of a text and then counts up what it considers to     be the most important "keywords". The C<keywords> subroutine returns a     list of five keywords in order of relevance.     =begin testing     my @keywords = keywords(scalar `perldoc -t perlxs`);     # reasonable sample document     is_deeply(\@keywords, [qw(perl xsub keyword code timep)],               "Correct keywords returned from perlxs");     =end testing     sub keywords {         ...

With this layout, the documentation section makes it clear what the subroutine should do and then the testing section contains code to test it; keeping the documentation and tests together makes it clearer what ought to be tested. It also means that changes to the functionality can be made in the three important places at the same time: in the code, in the documentation, and in the tests.

This is all well and good, but once we've got these embedded tests, what do we do with them? The Pod::Tests module contains a driver for extracting tests, pod2test:

     % pod2test lib/Keywords.pm t/Keywords-embedded.t     % make test     ...

The Test::Inline::Tutorial documentation provides some information about how to automate the extraction process, as well as tricks to make sure the example code that you give in your Pod works properly.



Advanced Perl Programming
Advanced Perl Programming
ISBN: 0596004567
EAN: 2147483647
Year: 2004
Pages: 107
Authors: Simon Cozens

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net