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.

In reply to Testing subroutines from a script by mp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.