{
    "mode": "perldoc",
    "parameter": "Test2::API::Context",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Test2%3A%3AAPI%3A%3AContext/json",
    "generated": "2026-06-09T18:25:41Z",
    "synopsis": "In general you will not be creating contexts directly. To obtain a context you should always use\n\"context()\" which is exported by the Test2::API module.\nuse Test2::API qw/context/;\nsub myok {\nmy ($bool, $name) = @;\nmy $ctx = context();\nif ($bool) {\n$ctx->pass($name);\n}\nelse {\n$ctx->fail($name);\n}\n$ctx->release; # You MUST do this!\nreturn $bool;\n}\nContext objects make it easy to wrap other tools that also use context. Once you grab a context,\nany tool you call before releasing your context will inherit it:\nsub wrapper {\nmy ($bool, $name) = @;\nmy $ctx = context();\n$ctx->diag(\"wrapping myok\");\nmy $out = myok($bool, $name);\n$ctx->release; # You MUST do this!\nreturn $out;\n}",
    "sections": {
        "NAME": {
            "content": "Test2::API::Context - Object to represent a testing context.\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "The context object is the primary interface for authors of testing tools written with Test2. The\ncontext object represents the context in which a test takes place (File and Line Number), and\nprovides a quick way to generate events from that context. The context object also takes care of\nsending events to the correct Test2::Hub instance.\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "In general you will not be creating contexts directly. To obtain a context you should always use\n\"context()\" which is exported by the Test2::API module.\n\nuse Test2::API qw/context/;\n\nsub myok {\nmy ($bool, $name) = @;\nmy $ctx = context();\n\nif ($bool) {\n$ctx->pass($name);\n}\nelse {\n$ctx->fail($name);\n}\n\n$ctx->release; # You MUST do this!\nreturn $bool;\n}\n\nContext objects make it easy to wrap other tools that also use context. Once you grab a context,\nany tool you call before releasing your context will inherit it:\n\nsub wrapper {\nmy ($bool, $name) = @;\nmy $ctx = context();\n$ctx->diag(\"wrapping myok\");\n\nmy $out = myok($bool, $name);\n$ctx->release; # You MUST do this!\nreturn $out;\n}\n",
            "subsections": []
        },
        "CRITICAL DETAILS": {
            "content": "you MUST always use the context() sub from Test2::API\nCreating your own context via \"Test2::API::Context->new()\" will almost never produce a\ndesirable result. Use \"context()\" which is exported by Test2::API.\n\nThere are a handful of cases where a tool author may want to create a new context by hand,\nwhich is why the \"new\" method exists. Unless you really know what you are doing you should\navoid this.\n\nYou MUST always release the context when done with it\nReleasing the context tells the system you are done with it. This gives it a chance to run\nany necessary callbacks or cleanup tasks. If you forget to release the context it will try\nto detect the problem and warn you about it.\n\nYou MUST NOT pass context objects around\nWhen you obtain a context object it is made specifically for your tool and any tools nested\nwithin. If you pass a context around you run the risk of polluting other tools with\nincorrect context information.\n\nIf you are certain that you want a different tool to use the same context you may pass it a\nsnapshot. \"$ctx->snapshot\" will give you a shallow clone of the context that is safe to pass\naround or store.\n\nYou MUST NOT store or cache a context for later\nAs long as a context exists for a given hub, all tools that try to get a context will get\nthe existing instance. If you try to store the context you will pollute other tools with\nincorrect context information.\n\nIf you are certain that you want to save the context for later, you can use a snapshot.\n\"$ctx->snapshot\" will give you a shallow clone of the context that is safe to pass around or\nstore.\n\n\"context()\" has some mechanisms to protect you if you do cause a context to persist beyond\nthe scope in which it was obtained. In practice you should not rely on these protections,\nand they are fairly noisy with warnings.\n\nYou SHOULD obtain your context as soon as possible in a given tool\nYou never know what tools you call from within your own tool will need a context. Obtaining\nthe context early ensures that nested tools can find the context you want them to find.\n",
            "subsections": []
        },
        "METHODS": {
            "content": "$ctx->donetesting;\nNote that testing is finished. If no plan has been set this will generate a Plan event.\n\n$clone = $ctx->snapshot()\nThis will return a shallow clone of the context. The shallow clone is safe to store for\nlater.\n\n$ctx->release()\nThis will release the context. This runs cleanup tasks, and several important hooks. It will\nalso restore $!, $?, and $@ to what they were when the context was created.\n\nNote: If a context is acquired more than once an internal refcount is kept. \"release()\"\ndecrements the ref count, none of the other actions of \"release()\" will occur unless the\nrefcount hits 0. This means only the last call to \"release()\" will reset $?, $!, $@,and run\nthe cleanup tasks.\n\n$ctx->throw($message)\nThis will throw an exception reporting to the file and line number of the context. This will\nalso release the context for you.\n\n$ctx->alert($message)\nThis will issue a warning from the file and line number of the context.\n\n$stack = $ctx->stack()\nThis will return the Test2::API::Stack instance the context used to find the current hub.\n\n$hub = $ctx->hub()\nThis will return the Test2::Hub instance the context recognizes as the current one to which\nall events should be sent.\n\n$dbg = $ctx->trace()\nThis will return the Test2::EventFacet::Trace instance used by the context.\n\n$ctx->doincontext(\\&code, @args);\nSometimes you have a context that is not current, and you want things to use it as the\ncurrent one. In these cases you can call \"$ctx->doincontext(sub { ... })\". The codeblock\nwill be run, and anything inside of it that looks for a context will find the one on which\nthe method was called.\n\nThis DOES NOT affect context on other hubs, only the hub used by the context will be\naffected.\n\nmy $ctx = ...;\n$ctx->doincontext(sub {\nmy $ctx = context(); # returns the $ctx the sub is called on\n});\n\nNote: The context will actually be cloned, the clone will be used instead of the original.\nThis allows the thread id, process id, and error variables to be correct without modifying\nthe original context.\n\n$ctx->restoreerrorvars()\nThis will set $!, $?, and $@ to what they were when the context was created. There is no\nlocalization or anything done here, calling this method will actually set these vars.\n\n$! = $ctx->errno()\nThe (numeric) value of $! when the context was created.\n\n$? = $ctx->childerror()\nThe value of $? when the context was created.\n\n$@ = $ctx->evalerror()\nThe value of $@ when the context was created.\n\nEVENT PRODUCTION METHODS\nWhich one do I use?\n\nThe \"pass*\" and \"fail*\" are optimal if they meet your situation, using one of them will always\nbe the most optimal. That said they are optimal by eliminating many features.\n\nMethod such as \"ok\", and \"note\" are shortcuts for generating common 1-task events based on the\nold API, however they are forward compatible, and easy to use. If these meet your needs then go\nahead and use them, but please check back often for alternatives that may be added.\n\nIf you want to generate new style events, events that do many things at once, then you want the\n\"*ev2*\" methods. These let you directly specify which facets you wish to use.\n\n$event = $ctx->pass()\n$event = $ctx->pass($name)\nThis will send and return an Test2::Event::Pass event. You may optionally provide a $name\nfor the assertion.\n\nThe Test2::Event::Pass is a specially crafted and optimized event, using this will help the\nperformance of passing tests.\n\n$true = $ctx->passandrelease()\n$true = $ctx->passandrelease($name)\nThis is a combination of \"pass()\" and \"release()\". You can use this if you do not plan to do\nanything with the context after sending the event. This helps write more clear and compact\ncode.\n\nsub shorthand {\nmy ($bool, $name) = @;\nmy $ctx = context();\nreturn $ctx->passandrelease($name) if $bool;\n\n... Handle a failure ...\n}\n\nsub longform {\nmy ($bool, $name) = @;\nmy $ctx = context();\n\nif ($bool) {\n$ctx->pass($name);\n$ctx->release;\nreturn 1;\n}\n\n... Handle a failure ...\n}\n\nmy $event = $ctx->fail()\nmy $event = $ctx->fail($name)\nmy $event = $ctx->fail($name, @diagnostics)\nThis lets you send an Test2::Event::Fail event. You may optionally provide a $name and\n@diagnostics messages.\n\nDiagnostics messages can be simple strings, data structures, or instances of\nTest2::EventFacet::Info::Table (which are converted inline into the Test2::EventFacet::Info\nstructure).\n\nmy $false = $ctx->failandrelease()\nmy $false = $ctx->failandrelease($name)\nmy $false = $ctx->failandrelease($name, @diagnostics)\nThis is a combination of \"fail()\" and \"release()\". This can be used to write clearer and\nshorter code.\n\nsub shorthand {\nmy ($bool, $name) = @;\nmy $ctx = context();\nreturn $ctx->failandrelease($name) unless $bool;\n\n... Handle a success ...\n}\n\nsub longform {\nmy ($bool, $name) = @;\nmy $ctx = context();\n\nunless ($bool) {\n$ctx->pass($name);\n$ctx->release;\nreturn 1;\n}\n\n... Handle a success ...\n}\n\n$event = $ctx->ok($bool, $name)\n$event = $ctx->ok($bool, $name, \\@onfail)\nNOTE: Use of this method is discouraged in favor of \"pass()\" and \"fail()\" which produce\nTest2::Event::Pass and Test2::Event::Fail events. These newer event types are faster and\nless crufty.\n\nThis will create an Test2::Event::Ok object for you. If $bool is false then an\nTest2::Event::Diag event will be sent as well with details about the failure. If you do not\nwant automatic diagnostics you should use the \"sendevent()\" method directly.\n\nThe third argument \"\\@onfail\") is an optional set of diagnostics to be sent in the event of\na test failure. Unlike with \"fail()\" these diagnostics must be plain strings, data\nstructures are not supported.\n\n$event = $ctx->note($message)\nSend an Test2::Event::Note. This event prints a message to STDOUT.\n\n$event = $ctx->diag($message)\nSend an Test2::Event::Diag. This event prints a message to STDERR.\n\n$event = $ctx->plan($max)\n$event = $ctx->plan(0, 'SKIP', $reason)\nThis can be used to send an Test2::Event::Plan event. This event usually takes either a\nnumber of tests you expect to run. Optionally you can set the expected count to 0 and give\nthe 'SKIP' directive with a reason to cause all tests to be skipped.\n\n$event = $ctx->skip($name, $reason);\nSend an Test2::Event::Skip event.\n\n$event = $ctx->bail($reason)\nThis sends an Test2::Event::Bail event. This event will completely terminate all testing.\n\n$event = $ctx->sendev2(%facets)\nThis lets you build and send a V2 event directly from facets. The event is returned after it\nis sent.\n\nThis example sends a single assertion, a note (comment for stdout in Test::Builder talk) and\nsets the plan to 1.\n\nmy $event = $ctx->sendevent(\nplan   => {count => 1},\nassert => {pass  => 1, details => \"A passing assert\"},\ninfo => [{tag => 'NOTE', details => \"This is a note\"}],\n);\n\n$event = $ctx->builde2(%facets)\nThis is the same as \"sendev2()\", except it builds and returns the event without sending it.\n\n$event = $ctx->sendev2andrelease($Type, %parameters)\nThis is a combination of \"sendev2()\" and \"release()\".\n\nsub shorthand {\nmy $ctx = context();\nreturn $ctx->sendev2andrelease(assert => {pass => 1, details => 'foo'});\n}\n\nsub longform {\nmy $ctx = context();\nmy $event = $ctx->sendev2(assert => {pass => 1, details => 'foo'});\n$ctx->release;\nreturn $event;\n}\n\n$event = $ctx->sendevent($Type, %parameters)\nIt is better to use sendev2() in new code.\n\nThis lets you build and send an event of any type. The $Type argument should be the event\npackage name with \"Test2::Event::\" left off, or a fully qualified package name prefixed with\na '+'. The event is returned after it is sent.\n\nmy $event = $ctx->sendevent('Ok', ...);\n\nor\n\nmy $event = $ctx->sendevent('+Test2::Event::Ok', ...);\n\n$event = $ctx->buildevent($Type, %parameters)\nIt is better to use buildev2() in new code.\n\nThis is the same as \"sendevent()\", except it builds and returns the event without sending\nit.\n\n$event = $ctx->sendeventandrelease($Type, %parameters)\nIt is better to use sendev2andrelease() in new code.\n\nThis is a combination of \"sendevent()\" and \"release()\".\n\nsub shorthand {\nmy $ctx = context();\nreturn $ctx->sendeventandrelease(Pass => { name => 'foo' });\n}\n\nsub longform {\nmy $ctx = context();\nmy $event = $ctx->sendevent(Pass => { name => 'foo' });\n$ctx->release;\nreturn $event;\n}\n",
            "subsections": []
        },
        "HOOKS": {
            "content": "There are 2 types of hooks, init hooks, and release hooks. As the names suggest, these hooks are\ntriggered when contexts are created or released.\n\nINIT HOOKS\nThese are called whenever a context is initialized. That means when a new instance is created.\nThese hooks are NOT called every time something requests a context, just when a new one is\ncreated.\n\nGLOBAL\nThis is how you add a global init callback. Global callbacks happen for every context for any\nhub or stack.\n\nTest2::API::test2addcallbackcontextinit(sub {\nmy $ctx = shift;\n...\n});\n\nPER HUB\nThis is how you add an init callback for all contexts created for a given hub. These callbacks\nwill not run for other hubs.\n\n$hub->addcontextinit(sub {\nmy $ctx = shift;\n...\n});\n\nPER CONTEXT\nThis is how you specify an init hook that will only run if your call to \"context()\" generates a\nnew context. The callback will be ignored if \"context()\" is returning an existing context.\n\nmy $ctx = context(oninit => sub {\nmy $ctx = shift;\n...\n});\n\nRELEASE HOOKS\nThese are called whenever a context is released. That means when the last reference to the\ninstance is about to be destroyed. These hooks are NOT called every time \"$ctx->release\" is\ncalled.\n\nGLOBAL\nThis is how you add a global release callback. Global callbacks happen for every context for any\nhub or stack.\n\nTest2::API::test2addcallbackcontextrelease(sub {\nmy $ctx = shift;\n...\n});\n\nPER HUB\nThis is how you add a release callback for all contexts created for a given hub. These callbacks\nwill not run for other hubs.\n\n$hub->addcontextrelease(sub {\nmy $ctx = shift;\n...\n});\n\nPER CONTEXT\nThis is how you add release callbacks directly to a context. The callback will ALWAYS be added\nto the context that gets returned, it does not matter if a new one is generated, or if an\nexisting one is returned.\n\nmy $ctx = context(onrelease => sub {\nmy $ctx = shift;\n...\n});\n",
            "subsections": []
        },
        "THIRD PARTY META-DATA": {
            "content": "This object consumes Test2::Util::ExternalMeta which provides a consistent way for you to attach\nmeta-data to instances of this class. This is useful for tools, plugins, and other extensions.\n",
            "subsections": []
        },
        "SOURCE": {
            "content": "The source code repository for Test2 can be found at http://github.com/Test-More/test-more/.\n",
            "subsections": []
        },
        "MAINTAINERS": {
            "content": "Chad Granum <exodist@cpan.org>\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "Chad Granum <exodist@cpan.org>\nKent Fredric <kentnl@cpan.org>\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright 2020 Chad Granum <exodist@cpan.org>.\n\nThis program is free software; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n\nSee http://dev.perl.org/licenses/\n",
            "subsections": []
        }
    },
    "summary": "Test2::API::Context - Object to represent a testing context.",
    "flags": [],
    "examples": [],
    "see_also": []
}