Apache::TestUtil(3pm)
β¨ NAME β¨
Apache::TestUtil(3pm) β bestie, this is your utility belt for writing tests, and honestly it's giving organized queen energy πβ¨
π SYNOPSIS π
use Apache::Test;
use Apache::TestUtil;
ok t_cmp("foo", "foo", "sanity check");
t_write_file("filename", @content);
my $fh = t_open_file($filename);
t_mkdir("/foo/bar");
t_rmtree("/foo/bar");
t_is_equal($a, $b);
π DESCRIPTION π
Apache::TestUtil automatically exports a bunch of functions that are genuinely useful when you're writing tests. No cap, it just hands them over π
Every file and directory you create with these functions gets automatically destroyed at the end of the program's execution (via an END block). So like, don't use these outside of tests that are supposed to clean up all the directories and files when they're done, okay? That's the vibe. π§Ήβ¨
π§ FUNCTIONS π§
t_cmp()
t_cmp($received, $expected, $comment);
t_cmp() prints the values of $comment, $expected and $received. e.g.:</p>
t_cmp(1, 1, "1 == 1?");
prints:
# testing : 1 == 1?
# expected: 1
# received: 1
then it returns the result of comparison of the $expected and the $received variables. Usually, the return value of this function is fed directly to the ok() function, like this:
ok t_cmp(1, 1, "1 == 1?");
the third argument ($comment) is optional, mostly useful for telling what the comparison is trying to do. lowkey a nice little note-to-self moment π
It is valid to use undef as an expected value. Therefore:
my $foo;
t_cmp(undef, $foo, "undef == undef?");
will return a true value. slay π
You can compare any two data-structures with t_cmp(). Just make sure that if you pass non-scalars, you have to pass their references. The datastructures can be deeply nested. For example you can compare:
t_cmp({1 => [2..3,{5..8}], 4 => [5..6]},
{1 => [2..3,{5..8}], 4 => [5..6]},
"hash of array of hashes");
You can also compare the second argument against the first as a regex. Use the qr// function in the second argument. For example:
t_cmp("abcd", qr/^abc/, "regex compare");
will do:
"abcd" =~ /^abc/;
This function is exported by default. π
t_filepath_cmp()
This function is used to compare two filepaths via t_cmp(). For non-Win32, it simply uses t_cmp() for the comparison, but for Win32, Win32::GetLongPathName() is invoked to convert the first two arguments to their DOS long pathname. This is useful when there is a possibility the two paths being compared are not both represented by their long or short pathname.
This function is exported by default. πΈ
t_debug()
t_debug("testing feature foo");
t_debug("test", [1..3], 5, {a=>[1..5]});
t_debug() prints out any datastructure while prepending # at the beginning of each line, to make the debug printouts comply with Test::Harness's requirements. This function should be always used for debug prints, since if in the future the debug printing will change (e.g. redirected into a file) your tests won't need to be changed. future-proofing, we love to see it β¨
the special global variable $Apache::TestUtil::DEBUG_OUTPUT can be used to redirect the output from t_debug() and related calls such as t_write_file(). for example, from a server-side test you would probably need to redirect it to STDERR:
sub handler {
plan $r, tests => 1;
local $Apache::TestUtil::DEBUG_OUTPUT = \*STDERR;
t_write_file('/tmp/foo', 'bar');
...
}
left to its own devices, t_debug() will collide with the standard HTTP protocol during server-side tests, resulting in a situation both confusing difficult to debug. but STDOUT is left as the default, since you probably don't want debug output under normal circumstances unless running under verbose mode. π
This function is exported by default. π¦
t_write_test_lib()
t_write_test_lib($filename, @lines)
t_write_test_lib()</purl> creates a new file at $filename or overwrites the existing file with the content passed in @lines. The file is created in a temporary directory which is added to @INC at test configuration time. It is intended to be used for creating temporary packages for testing which can be modified at run time, see the Apache::Reload unit tests for an example. π§ͺ
t_write_file()
t_write_file($filename, @lines);
t_write_file() creates a new file at $filename or overwrites the existing file with the content passed in @lines. If only the $filename is passed, an empty file will be created.
If parent directories of $filename don't exist they will be automagically created. β¨
The generated file will be automatically deleted at the end of the program's execution.
This function is exported by default. π
t_append_file()
t_append_file($filename, @lines);
t_append_file() is similar to t_write_file(), but it doesn't clobber existing files and appends @lines to the end of the file. If the file doesn't exist it will create it. no destruction, just addition π«Ά
If parent directories of $filename don't exist they will be automagically created.
The generated file will be registered to be automatically deleted at the end of the program's execution, only if the file was created by t_append_file().
This function is exported by default. π
t_write_shell_script()
Apache::TestUtil::t_write_shell_script($filename, @lines);
Similar to t_write_file() but creates a portable shell/batch script. The created filename is constructed from $filename and an appropriate extension automatically selected according to the platform the code is running under. π
It returns the extension of the created file.
t_write_perl_script()
Apache::TestUtil::t_write_perl_script($filename, @lines);
Similar to t_write_file() but creates a executable Perl script with correctly set shebang line. πͺ
t_open_file()
my $fh = t_open_file($filename);
t_open_file() opens a file $filename for writing and returns the file handle to the opened file.
If parent directories of $filename don't exist they will be automagically created. β¨
The generated file will be automatically deleted at the end of the program's execution.
This function is exported by default. π
t_mkdir()
t_mkdir($dirname);
t_mkdir() creates a directory $dirname. The operation will fail if the parent directory doesn't exist.
If parent directories of $dirname don't exist they will be automagically created.
The generated directory will be automatically deleted at the end of the program's execution.
This function is exported by default. π
t_rmtree()
t_rmtree(@dirs);
t_rmtree() deletes the whole directories trees passed in @dirs. bye bye bye π§Ή
This function is exported by default. π₯
t_chown()
Apache::TestUtil::t_chown($file);
Change ownership of $file to the test's User/Group. This function is noop on platforms where chown(2) is unsupported (e.g. Win32). πͺ
t_is_equal()
t_is_equal($a, $b);
t_is_equal() compares any two datastructures and returns 1 if they are exactly the same, otherwise 0. The datastructures can be nested hashes, arrays, scalars, undefs or a combination of any of these. See t_cmp() for an example.
If $b is a regex reference, the regex comparison "$a =~ $b" is performed. For example:
t_is_equal($server_version, qr{^Apache});
If comparing non-scalars make sure to pass the references to the datastructures.
This function is exported by default. β
t_server_log_error_is_expected()
If the handler's execution results in an error or a warning logged to the error_log file which is expected, it's a good idea to have a disclaimer printed before the error itself, so one can tell real problems with tests from expected errors. For example when testing how the package behaves under error conditions the error_log file might be loaded with errors, most of which are expected. π
For example if a handler is about to generate a run-time error, this function can be used as:
use Apache::TestUtil;
...
sub handler {
my $r = shift;
...
t_server_log_error_is_expected();
die "failed because ...";
}
After running this handler the error_log file will include:
*** The following error entry is expected and harmless ***
[Tue Apr 01 14:00:21 2003] [error] failed because ...
When more than one entry is expected, an optional numerical argument, indicating how many entries to expect, can be passed. For example:
t_server_log_error_is_expected(2);
will generate:
*** The following 2 error entries are expected and harmless ***
If the error is generated at compile time, the logging must be done in the BEGIN block at the very beginning of the file:
BEGIN {
use Apache::TestUtil;
t_server_log_error_is_expected();
}
use DOES_NOT_exist;
After attempting to run this handler the error_log file will include:
*** The following error entry is expected and harmless ***
[Tue Apr 01 14:04:49 2003] [error] Can't locate "DOES_NOT_exist.pm"
in @INC (@INC contains: ...
Also see t_server_log_warn_is_expected() which is similar but used for warnings.
This function is exported by default. π
t_server_log_warn_is_expected()
t_server_log_warn_is_expected() generates a disclaimer for expected warnings.
See the explanation for t_server_log_error_is_expected() for more details.
This function is exported by default. πΈ
t_client_log_error_is_expected()
t_client_log_error_is_expected() generates a disclaimer for expected errors. But in contrast to t_server_log_error_is_expected() called by the client side of the script.
See the explanation for t_server_log_error_is_expected() for more details.
For example the following client script fails to find the handler:
use Apache::Test;
use Apache::TestUtil;
use Apache::TestRequest qw(GET);
plan tests => 1;
t_client_log_error_is_expected();
my $url = "/error_document/cannot_be_found";
my $res = GET($url);
ok t_cmp(404, $res->code, "test 404");
so after you run this test, your error_log file is gonna have an entry in it that looks a lil something like this:
*** The following error entry is expected and harmless ***
[Tue Apr 01 14:02:55 2003] [error] [client 127.0.0.1]
File does not exist: /tmp/test/t/htdocs/error
and if you're expecting more than one entry, you can pass an optional numerical argument that says how many entries you expect, bestie:
t_client_log_error_is_expected(2);
which will then generate:
*** The following 2 error entries are expected and harmless ***
this function is exported by default β¨
t_client_log_warn_is_expected() π
t_client_log_warn_is_expected() generates a disclaimer for expected warnings on the client side.
for the deets, go read the explanation for t_client_log_error_is_expected() β same energy, just for warnings.
this function is exported by default β¨
t_catfile('a', 'b', 'c')
this one is basically File::Spec->catfile, BUT on Win32 it'll use Win32::GetLongpathName() to convert the result into a long path name (only if the result is an absolute file, iykyk). this function is not exported by default π
t_catfile_apache('a', 'b', 'c')
this one is basically File::Spec::Unix->catfile, but again on Win32 it'll use Win32::GetLongpathName() to convert the result to a long path name (again, only if the result is an absolute file). it's useful when you're comparing something against what Apache hands back, since Apache uses a Unix-style spec with forward slashes as directory separators π the function is not exported by default.
t_start_error_log_watch(), t_finish_error_log_watch()
this lil duo gives you an easy-peasy interface for checking whether any particular message(s) showed up (or did NOT show up) in the httpd error_log β the ones that the httpd daemon itself generated as part of a test suite. and it's likely that you'll wanna set this up with a call to one of the t_*_is_expected() functions first π
t_start_error_log_watch();
do_it;
ok grep {...} t_finish_error_log_watch();
other usage case? say a handler is out here emitting some debugging messages into the error_log. if that handler gets called in a whole series of other test cases, finding the relevant messages by hand is lowkey a nightmare π in those situations, this sequence in the test file might help:
t_start_error_log_watch();
GET '/this/or/that';
t_debug t_finish_error_log_watch();
t_start_file_watch()
Apache::TestUtil::t_start_file_watch('access_log');
this function is similar to t_start_error_log_watch() but it lets you watch files other than error_log. it opens the given file and positions the file pointer at its end π«Ά so any later calls to t_read_file_watch() or t_finish_file_watch() will read the lines that got appended after this call.
you can pass a file name as the parameter. if it's omitted or undefined, the error_log gets opened instead. relative file names are evaluated relative to the directory that contains error_log.
if the file you named doesn't exist (yet), no error is returned β the vibe is that it's just assumed to appear soon. in that case t_{read,finish}_file_watch() will open the file silently and read from the beginning β¨
t_read_file_watch(), t_finish_file_watch()
local $/ = "\n";
$line1=Apache::TestUtil::t_read_file_watch('access_log');
$line2=Apache::TestUtil::t_read_file_watch('access_log');
@lines=Apache::TestUtil::t_finish_file_watch('access_log');
this pair reads the file that was opened by t_start_error_log_watch().
just like the core readline function, they return one line if they're called in scalar context, otherwise they return all lines until end of file π
before calling readline, these functions do not set $/ the way t_finish_error_log_watch does. so if the file, say, has a fixed record length, do this instead:
{
local $/=\$record_length;
@lines=t_finish_file_watch($name);
}
t_file_watch_for()
@lines=Apache::TestUtil::t_file_watch_for('access_log',
qr/condition/,
$timeout);
this function reads the file from the current position and hunts for the first line that matches qr/condition/. if it can't find such a line before hitting end of file, it pauses and retries until either a matching line shows up or the timeout (in seconds) is reached β³
in scalar or void context, only the matching line is returned. in list context, all the read lines are returned, with the matching one sitting in last position.
the function uses "\n" as the end-of-line marker and waits for complete lines β¨
and here's the tea about the timeout: even though you can specify it with sub-second precision, it's not very accurate. it simply gets multiplied by 10, and that result is used as a maximum loop count. for the intended purpose, that should be good enough, ngl.
use this function to check for logfile entries when you can't be sure they're already written by the time your test program reaches that point β for example, to check for messages written in a PerlCleanupHandler or a PerlLogHandler π
ok t_file_watch_for 'access_log', qr/expected log entry/, 2;
this call reads the access_log and waits for a maximum of 2 seconds for the expected entry to appear π
π AUTHOR
Stas Bekman <stas@stason.org>, Torsten FΓΆrtsch <torsten.foertsch@gmx.net>
π SEE ALSO
okay and that's a wrap bestie π this page came to you courtesy of perl v5.42.3, dated 2026-08-20 β go forth and test slayfully, you absolute icon π β¨
π¦ where this page comes from
- ubuntu stonking: libapache2-mod-perl2 2.0.13-2build3 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms