[tpm] testing; using eval to catch an error in a module

Michael Graham magog at the-wire.com
Sat Aug 29 11:33:42 PDT 2009

If you're trying to catch compile-time errors, you need to wrap the
'use' or 'require' in an eval as well:
    BEGIN {
        eval {
            require Some::Module;
        if ($@) {
            print "The module could not be loaded: $@\n";

Perl has a highly evolved testing culture, and there are lots of
test-related modules on CPAN.  You'll be better off in the long run if
you learn how to do standard Perl testing, than if you reinvent the
wheel with one-off testing scripts.

The basic testing module is Test::More.  If you learn nothing else,
learn how to use Test::More.

Here's an (untested) Test::More-based script that does what you're 
doing by hand:

    # save this as test.t

    use Test::More;

    BEGIN { use_ok('Some::Module'); }
    eval {
        $an->foo("some Illegal arg");

    my $e = $@; 
    ok($e, "The module 'die'ed as planned and emitted error: $e");


You run this with:

    $ prove test.t

There are other modules that add syntactic sugar for specific testing
scenarios.  In your case, you might look at Test::Exception:


    use Test::Exception;

    BEGIN { use_ok('Some::Module'); }

    throws_ok { $an->foo("some Illegal arg") } 
        qr/that's an Illegal arg, you insensitive clod!/, 
        "The module 'die'ed as planned and emitted an error";



On Sat, 29 Aug 2009 13:01:04 -0400
Madison Kelly <linux at alteeve.com> wrote:

> Hi all,
>    I've been working on a test script for my module suite/hobby and
> I've been having a bit of trouble. I want to trap errors in the
> module without killing the test script. I was hoping I could do
> something like:
> eval {
> 	$an->foo("some Illegal arg");
> }
> if ($@)
> {
> 	print "The module 'die'ed as planned and emitted error:
> [$@]\n"; }
> else
> {
> 	die "Testing of module death failed as [$@] wasn't set.\n";
> }
> I think this is because it's not a compile time error, but the
> perldoc for eval shows trapping for a divide by zero error, which as
> I understand it would trigger on execution, not compile.
> Am I missing something fundamental? Should I be approaching my
> testing in a different way?
> I'm sorry is this is a simple question... I've been trying to make
> sure I've got a good handle on a lot of perl topics recently and am
> starting to get a wee blender-brain.
> Thanks!
> Madi
> _______________________________________________
> toronto-pm mailing list
> toronto-pm at pm.org
> http://mail.pm.org/mailman/listinfo/toronto-pm

More information about the toronto-pm mailing list