Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Test that a module's SYNOPSIS code really runs

by Jeffrey Kegler (Friar)
on Oct 17, 2007 at 01:42 UTC ( #645345=snippet: print w/ replies, xml ) Need Help??

Description: In reformatting the code in the POD's SYNOPSIS section of a CPAN module I'm writing, it struck me that it's easy to accidentally break the code. Nice to have at least the code in the SYNOPSIS run! So I created a synopsis.t.

UPDATE: Fixed two bugs. synopsis.t no longer reports success if it can't open the POD file. And it no longer depends on the file being in a specific location.

enjoy, Jeffrey Kegler


use strict;
use warnings;
use English;
use Test::More tests => 2;

# Module specific stuff here -- setup code
use Scalar::Util qw(weaken isweak);

BEGIN { use_ok('Test::Weaken') };

package Module::Test_me1; sub new { bless [], (shift); }
package Module::Test_me2; sub new { bless [], (shift); }

package main;

# slurp in the code
my $filename = $INC{"Test/Weaken.pm"};
unless (open(CODE, $filename)) {
    fail("Cannot open $filename");
    exit(1);
}
$RS = undef;
my $code = <CODE>;

# remove stuff before and after the SYNOPSIS
$code =~ s/.*^=head1\s*SYNOPSIS\s*$//xms;
$code =~ s/^=cut.*\z//xms;

# remove POD text
$code =~ s/^\S[^\n]*$//xmsg;

# compute line count -- don't include whitespace lines
$code =~ s/^\s*$//xmsg;
my @lines = split(/\n/, $code);
my $line_count = @lines;

# check for absence of code
if ($code =~ /\A\s*\z/xms) {
    fail("No code in synopsis");
    exit(1);
}

# Try the code and see what happens
eval $code;

# Report the results
if ($@) {
    fail("Synopsis code failed: $@");
} else {
    pass("Synopsis has $line_count lines of good code");
}


Comment on Test that a module's SYNOPSIS code really runs
Download Code
Re: Test that a module's SYNOPSIS code really runs
by erroneousBollock (Curate) on Oct 17, 2007 at 08:01 UTC
    Most of the non-running code examples in synopses could be classified as "fill in the blanks" omissions and "assuming an environment" omissions.

    For "fill in the blanks", Perl 6's ... (yada yada yada) operator will mostly fix that. This applies generally to higher-order libraries, visitors and event-generators that take callbacks.

    For "assuming an environment", it would be more difficult, as you can't really know what environment the author expects of the end-user.

    -David

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://645345]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2014-07-11 03:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (217 votes), past polls