Testing that darned filehandle

It wasn't fun finding out that some legacy code creates a bunch of filehandles on the fly to do logging.

package Some::Client;
use Some::Logging::Module;

# later ...
print MAGICLOGHANDLE $some_data;

That MAGICLOGHANDLE is dynamically generated and shoved into my namespace (along with a ton of other handles, one per log). So I needed to test what was being printed to it. Fortunately, Perl's dynamism makes this really, really easy.

Here's the basics:

use Test::Class::Most parent => 'My::Test::Class';

use Some::Client;
use IO::Scalar;

sub logging : Tests {
    my $test = shift

    my $SH = IO::Scalar->new(\my $data);
    no warnings 'redefine';
    local *Some::Client::MAGICLOGHANDLE = $SH;

    # run a bunch of code
    like $data, qr/whateever should be in the log/,
        '... I love diddling namespaces;

Yup. It's just that easy to hijack a filehandle for my own nefarious purposes.

Leave a comment

About Ovid

user-pic Freelance Perl/Testing/Agile consultant and trainer. See http://www.allaroundtheworld.fr/ for our services. If you have a problem with Perl, we will solve it for you. And don't forget to buy my book! http://www.amazon.com/Beginning-Perl-Curtis-Poe/dp/1118013840/