mp has asked for the wisdom of the Perl Monks concerning the following question:

I am writing a self-contained perl script (no reliance on external modules), and I would like to glassbox/whitebox subroutines in it from a separate test script without running the code in package main in the original perl script. What is a good way to go about doing this?

The only thing I have come up with so far is to add some special comments before and after the code that I don't want to execute under test, then make the test script read the script under test into a scalar or array, strip out the code that should not be executed, then eval what is left over to create the package and subroutines/methods, then run the tests against those subroutines. Is there a way of achieving the same effect without jumping through the extra hoops? Is there a way for a perl script to tell if it is being run from a shell versus being 'require'-ed? If it makes a difference, the script will be run on Win32.

To clarify, here is some example code:
In script_under_test:
#!/usr/local/bin/perl -w #<ignore_during_test> my $obj = SupportingPackage->new; $obj->do_something; $obj->do_something_else; #</ignore_during_test> package SupportingPackage; sub new { bless {}, $_[0]; } sub do_something { 1;} sub do_something_else { 2;}


In 01test.t:

use strict; use warnings; use Test::More tests => 2; #... pull in package SupportingPackage somehow #without running code that is in main ... # then: ok(my $obj = SupportingPackage->new); can_ok($obj, 'do_something'); is($obj->do_something, 1); can_ok($obj, 'do_something_else'); is($obj->do_something_else, 2); # etc.

Replies are listed 'Best First'.
Re: Testing subroutines from a script
by chromatic (Archbishop) on Aug 30, 2002 at 19:32 UTC

    If you're running your tests under Test::Harness, it'll set $ENV{HARNESS_ACTIVE} for you. You can then write:

    sub main { # everything you'd normally execute here } main() unless ($ENV{HARNESS_ACTIVE});
      Thank you. This works great. I added
      BEGIN { $ENV{HARNESS_ACTIVE} = 1 }
      to the test script so that it will work regardless of whether it is invoked under Test::Harness.
Re: Testing subroutines from a script
by mp (Deacon) on Aug 30, 2002 at 19:22 UTC
    I realize that I could just add a test mode to the script_under_test, but would prefer not to do that.