Perl version

Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

Test

Perl 5 version 8.8 documentation
Recently read

Test

NAME

Test - provides a simple framework for writing test scripts

SYNOPSIS

  1. use strict;
  2. use Test;
  3. # use a BEGIN block so we print our plan before MyModule is loaded
  4. BEGIN { plan tests => 14, todo => [3,4] }
  5. # load your module...
  6. use MyModule;
  7. # Helpful notes. All note-lines must start with a "#".
  8. print "# I'm testing MyModule version $MyModule::VERSION\n";
  9. ok(0); # failure
  10. ok(1); # success
  11. ok(0); # ok, expected failure (see todo list, above)
  12. ok(1); # surprise success!
  13. ok(0,1); # failure: '0' ne '1'
  14. ok('broke','fixed'); # failure: 'broke' ne 'fixed'
  15. ok('fixed','fixed'); # success: 'fixed' eq 'fixed'
  16. ok('fixed',qr/x/); # success: 'fixed' =~ qr/x/
  17. ok(sub { 1+1 }, 2); # success: '2' eq '2'
  18. ok(sub { 1+1 }, 3); # failure: '2' ne '3'
  19. my @list = (0,0);
  20. ok @list, 3, "\@list=".join(',',@list); #extra notes
  21. ok 'segmentation fault', '/(?i)success/'; #regex match
  22. skip(
  23. $^O =~ m/MSWin/ ? "Skip if MSWin" : 0, # whether to skip
  24. $foo, $bar # arguments just like for ok(...)
  25. );
  26. skip(
  27. $^O =~ m/MSWin/ ? 0 : "Skip unless MSWin", # whether to skip
  28. $foo, $bar # arguments just like for ok(...)
  29. );

DESCRIPTION

This module simplifies the task of writing test files for Perl modules, such that their output is in the format that Test::Harness expects to see.

QUICK START GUIDE

To write a test for your new (and probably not even done) module, create a new file called t/test.t (in a new t directory). If you have multiple test files, to test the "foo", "bar", and "baz" feature sets, then feel free to call your files t/foo.t, t/bar.t, and t/baz.t

Functions

This module defines three public functions, plan(...) , ok(...) , and skip(...) . By default, all three are exported by the use Test; statement.

  • plan(...)
    1. BEGIN { plan %theplan; }

    This should be the first thing you call in your test script. It declares your testing plan, how many there will be, if any of them should be allowed to fail, and so on.

    Typical usage is just:

    1. use Test;
    2. BEGIN { plan tests => 23 }

    These are the things that you can put in the parameters to plan:

    • tests => <i>number</i>

      The number of tests in your script. This means all ok() and skip() calls.

    • todo => [<i>1,5,14</i>]

      A reference to a list of tests which are allowed to fail. See TODO TESTS.

    • onfail => sub { ... }
    • onfail => \&some_sub

      A subroutine reference to be run at the end of the test script, if any of the tests fail. See ONFAIL.

    You must call plan(...) once and only once. You should call it in a BEGIN {...} block, like so:

    1. BEGIN { plan tests => 23 }
  • _to_value
    1. my $value = _to_value($input);

    Converts an C parameter to its value. Typically this just means running it, if it's a code reference. You should run all inputted values through this.

  1. ok(1 + 1 == 2);
  2. ok($have, $expect);
  3. ok($have, $expect, $diagnostics);

This function is the reason for C's existence. It's the basic function that handles printing "C" or "C", along with the current test number. (That's what C wants to see.)

In its most basic usage, C simply takes a single scalar expression. If its value is true, the test passes; if false, the test fails. Examples:

  1. # Examples of ok(scalar)
  2. ok( 1 + 1 == 2 ); # ok if 1 + 1 == 2
  3. ok( $foo =~ /bar/ ); # ok if $foo contains 'bar'
  4. ok( baz($x + $y) eq 'Armondo' ); # ok if baz($x + $y) returns
  5. # 'Armondo'
  6. ok( @a == @b ); # ok if @a and @b are the same length

The expression is evaluated in scalar context. So the following will work:

  1. ok( @stuff ); # ok if @stuff has any elements
  2. ok( !grep !defined $_, @stuff ); # ok if everything in @stuff is
  3. # defined.

A special case is if the expression is a subroutine reference (in either C syntax or C<\&foo> syntax). In that case, it is executed and its value (true or false) determines if the test passes or fails. For example,

  1. ok( sub { # See whether sleep works at least passably
  2. my $start_time = time;
  3. sleep 5;
  4. time() - $start_time >= 4
  5. });

In its two-argument form, C, I)> compares the two scalar values to see if they match. They match if both are undefined, or if I is a regex that matches I, or if they compare equal with C.

  1. # Example of ok(scalar, scalar)
  2. ok( "this", "that" ); # not ok, 'this' ne 'that'
  3. ok( "", undef ); # not ok, "" is defined

The second argument is considered a regex if it is either a regex object or a string that looks like a regex. Regex objects are constructed with the qr// operator in recent versions of perl. A string is considered to look like a regex if its first and last characters are "/", or if the first character is "m" and its second and last characters are both the same non-alphanumeric non-whitespace character. These regexp

Regex examples:

  1. ok( 'JaffO', '/Jaff/' ); # ok, 'JaffO' =~ /Jaff/
  2. ok( 'JaffO', 'm|Jaff|' ); # ok, 'JaffO' =~ m|Jaff|
  3. ok( 'JaffO', qr/Jaff/ ); # ok, 'JaffO' =~ qr/Jaff/;
  4. ok( 'JaffO', '/(?i)jaff/ ); # ok, 'JaffO' =~ /jaff/i;

If either (or both!) is a subroutine reference, it is run and used as the value for comparing. For example:

  1. ok sub {
  2. open(OUT, ">x.dat") || die $!;
  3. print OUT "\x{e000}";
  4. close OUT;
  5. my $bytecount = -s 'x.dat';
  6. unlink 'x.dat' or warn "Can't unlink : $!";
  7. return $bytecount;
  8. },
  9. 4
  10. ;

The above test passes two values to C -- the first a coderef, and the second is the number 4. Before C compares them, it calls the coderef, and uses its return value as the real value of this parameter. Assuming that C<$bytecount> returns 4, C ends up testing C<4 eq 4>. Since that's true, this test passes.

Finally, you can append an optional third argument, in C,I, I)>, where I is a string value that will be printed if the test fails. This should be some useful information about the test, pertaining to why it failed, and/or a description of the test. For example:

  1. ok( grep($_ eq 'something unique', @stuff), 1,
  2. "Something that should be unique isn't!\n".
  3. '@stuff = '.join ', ', @stuff
  4. );

Unfortunately, a note cannot be used with the single argument style of C. That is, if you try C, I)>, then C will interpret this as C, I)>, and probably end up testing C eq I> -- and that's not what you want!

All of the above special cases can occasionally cause some problems. See L.

This is used for tests that under some conditions can be skipped. It's basically equivalent to:

  1. if( $skip_if_true ) {
  2. ok(1);
  3. } else {
  4. ok( args... );
  5. }

...except that the C emits not just "C>" but actually "C # I>".

The arguments after the I are what is fed to C if this test isn't skipped.

Example usage:

  1. my $if_MSWin =
  2. $^O =~ m/MSWin/ ? 'Skip if under MSWin' : '';
  3. # A test to be skipped if under MSWin (i.e., run except under MSWin)
  4. skip($if_MSWin, thing($foo), thing($bar) );

Or, going the other way:

  1. my $unless_MSWin =
  2. $^O =~ m/MSWin/ ? '' : 'Skip unless under MSWin';
  3. # A test to be skipped unless under MSWin (i.e., run only under MSWin)
  4. skip($unless_MSWin, thing($foo), thing($bar) );

The tricky thing to remember is that the first parameter is true if you want to I the test, not I it; and it also doubles as a note about why it's being skipped. So in the first codeblock above, read the code as "skip if MSWin -- (otherwise) test whether C is C" or for the second case, "skip unless MSWin...".

Also, when your I string is true, it really should (for backwards compatibility with older Test.pm versions) start with the string "Skip", as shown in the above examples.

Note that in the above cases, C and C I evaluated -- but as long as the C is true, then we C just tosses out their value (i.e., not bothering to treat them like values to C. But if you need to I eval the arguments when skipping the test, use this format:

  1. skip( $unless_MSWin,
  2. sub {
  3. # This code returns true if the test passes.
  4. # (But it doesn't even get called if the test is skipped.)
  5. thing($foo) eq thing($bar)
  6. }
  7. );

or even this, which is basically equivalent:

  1. skip( $unless_MSWin,
  2. sub { thing($foo) }, sub { thing($bar) }
  3. );

That is, both are like this:

  1. if( $unless_MSWin ) {
  2. ok(1); # but it actually appends "# $unless_MSWin"
  3. # so that Test::Harness can tell it's a skip
  4. } else {
  5. # Not skipping, so actually call and evaluate...
  6. ok( sub { thing($foo) }, sub { thing($bar) } );
  7. }

TEST TYPES

  • NORMAL TESTS

    These tests are expected to succeed. Usually, most or all of your tests are in this category. If a normal test doesn't succeed, then that means that something is I.

  • SKIPPED TESTS

    The C function is for tests that might or might not be possible to run, depending on the availability of platform-specific features. The first argument should evaluate to true (think "yes, please skip") if the required feature is I available. After the first argument, C works exactly the same way as C does.

  • TODO TESTS

    TODO tests are designed for maintaining an B. These tests are I If a TODO test does succeed, then the feature in question shouldn't be on the TODO list, now should it?

    Packages should NOT be released with succeeding TODO tests. As soon as a TODO test starts working, it should be promoted to a normal test, and the newly working feature should be documented in the release notes or in the change log.

ONFAIL

  1. BEGIN { plan test => 4, onfail => sub { warn "CALL 911!" } }

Although test failures should be enough, extra diagnostics can be triggered at the end of a test run. C is passed an array ref of hash refs that describe each test failure. Each hash will contain at least the following fields: C, C, and C. (You shouldn't rely on any other fields being present.) If the test had an expected value or a diagnostic (or "note") string, these will also be included.

The I C hook might be used simply to print out the version of your package and/or how to report problems. It might also be used to generate extremely sophisticated diagnostics for a particularly bizarre test failure. However it's not a panacea. Core dumps or other unrecoverable errors prevent the C hook from running. (It is run inside an C block.) Besides, C is probably over-kill in most cases. (Your test code should be simpler than the code it is testing, yes?)

BUGS and CAVEATS

  • C's special handing of strings which look like they might be regexes can also cause unexpected behavior. An innocent:

    1. ok( $fileglob, '/path/to/some/*stuff/' );

    will fail, since Test.pm considers the second argument to be a regex! The best bet is to use the one-argument form:

    1. ok( $fileglob eq '/path/to/some/*stuff/' );
  • C's use of string C can sometimes cause odd problems when comparing numbers, especially if you're casting a string to a number:

    1. $foo = "1.0";
    2. ok( $foo, 1 ); # not ok, "1.0" ne 1

    Your best bet is to use the single argument form:

    1. ok( $foo == 1 ); # ok "1.0" == 1
  • As you may have inferred from the above documentation and examples, C's prototype is C<($;$$)> (and, incidentally, C's is C<($;$$$)>). This means, for example, that you can do C to compare the I of the two arrays. But don't be fooled into thinking that C means a comparison of the contents of two arrays -- you're comparing I the number of elements of each. It's so easy to make that mistake in reading C that you might want to be very explicit about it, and instead write C.

  • This almost definitely doesn't do what you expect:

    1. ok $thingy->can('some_method');

    Why? Because C returns a coderef to mean "yes it can (and the method is this...)", and then C sees a coderef and thinks you're passing a function that you want it to call and consider the truth of the result of! I.e., just like:

    1. ok $thingy->can('some_method')->();

    What you probably want instead is this:

    1. ok $thingy->can('some_method') && 1;

    If the C returns false, then that is passed to C. If it returns true, then the larger expression S<< C<< $thingy->can('some_method') && 1 >> >> returns 1, which C sees as a simple signal of success, as you would expect.

  • The syntax for C is about the only way it can be, but it's still quite confusing. Just start with the above examples and you'll be okay.

    Moreover, users may expect this:

    1. skip $unless_mswin, foo($bar), baz($quux);

    to not evaluate C and C when the test is being skipped. But in reality, they I evaluated, but C just won't bother comparing them if C<$unless_mswin> is true.

    You could do this:

    1. skip $unless_mswin, sub{foo($bar)}, sub{baz($quux)};

    But that's not terribly pretty. You may find it simpler or clearer in the long run to just do things like this:

    1. if( $^O =~ m/MSWin/ ) {
    2. print "# Yay, we're under $^O\n";
    3. ok foo($bar), baz($quux);
    4. ok thing($whatever), baz($stuff);
    5. ok blorp($quux, $whatever);
    6. ok foo($barzbarz), thang($quux);
    7. } else {
    8. print "# Feh, we're under $^O. Watch me skip some tests...\n";
    9. for(1 .. 4) { skip "Skip unless under MSWin" }
    10. }

    But be quite sure that C is called exactly as many times in the first block as C is called in the second block.

ENVIRONMENT

If C environment variable is set, it will be used as a command for comparing unexpected multiline results. If you have GNU diff installed, you might want to set C to C. If you don't have a suitable program, you might install the C module and then set C to be C. If C isn't set but the C module is available, then it will be used to show the differences in multiline results.

NOTE

A past developer of this module once said that it was no longer being actively developed. However, rumors of its demise were greatly exaggerated. Feedback and suggestions are quite welcome.

Be aware that the main value of this module is its simplicity. Note that there are already more ambitious modules out there, such as L and L.

Some earlier versions of this module had docs with some confusing typoes in the description of C.

SEE ALSO

L

L, L, L

L for building your own testing library.

L is an interesting XUnit-style testing library.

L and L let you embed tests in code.

AUTHOR

Copyright (c) 1998-2000 Joshua Nathaniel Pritikin. All rights reserved.

Copyright (c) 2001-2002 Michael G. Schwern.

Copyright (c) 2002-2004 and counting Sean M. Burke.

Current maintainer: Sean M. Burke. Esburke@cpan.orgE

This package is free software and is provided "as is" without express or implied warranty. It may be used, redistributed and/or modified under the same terms as Perl itself.