After watching a lot of test-related talks at YAPC::EU::2009, I finally got 'infected' with the "Code Should First Run In A Test" virus, so i'm currently thinking of a way to convert various utility scripts to a testable form. I think I have nailed a workable solution, but some monk wisdom would be welcome.

So far, the requirements are:

For now, i ended up with something like this (inspired mainly by How a script becomes a module):
######## foo.pl ############ #!/usr/bin/perl use strict; use warnings; MyApp->import( 'run' ); run() unless caller(); package MyApp; BEGIN { use Exporter 'import'; our @EXPORT_OK = qw(run mysub); } sub run { my $result = mysub(); print "$result\n"; } sub mysub { return "mysub called"; } ########## foo.t ############# #!/usr/bin/perl use strict; use warnings; use Test::Simple tests => 1; require 'foo.pl'; MyApp->import(qw(mysub)); ok ( mysub() =~ 'mysub' , '&mysub successfully imported' );
Now I'm satisfied:

All this being said, I think it's clear enough to show to people less Perl-inclined and to help preach the benefits of testing, even for sysadmin scripts. Any improvement ideas?


In reply to Guidelines for creating self-contained testable scripts by rpetre

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.