2.2.1. Test::More
Perl ships with a module called Test::More (which is part of the Test-Simple CPAN distribution, which may be more up-to-date there), that allows one to write and run tests using convenient functions. Here's an example for a test script:
#!/usr/bin/env perl use strict; use warnings; use Test::More tests => 7; use Add2 (qw(add)); # TEST is (add(0, 0), 0, "0+0 == 0", ); # TEST is (add(2, 2), 4, "2+2 == 4", ); # TEST is (add(4, 20), 24, "4+20 == 24", ); # TEST is (add(20, 4), 24, "20+4 == 24", ); # TEST is (add(-2, 8), 6, "(-2)+8 == 6", ); # TEST is (add(4, 3.5), 7.5, "4+3.5 == 7.5", ); # TEST is (add(3.5, 3.5), 7, "3.5+3.5 == 7" );
is()
is a Test-More built-in that compares a received result ("have") to an expected result ("want") for exact equivalence. There are also ok()
, which just tests for truth-hood, is_deeply()
which performs a deep comparison of nested data structures, and others.
You may also notice the # TEST
comments - these are Test::Count annotations that allow us to keep track of the number of test assertions that we have declared and update it.
Now, the output of this would be:
1..7 ok 1 - 0+0 == 0 ok 2 - 2+2 == 4 ok 3 - 4+20 == 24 ok 4 - 20+4 == 24 ok 5 - (-2)+8 == 6 ok 6 - 4+3.5 == 7.5 ok 7 - 3.5+3.5 == 7
This is in an output format called TAP - The Test Anything Protocol. There are several TAP parsers, which analyse the output and present a human-friendly summary. For example, we can run the test script above using the prove
command-line utility that ships with perl 5:
$ prove Test-More-1.t Test-More-1.t .. ok All tests successful. Files=1, Tests=7, 0 wallclock secs ( 0.06 usr 0.01 sys + 0.06 cusr 0.01 csys = 0.14 CPU) Result: PASS
For more information refer to the following sources:
- Test::Tutorial on the CPAN
- "Testing with Perl" by Gabor Szabo - comprehensive material of a talk about Perl and testing.
- Test::Count - allows one to keep track of the number of assertions in the test file.
- Test-Run - an alternative test harness under development (with output in colour and other enhancements).
- The Perl Quality Assurance (QA) Project.