Test(3perl)

πŸ’– Test πŸ’–

hey bestie, welcome to the Test page from the Perl Programmers Reference Guide 🫢 this is the one that teaches you how to write test scripts without losing your entire mind, so grab a boba and let's go πŸ’…


✨ NAME ✨

Test β€” provides a simple framework for writing test scripts. that's it, that's the whole vibe 🌸


πŸ¦‹ SYNOPSIS πŸ¦‹

no cap, just read it, it's giving tutorial:

use strict;
use Test;

# use a BEGIN block so we print our plan before MyModule is loaded
BEGIN { plan tests => 14, todo => [3,4] }

# load your module...
use MyModule;

# Helpful notes.  All note-lines must start with a "#".
print "# I'm testing MyModule version $MyModule::VERSION\n";

ok(0); # failure
ok(1); # success

ok(0); # ok, expected failure (see todo list, above)
ok(1); # surprise success!

ok(0,1);             # failure: '0' ne '1'
ok('broke','fixed'); # failure: 'broke' ne 'fixed'
ok('fixed','fixed'); # success: 'fixed' eq 'fixed'
ok('fixed',qr/x/);   # success: 'fixed' =~ qr/x/

ok(sub { 1+1 }, 2);  # success: '2' eq '2'
ok(sub { 1+1 }, 3);  # failure: '2' ne '3'

my @list = (0,0);
ok @list, 3, "\@list=".join(',',@list);      #extra notes
ok 'segmentation fault', '/(?i)success/';    #regex match

skip(
  $^O =~ m/MSWin/ ? "Skip if MSWin" : 0,  # whether to skip
  $foo, $bar  # arguments just like for ok(...)
);
skip(
  $^O =~ m/MSWin/ ? 0 : "Skip unless MSWin",  # whether to skip
  $foo, $bar  # arguments just like for ok(...)
);

🌈 DESCRIPTION 🌈

so this module simplifies the task of writing test files for Perl modules, so that the output they spit out is in exactly the format that Test::Harness expects to see. that's the whole point bestie, Test::Harness is the picky one and Test is here to make it happy πŸ™Œ


πŸ‘‘ QUICK START GUIDE πŸ‘‘

to write a test for your new (and probably not even done) module, make a new file called t/test.t (inside a brand new t directory, iconic). and if you've got multiple test files β€” say you're testing the "foo", "bar", and "baz" feature sets β€” then feel free to call them 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 of them get exported when you say use Test; ✨

🧚 plan(...)

BEGIN { plan %theplan; }

this should be the first thing you call in your test script, no exceptions. it declares your testing plan: how many tests there'll be, if any of them are allowed to fail, all of that.

typical usage is literally just:

use Test;
BEGIN { plan tests => 23 }

here's everything you can put in the parameters to plan:

  • tests => number β€” the number of tests in your script. and yes that means all the ok() and skip() calls, every single one πŸ’―
  • todo => [1,5,14] β€” a reference to a list of tests which are allowed to fail. go see "TODO TESTS" for the tea.
  • onfail => sub { ... }
  • onfail => \&some_sub β€” a subroutine reference that gets run at the very end of the test script, but only if any of the tests fail. details live in "ONFAIL".
you must call plan(...) once and only once. not zero times, not twice, once. and you should call it inside a BEGIN {...} block, like so:
BEGIN { plan tests => 23 }

πŸ¦‹ ok(...)

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

this function is literally the reason Test exists. it's the basic one that handles printing "ok" or "not ok", together with the current test number β€” which is exactly what Test::Harness wants to see πŸ‘‘

in its most basic usage, ok(...) just takes a single scalar expression. if its value is true β†’ the test passes. if it's false β†’ the test fails. examples:

# Examples of ok(scalar)

ok( 1 + 1 == 2 );           # ok if 1 + 1 == 2
ok( $foo =~ /bar/ );        # ok if $foo contains 'bar'
ok( baz($x + $y) eq 'Armondo' );    # ok if baz($x + $y) returns
                                    # 'Armondo'
ok( @a == @b );             # ok if @a and @b are the same
                            # length

the expression gets evaluated in scalar context. so this absolutely works:

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

there's a special case: if the expression is a subroutine reference (either the sub {...} syntax or the \&foo syntax), then it gets executed, and its value (true or false) is what decides pass or fail. for example:

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

in its two-argument form, ok(arg1, arg2) compares the two scalar values to see if they match. they match if both are undefined, or if arg2 is a regex that matches arg1, or if they compare equal with eq. periodt πŸ’…

# Example of ok(scalar, scalar)

ok( "this", "that" );               # not ok, 'this' ne 'that'
ok( "", undef );                    # not ok, "" is defined

the second argument counts as a regex if it's either a regex object or a string that looks like a regex. regex objects are made with the qr// operator in recent versions of perl. and a string "looks like a regex" if its first and last characters are /, or if its first character is m and its second and last characters are both the same non-alphanumeric non-whitespace character. so:

these regexp πŸ‘€

regex examples:

ok( 'JaffO', '/Jaff/' );    # ok, 'JaffO' =~ /Jaff/
ok( 'JaffO', 'm|Jaff|' );   # ok, 'JaffO' =~ m|Jaff|
ok( 'JaffO', qr/Jaff/ );    # ok, 'JaffO' =~ qr/Jaff/;
ok( 'JaffO', '/(?i)jaff/ ); # ok, 'JaffO' =~ /jaff/i;

if either (or both!!) argument is a subroutine reference, it gets run and its value is used for the comparing. for example:

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

so the test above passes two values to ok(arg1, arg2) β€” the first one is a coderef, and the second one is the number 4. before ok compares them, it calls the coderef and uses whatever it returns as the real value of that parameter. assuming $bytecount comes back as 4, ok ends up testing 4 eq 4. and since that's true, the test passes πŸŽ‰

finally, you can tack on an optional third argument, ok(arg1,arg2, note), where note is a string value that'll get printed only if the test fails. it should be useful info about the test β€” why it failed, and/or a description of the test itself. for example:

ok( grep($_ eq 'something unique', @stuff), 1,
    "Something that should be unique isn't!\n".
    '@stuff = '.join ', ', @stuff
  );
unfortunately πŸ‘Ž a note cannot be used with the single-argument style of ok(). like, if you try ok(arg1, note), then Test is gonna read that as ok(arg1, arg2), and it'll probably end up testing arg1 eq arg2 β€” which is absolutely not what you wanted bestie, i'm so serious πŸ’€

all of the special cases above can occasionally cause some problems. see "BUGS and CAVEATS".

πŸ’… skip(skip_if_true, args...)

this one's for tests that, under some conditions, can be skipped. it's basically equivalent to:

if( $skip_if_true ) {
  ok(1);
} else {
  ok( args... );
}

...except that the ok(1) doesn't just emit "ok testnum", it actually emits "ok testnum # skip_if_true_value" 🌟

the arguments after the skip_if_true are exactly what gets fed to ok(...) if this test isn't skipped.

example usage:

my $if_MSWin =
  $^O =~ m/MSWin/ ? 'Skip if under MSWin' : '';

# A test to be skipped if under MSWin (i.e., run except under
# MSWin)
skip($if_MSWin, thing($foo), thing($bar) );

or, going the other way:

my $unless_MSWin =
  $^O =~ m/MSWin/ ? '' : 'Skip unless under MSWin';

# A test to be skipped unless under MSWin (i.e., run only under
# MSWin)
skip($unless_MSWin, thing($foo), thing($bar) );

the tricky thing to keep in your head 🧠 is that the first parameter is true if you want to SKIP the test, not run it. and it also doubles as the note about why it's being skipped. so in that first code block, read the code as "skip if MSWin -- (otherwise) test whether thing($foo) is thing($bar)", and for the second case, "skip unless MSWin...".

also, when your skip_if_reason string is true, it really should (for backwards compatibility with older Test.pm versions) start with the string "Skip", exactly like the examples above show.

heads up though: in the cases above, thing($foo) and thing($bar) are evaluated β€” but as long as the "skip_if_true" is true, then skip(...) just tosses out their value (like, it doesn't bother treating them as values to ok(...)). but if you need to not evaluate the arguments when the test is skipped, use this format:

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

or even this one, which is basically equivalent:

skip( $unless_MSWin,
  sub { thing($foo) }, sub { thing($bar) }
);

which is to say, both of those are just like:

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

and that's the end of part 1 bestie 😭 don't close the tab, there's literally so much more coming β€” we're not even close to done πŸ’œ

✨ TEST TYPES ✨

πŸ’– NORMAL TESTS

okay so these ones are expected to succeed. Usually, most or literally all of your tests are gonna be in this category. If a normal test doesn't succeed, then that means that something is wrong. screaming, crying, throwing up, etc. 😭

πŸ¦‹ SKIPPED TESTS

The skip(...) 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 not available. After the first argument, skip(...) works exactly the same way as ok(...) does. no cap πŸ’…

πŸ”₯ TODO TESTS

TODO tests are designed for maintaining an executable TODO list. These tests are expected to fail. If a TODO test does succeed, then the feature in question shouldn't be on the TODO list, now should it? like… embarrassing fr πŸ™ˆ

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. periodt. ✨


🫢 ONFAIL 🫢

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. onfail is passed an array ref of hash refs that describe each test failure. Each hash will contain at least the following fields: package, repetition, and result. (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 optional onfail 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 onfail hook from running. (It is run inside an END block.) Besides, onfail is probably over-kill in most cases. (Your test code should be simpler than the code it is testing, yes?) πŸ’€


😭 BUGS and CAVEATS 😭

  • ok(...)'s special handing of strings which look like they might be regexes can also cause unexpected behavior. An innocent:
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:

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

Your best bet is to use the single argument form:

ok( $foo == 1 );    # ok "1.0" == 1
  • As you may have inferred from the above documentation and examples, ok's prototype is ($;$$) (and, incidentally, skip's is ($;$$$)). This means, for example, that you can do ok @foo, @bar to compare the size of the two arrays. But don't be fooled into thinking that ok @foo, @bar means a comparison of the contents of two arrays -- you're comparing just the number of elements of each. It's so easy to make that mistake in reading ok @foo, @bar that you might want to be very explicit about it, and instead write ok scalar(@foo), scalar(@bar). πŸ™ˆ
  • This almost definitely doesn't do what you expect:
ok $thingy->can('some_method');

Why? Because can returns a coderef to mean "yes it can (and the method is this...)", and then ok 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:

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

What you probably want instead is this:

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

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

  • The syntax for skip 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:

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

to not evaluate foo($bar) and baz($quux) when the test is being skipped. But in reality, they are evaluated, but skip just won't bother comparing them if $unless_mswin is true.

You could do this:

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:

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

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


🌈 ENVIRONMENT 🌈

If PERL_TEST_DIFF 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 PERL_TEST_DIFF to diff -u. If you don't have a suitable program, you might install the Text::Diff module and then set PERL_TEST_DIFF to be perl -MText::Diff -e 'print diff(@ARGV)'. If PERL_TEST_DIFF isn't set but the Algorithm::Diff module is available, then it will be used to show the differences in multiline results. lowkey handy ngl πŸ’–


πŸ’œ 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. not me getting emotional about a test module πŸ˜­πŸ’•

Be aware that the main value of this module is its simplicity. Note that there are already more ambitious modules out there, such as Test::More and Test::Unit. different vibes, same energy ✨

Some earlier versions of this module had docs with some confusing typos in the description of skip(...). we've all been there bestie 🫢


πŸ‘‘ SEE ALSO πŸ‘‘

  • Test::Harness
  • Test::Simple, Test::More, Devel::Cover
  • Test::Builder for building your own testing library.
  • Test::Unit is an interesting XUnit-style testing library.
  • Test::Inline lets you embed tests in code.

πŸŽ€ AUTHOR πŸŽ€

Copyright (c) 1998-2000 Joshua Nathaniel Pritikin.

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

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

Current maintainer: Jesse Vincent. <jesse@bestpractical.com>

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.


okay that's the whole thing bestie πŸ’… this was Test(3perl) from perl v5.44.0, dated 2026-10-17 β€” iconic, legendary, ate and left no crumbs πŸ‘‘πŸ’– go write some tests, you got this! πŸ¦‹βœ¨

πŸ“¦ where this page comes from
  • arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms