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

Perhaps its just the flu ravaging our household this week that has muddled my brain, but nothing occurs to me here. I'm adding some new functionality to a rather large application I wrote several years ago before I learned to write test suites and and create object methods. A few pieces of it are broken off into loadable modules, but thousands of lines of code at included in a single .cgi script.

I am doing some work on a subroutine of that cgi script and I figure this is as good a place as any for which to start writing a test suite. But how do I "use script.cgi;" and test script::method(), without first rewriting it to break that function off into a distinct module? This needs to be a quick task, not a major distraction.

Any ideas would be appreciated.

-- Hugh

if( $lal && $lol ) { $life++; }
  • Comment on How do I test a cgi script's subroutines?

Replies are listed 'Best First'.
Re: How do I test a cgi script's subroutines?
by chromatic (Archbishop) on Oct 12, 2006 at 23:52 UTC

    The easiest approach is to break it into a separate module; it's really not that difficult.

    Alternately, if the invocation is pretty simple, you can wrap everything in main() and call that only if you have no caller.

    main() unless caller(); sub main { my $q = CGI->new(); # .... }

    Then do or require the script and test it as normal.

Re: How do I test a cgi script's subroutines?
by brian_d_foy (Abbot) on Oct 13, 2006 at 04:15 UTC

    I talk about this at length in How a script becomes a module, which is workign it's way into a chapter in Mastering Perl. chromatic gives you the secret, but I show a full example of using it.

    If you don't like the caller idea, you might just break out the subroutines into their own file and load that file with require. You don't need to write a full module: you're just pulling in code that used to be there but is now stored in a separate file. Once in the separate file, you can easily test the individual subroutines without executing any code until you want to.

    Good luck :)

    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review
Re: How do I test a cgi script's subroutines?
by spatterson (Pilgrim) on Oct 16, 2006 at 09:47 UTC
    I tend to write CGI scripts in a c-ish manner, so there'll be a sub for each page-output & often some support subs, then main() comes down to an if statement on 1 parameter:
    ## main foo starts my $run = param("run"); if ($run eq 'sub_1') { sub_1; } elsif ($run eq 'sub_2') { sub_2; } else { start_page }
    Very handy for testing as I can then call each sub individually.

    just another cpan module author