{
    "mode": "perldoc",
    "parameter": "Test",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Test/json",
    "generated": "2026-06-13T22:56:06Z",
    "synopsis": "use strict;\nuse Test;\n# use a BEGIN block so we print our plan before MyModule is loaded\nBEGIN { plan tests => 14, todo => [3,4] }\n# load your module...\nuse MyModule;\n# Helpful notes.  All note-lines must start with a \"#\".\nprint \"# I'm testing MyModule version $MyModule::VERSION\\n\";\nok(0); # failure\nok(1); # success\nok(0); # ok, expected failure (see todo list, above)\nok(1); # surprise success!\nok(0,1);             # failure: '0' ne '1'\nok('broke','fixed'); # failure: 'broke' ne 'fixed'\nok('fixed','fixed'); # success: 'fixed' eq 'fixed'\nok('fixed',qr/x/);   # success: 'fixed' =~ qr/x/\nok(sub { 1+1 }, 2);  # success: '2' eq '2'\nok(sub { 1+1 }, 3);  # failure: '2' ne '3'\nmy @list = (0,0);\nok @list, 3, \"\\@list=\".join(',',@list);      #extra notes\nok 'segmentation fault', '/(?i)success/';    #regex match\nskip(\n$^O =~ m/MSWin/ ? \"Skip if MSWin\" : 0,  # whether to skip\n$foo, $bar  # arguments just like for ok(...)\n);\nskip(\n$^O =~ m/MSWin/ ? 0 : \"Skip unless MSWin\",  # whether to skip\n$foo, $bar  # arguments just like for ok(...)\n);",
    "sections": {
        "NAME": {
            "content": "Test - provides a simple framework for writing test scripts\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use strict;\nuse Test;\n\n# use a BEGIN block so we print our plan before MyModule is loaded\nBEGIN { plan tests => 14, todo => [3,4] }\n\n# load your module...\nuse MyModule;\n\n# Helpful notes.  All note-lines must start with a \"#\".\nprint \"# I'm testing MyModule version $MyModule::VERSION\\n\";\n\nok(0); # failure\nok(1); # success\n\nok(0); # ok, expected failure (see todo list, above)\nok(1); # surprise success!\n\nok(0,1);             # failure: '0' ne '1'\nok('broke','fixed'); # failure: 'broke' ne 'fixed'\nok('fixed','fixed'); # success: 'fixed' eq 'fixed'\nok('fixed',qr/x/);   # success: 'fixed' =~ qr/x/\n\nok(sub { 1+1 }, 2);  # success: '2' eq '2'\nok(sub { 1+1 }, 3);  # failure: '2' ne '3'\n\nmy @list = (0,0);\nok @list, 3, \"\\@list=\".join(',',@list);      #extra notes\nok 'segmentation fault', '/(?i)success/';    #regex match\n\nskip(\n$^O =~ m/MSWin/ ? \"Skip if MSWin\" : 0,  # whether to skip\n$foo, $bar  # arguments just like for ok(...)\n);\nskip(\n$^O =~ m/MSWin/ ? 0 : \"Skip unless MSWin\",  # whether to skip\n$foo, $bar  # arguments just like for ok(...)\n);\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This module simplifies the task of writing test files for Perl modules, such that their output\nis in the format that Test::Harness expects to see.\n",
            "subsections": []
        },
        "QUICK START GUIDE": {
            "content": "To write a test for your new (and probably not even done) module, create a new file called\nt/test.t (in a new t directory). If you have multiple test files, to test the \"foo\", \"bar\", and\n\"baz\" feature sets, then feel free to call your files t/foo.t, t/bar.t, and t/baz.t\n",
            "subsections": [
                {
                    "name": "Functions",
                    "content": "This module defines three public functions, \"plan(...)\", \"ok(...)\", and \"skip(...)\". By default,\nall three are exported by the \"use Test;\" statement.\n\n\"plan(...)\"\nBEGIN { plan %theplan; }\n\nThis should be the first thing you call in your test script. It declares your testing plan,\nhow many there will be, if any of them should be allowed to fail, and so on.\n\nTypical usage is just:\n\nuse Test;\nBEGIN { plan tests => 23 }\n\nThese are the things that you can put in the parameters to plan:\n\n\"tests => *number*\"\nThe number of tests in your script. This means all ok() and skip() calls.\n\n\"todo => [*1,5,14*]\"\nA reference to a list of tests which are allowed to fail. See \"TODO TESTS\".\n\n\"onfail => sub { ... }\"\n\"onfail => \\&somesub\"\nA subroutine reference to be run at the end of the test script, if any of the tests\nfail. See \"ONFAIL\".\n\nYou must call \"plan(...)\" once and only once. You should call it in a \"BEGIN {...}\" block,\nlike so:\n\nBEGIN { plan tests => 23 }\n\n\"ok(...)\"\nok(1 + 1 == 2);\nok($have, $expect);\nok($have, $expect, $diagnostics);\n\nThis function is the reason for \"Test\"'s existence. It's the basic function that handles\nprinting \"\"ok\"\" or \"\"not ok\"\", along with the current test number. (That's what\n\"Test::Harness\" wants to see.)\n\nIn its most basic usage, \"ok(...)\" simply takes a single scalar expression. If its value is\ntrue, the test passes; if false, the test fails. Examples:\n\n# Examples of ok(scalar)\n\nok( 1 + 1 == 2 );           # ok if 1 + 1 == 2\nok( $foo =~ /bar/ );        # ok if $foo contains 'bar'\nok( baz($x + $y) eq 'Armondo' );    # ok if baz($x + $y) returns\n# 'Armondo'\nok( @a == @b );             # ok if @a and @b are the same\n# length\n\nThe expression is evaluated in scalar context. So the following will work:\n\nok( @stuff );                       # ok if @stuff has any\n# elements\nok( !grep !defined $, @stuff );    # ok if everything in @stuff\n# is defined.\n\nA special case is if the expression is a subroutine reference (in either \"sub {...}\" syntax\nor \"\\&foo\" syntax). In that case, it is executed and its value (true or false) determines if\nthe test passes or fails. For example,\n\nok( sub {   # See whether sleep works at least passably\nmy $starttime = time;\nsleep 5;\ntime() - $starttime  >= 4\n});\n\nIn its two-argument form, \"ok(*arg1*, *arg2*)\" compares the two scalar values to see if they\nmatch. They match if both are undefined, or if *arg2* is a regex that matches *arg1*, or if\nthey compare equal with \"eq\".\n\n# Example of ok(scalar, scalar)\n\nok( \"this\", \"that\" );               # not ok, 'this' ne 'that'\nok( \"\", undef );                    # not ok, \"\" is defined\n\nThe second argument is considered a regex if it is either a regex object or a string that\nlooks like a regex. Regex objects are constructed with the qr// operator in recent versions\nof perl. A string is considered to look like a regex if its first and last characters are\n\"/\", or if the first character is \"m\" and its second and last characters are both the same\nnon-alphanumeric non-whitespace character. These regexp\n\nRegex examples:\n\nok( 'JaffO', '/Jaff/' );    # ok, 'JaffO' =~ /Jaff/\nok( 'JaffO', 'm|Jaff|' );   # ok, 'JaffO' =~ m|Jaff|\nok( 'JaffO', qr/Jaff/ );    # ok, 'JaffO' =~ qr/Jaff/;\nok( 'JaffO', '/(?i)jaff/ ); # ok, 'JaffO' =~ /jaff/i;\n\nIf either (or both!) is a subroutine reference, it is run and used as the value for\ncomparing. For example:\n\nok sub {\nopen(OUT, '>', 'x.dat') || die $!;\nprint OUT \"\\x{e000}\";\nclose OUT;\nmy $bytecount = -s 'x.dat';\nunlink 'x.dat' or warn \"Can't unlink : $!\";\nreturn $bytecount;\n},\n4\n;\n\nThe above test passes two values to \"ok(arg1, arg2)\" -- the first a coderef, and the second\nis the number 4. Before \"ok\" compares them, it calls the coderef, and uses its return value\nas the real value of this parameter. Assuming that $bytecount returns 4, \"ok\" ends up\ntesting \"4 eq 4\". Since that's true, this test passes.\n\nFinally, you can append an optional third argument, in \"ok(*arg1*,*arg2*, *note*)\", where\n*note* is a string value that will be printed if the test fails. This should be some useful\ninformation about the test, pertaining to why it failed, and/or a description of the test.\nFor example:\n\nok( grep($ eq 'something unique', @stuff), 1,\n\"Something that should be unique isn't!\\n\".\n'@stuff = '.join ', ', @stuff\n);\n\nUnfortunately, a note cannot be used with the single argument style of \"ok()\". That is, if\nyou try \"ok(*arg1*, *note*)\", then \"Test\" will interpret this as \"ok(*arg1*, *arg2*)\", and\nprobably end up testing \"*arg1* eq *arg2*\" -- and that's not what you want!\n\nAll of the above special cases can occasionally cause some problems. See \"BUGS and CAVEATS\".\n\n\"skip(*skipiftrue*, *args...*)\"\nThis is used for tests that under some conditions can be skipped. It's basically equivalent\nto:\n\nif( $skipiftrue ) {\nok(1);\n} else {\nok( args... );\n}\n\n...except that the ok(1) emits not just \"\"ok *testnum*\"\" but actually \"\"ok *testnum* #\n*skipiftruevalue*\"\".\n\nThe arguments after the *skipiftrue* are what is fed to \"ok(...)\" if this test isn't\nskipped.\n\nExample usage:\n\nmy $ifMSWin =\n$^O =~ m/MSWin/ ? 'Skip if under MSWin' : '';\n\n# A test to be skipped if under MSWin (i.e., run except under\n# MSWin)\nskip($ifMSWin, thing($foo), thing($bar) );\n\nOr, going the other way:\n\nmy $unlessMSWin =\n$^O =~ m/MSWin/ ? '' : 'Skip unless under MSWin';\n\n# A test to be skipped unless under MSWin (i.e., run only under\n# MSWin)\nskip($unlessMSWin, thing($foo), thing($bar) );\n\nThe tricky thing to remember is that the first parameter is true if you want to *skip* the\ntest, not *run* it; and it also doubles as a note about why it's being skipped. So in the\nfirst codeblock above, read the code as \"skip if MSWin -- (otherwise) test whether\n\"thing($foo)\" is \"thing($bar)\"\" or for the second case, \"skip unless MSWin...\".\n\nAlso, when your *skipifreason* string is true, it really should (for backwards\ncompatibility with older Test.pm versions) start with the string \"Skip\", as shown in the\nabove examples.\n\nNote that in the above cases, \"thing($foo)\" and \"thing($bar)\" *are* evaluated -- but as long\nas the \"skipiftrue\" is true, then we \"skip(...)\" just tosses out their value (i.e., not\nbothering to treat them like values to \"ok(...)\". But if you need to *not* eval the\narguments when skipping the test, use this format:\n\nskip( $unlessMSWin,\nsub {\n# This code returns true if the test passes.\n# (But it doesn't even get called if the test is skipped.)\nthing($foo) eq thing($bar)\n}\n);\n\nor even this, which is basically equivalent:\n\nskip( $unlessMSWin,\nsub { thing($foo) }, sub { thing($bar) }\n);\n\nThat is, both are like this:\n\nif( $unlessMSWin ) {\nok(1);  # but it actually appends \"# $unlessMSWin\"\n#  so that Test::Harness can tell it's a skip\n} else {\n# Not skipping, so actually call and evaluate...\nok( sub { thing($foo) }, sub { thing($bar) } );\n}\n"
                }
            ]
        },
        "TEST TYPES": {
            "content": "*   NORMAL TESTS\n\nThese tests are expected to succeed. Usually, most or all of your tests are in this\ncategory. If a normal test doesn't succeed, then that means that something is *wrong*.\n\n*   SKIPPED TESTS\n\nThe \"skip(...)\" function is for tests that might or might not be possible to run, depending\non the availability of platform-specific features. The first argument should evaluate to\ntrue (think \"yes, please skip\") if the required feature is *not* available. After the first\nargument, \"skip(...)\" works exactly the same way as \"ok(...)\" does.\n\n*   TODO TESTS\n\nTODO tests are designed for maintaining an executable TODO list. These tests are *expected\nto fail.* If a TODO test does succeed, then the feature in question shouldn't be on the TODO\nlist, now should it?\n\nPackages should NOT be released with succeeding TODO tests. As soon as a TODO test starts\nworking, it should be promoted to a normal test, and the newly working feature should be\ndocumented in the release notes or in the change log.\n",
            "subsections": []
        },
        "ONFAIL": {
            "content": "BEGIN { plan test => 4, onfail => sub { warn \"CALL 911!\" } }\n\nAlthough test failures should be enough, extra diagnostics can be triggered at the end of a test\nrun. \"onfail\" is passed an array ref of hash refs that describe each test failure. Each hash\nwill contain at least the following fields: \"package\", \"repetition\", and \"result\". (You\nshouldn't rely on any other fields being present.) If the test had an expected value or a\ndiagnostic (or \"note\") string, these will also be included.\n\nThe *optional* \"onfail\" hook might be used simply to print out the version of your package\nand/or how to report problems. It might also be used to generate extremely sophisticated\ndiagnostics for a particularly bizarre test failure. However it's not a panacea. Core dumps or\nother unrecoverable errors prevent the \"onfail\" hook from running. (It is run inside an \"END\"\nblock.) Besides, \"onfail\" is probably over-kill in most cases. (Your test code should be simpler\nthan the code it is testing, yes?)\n\nBUGS and CAVEATS\n*   \"ok(...)\"'s special handing of strings which look like they might be regexes can also cause\nunexpected behavior. An innocent:\n\nok( $fileglob, '/path/to/some/*stuff/' );\n\nwill fail, since Test.pm considers the second argument to be a regex! The best bet is to use\nthe one-argument form:\n\nok( $fileglob eq '/path/to/some/*stuff/' );\n\n*   \"ok(...)\"'s use of string \"eq\" can sometimes cause odd problems when comparing numbers,\nespecially if you're casting a string to a number:\n\n$foo = \"1.0\";\nok( $foo, 1 );      # not ok, \"1.0\" ne 1\n\nYour best bet is to use the single argument form:\n\nok( $foo == 1 );    # ok \"1.0\" == 1\n\n*   As you may have inferred from the above documentation and examples, \"ok\"'s prototype is\n\"($;$$)\" (and, incidentally, \"skip\"'s is \"($;$$$)\"). This means, for example, that you can\ndo \"ok @foo, @bar\" to compare the *size* of the two arrays. But don't be fooled into\nthinking that \"ok @foo, @bar\" means a comparison of the contents of two arrays -- you're\ncomparing *just* the number of elements of each. It's so easy to make that mistake in\nreading \"ok @foo, @bar\" that you might want to be very explicit about it, and instead write\n\"ok scalar(@foo), scalar(@bar)\".\n\n*   This almost definitely doesn't do what you expect:\n\nok $thingy->can('somemethod');\n\nWhy? Because \"can\" returns a coderef to mean \"yes it can (and the method is this...)\", and\nthen \"ok\" sees a coderef and thinks you're passing a function that you want it to call and\nconsider the truth of the result of! I.e., just like:\n\nok $thingy->can('somemethod')->();\n\nWhat you probably want instead is this:\n\nok $thingy->can('somemethod') && 1;\n\nIf the \"can\" returns false, then that is passed to \"ok\". If it returns true, then the larger\nexpression \"$thingy->can('somemethod') && 1\" returns 1, which \"ok\" sees as a simple signal\nof success, as you would expect.\n\n*   The syntax for \"skip\" is about the only way it can be, but it's still quite confusing. Just\nstart with the above examples and you'll be okay.\n\nMoreover, users may expect this:\n\nskip $unlessmswin, foo($bar), baz($quux);\n\nto not evaluate \"foo($bar)\" and \"baz($quux)\" when the test is being skipped. But in reality,\nthey *are* evaluated, but \"skip\" just won't bother comparing them if $unlessmswin is true.\n\nYou could do this:\n\nskip $unlessmswin, sub{foo($bar)}, sub{baz($quux)};\n\nBut that's not terribly pretty. You may find it simpler or clearer in the long run to just\ndo things like this:\n\nif( $^O =~ m/MSWin/ ) {\nprint \"# Yay, we're under $^O\\n\";\nok foo($bar), baz($quux);\nok thing($whatever), baz($stuff);\nok blorp($quux, $whatever);\nok foo($barzbarz), thang($quux);\n} else {\nprint \"# Feh, we're under $^O.  Watch me skip some tests...\\n\";\nfor(1 .. 4) { skip \"Skip unless under MSWin\" }\n}\n\nBut be quite sure that \"ok\" is called exactly as many times in the first block as \"skip\" is\ncalled in the second block.\n",
            "subsections": []
        },
        "ENVIRONMENT": {
            "content": "If \"PERLTESTDIFF\" environment variable is set, it will be used as a command for comparing\nunexpected multiline results. If you have GNU diff installed, you might want to set\n\"PERLTESTDIFF\" to \"diff -u\". If you don't have a suitable program, you might install the\n\"Text::Diff\" module and then set \"PERLTESTDIFF\" to be \"perl -MText::Diff -e 'print",
            "subsections": [
                {
                    "name": "diff",
                    "content": "it will be used to show the differences in multiline results.\n"
                }
            ]
        },
        "NOTE": {
            "content": "A past developer of this module once said that it was no longer being actively developed.\nHowever, rumors of its demise were greatly exaggerated. Feedback and suggestions are quite\nwelcome.\n\nBe aware that the main value of this module is its simplicity. Note that there are already more\nambitious modules out there, such as Test::More and Test::Unit.\n\nSome earlier versions of this module had docs with some confusing typos in the description of\n\"skip(...)\".\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "Test::Harness\n\nTest::Simple, Test::More, Devel::Cover\n\nTest::Builder for building your own testing library.\n\nTest::Unit is an interesting XUnit-style testing library.\n\nTest::Inline lets you embed tests in code.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Copyright (c) 1998-2000 Joshua Nathaniel Pritikin.\n\nCopyright (c) 2001-2002 Michael G. Schwern.\n\nCopyright (c) 2002-2004 Sean M. Burke.\n\nCurrent maintainer: Jesse Vincent. <jesse@bestpractical.com>\n\nThis package is free software and is provided \"as is\" without express or implied warranty. It\nmay be used, redistributed and/or modified under the same terms as Perl itself.\n",
            "subsections": []
        }
    },
    "summary": "Test - provides a simple framework for writing test scripts",
    "flags": [],
    "examples": [],
    "see_also": []
}