O'Reilly logo

Perl Testing: A Developer's Notebook by Chromatic, Ian Langworth

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Overriding Live Code

Plenty of useful modules do their work procedurally, without the modularity of functions and objects. Many modules, written before object orientation became popular, use package variables to control their behavior. To test your code fully, sometimes you have to reach inside those packages to change their variables. Tread lightly, though. Tricky testing code is harder to write and harder to debug.

How do I do that?

Suppose that you have a simple logging package. Its single subroutine, log_message(), takes a message and logs it to a filehandle. It also adds a time and date stamp to the start of the message and information about the function’s caller to the end, if two package global variables, $REPORT_TIME and $REPORT_CALLER, are true.

Save the following code to lib/Logger.pm:

    package Logger;

    use strict;

    our $OUTPUT_FH     = *STDERR;
    our $REPORT_TIME   = 1;
    our $REPORT_CALLER = 1;

    sub log_message
    {
        my ($package, $file, $line)  = caller();
        my $time                     = localtime();

        my $message                  = '';
        $message                    .= "[$time] " if $REPORT_TIME;
        $message                    .= shift;
        $message                    .= " from $package:$line in $file"
                                                  if $REPORT_CALLER;
        $message                    .= "\n";

        write_message( $message );
    }

    sub write_message
    {
        my $message = shift;
        print $OUTPUT_FH $message;
    }

    1;

Fortunately, the module is simple enough, so it’s straightforward to test. The difficult part is figuring out how to capture the output from write_message(). You could test both functions at the same time, but it’s easier to test features in isolation, both ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required