File: Synopsis.pm

package info (click to toggle)
libtest-synopsis-perl 0.11-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 304 kB
  • ctags: 23
  • sloc: perl: 207; makefile: 2
file content (382 lines) | stat: -rw-r--r-- 11,172 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package Test::Synopsis;

use strict;
use warnings;
use 5.008_001;

our $VERSION = '0.11'; # VERSION

use base qw( Test::Builder::Module );
our @EXPORT = qw( synopsis_ok all_synopsis_ok );

use ExtUtils::Manifest qw( maniread );
my %ARGS;
 # = ( dump_all_code_on_error => 1 ); ### REMOVE THIS FOR PRODUCTION!!!
sub all_synopsis_ok {
    %ARGS = @_;

    my $manifest = maniread();
    my @files = grep m!^lib/.*\.p(od|m)$!, keys %$manifest;
    __PACKAGE__->builder->plan(@files
        ? (tests => 1 * @files)
        : (skip_all => 'No files in lib to test')
    );
    synopsis_ok(@files);
}

sub synopsis_ok {
    my @modules = @_;

    for my $module (@modules) {
        my($code, $line, @option) = extract_synopsis($module);
        unless ($code) {
            __PACKAGE__->builder->ok(1, "No SYNOPSIS code");
            next;
        }

        my $option = join(";", @option);
        my $test   = qq(#line $line "$module"\n$option; sub { $code });
        my $ok     = _compile($test);

        # See if the user is trying to skip this test using the =for block
        if ( !$ok and $@=~/^SKIP:.+BEGIN failed--compilation aborted/si ) {
          $@ =~ s/^SKIP:\s*//;
          $@ =~ s/\nBEGIN failed--compilation aborted at.+//s;
          __PACKAGE__->builder->skip($@, 1);
        }
        else {
          __PACKAGE__->builder->ok($ok, $module);
          __PACKAGE__->builder->diag(
              $ARGS{dump_all_code_on_error}
              ? "$@\nEVALED CODE:\n$test"
              : $@
            ) unless $ok;
        }
    }
}

my $sandbox = 0;
sub _compile {
    package
        Test::Synopsis::Sandbox;
    eval sprintf "package\nTest::Synopsis::Sandbox%d;\n%s",
      ++$sandbox, $_[0]; ## no critic
}

### WARNING: DESPITE THE NAME OF THIS SUBROUTINE (no underscore)
### IT'S A PRIVATE SUB; DO NOT USE IT DIRECTLY IN YOUR CODE!
sub extract_synopsis {
    my $file = shift;

    my $parser = Test::Synopsis::Parser->new;
    $parser->parse_from_file ($file);
    my $test_synopsis = $parser->{'test_synopsis'} || '';

    # don't want __END__ blocks in SYNOPSIS chopping our '}' in wrapper sub
    # same goes for __DATA__ and although we'll be sticking an extra '}'
    # into its contents; it shouldn't matter since the code shouldn't be
    # run anyways.
    $test_synopsis =~ s/(?=(?:__END__|__DATA__)\s*$)/}\n/m;

    # trim indent whitespace to make HEREDOCs work properly
    # we'll assume the indent of the first line is the proper indent
    # to use for the whole block
    $test_synopsis =~ s/(\A(\s+).+)/ (my $x = $1) =~ s{^$2}{}gm; $x /se;

    # Correct the reported line number of the error, depending on what
    # =for options we were supplied with.
    my $options_lines = join '', @{ $parser->{'test_synopsis_options'} };
    $options_lines = $options_lines =~ tr/\n/\n/;

    return (
      $test_synopsis,
      ($parser->{'test_synopsis_linenum'} || 0) - ($options_lines || 0),
      @{ $parser->{'test_synopsis_options'} }
    );
}

package
  Test::Synopsis::Parser; # on new line to avoid indexing

### Parser patch by Kevin Ryde

use base 'Pod::Parser';
sub new {
    my $class = shift;
    return $class->SUPER::new(
      @_, within_begin => '', test_synopsis_options => []
    );
}

sub command {
    my $self = shift;
    my ($command, $text) = @_;
    ## print "command: '$command' -- '$text'\n";

    if ($command eq 'for') {
        if ($text =~ /^test_synopsis\s+(.*)/s) {
            push @{$self->{'test_synopsis_options'}}, $1;
        }
    } elsif ($command eq 'begin') {
        $self->{'within_begin'} = $text;
    } elsif ($command eq 'end') {
        $self->{'within_begin'} = '';
    } elsif ($command eq 'pod') {
        # resuming pod, retain begin/end/synopsis state
    } else {
        # Synopsis is "=head1 SYNOPSIS" through to next command other than
        # the above "=for", "=begin", "=end", "=pod".  This means
        #     * "=for" directives for other programs are skipped
        #       (eg. HTML::Scrubber)
        #     * "=begin" to "=end" for other program are skipped
        #       (eg. Date::Simple)
        #     * "=cut" to "=pod" actual code is skipped (perhaps unlikely in
        #       practice)
        #
        # Could think about not stopping at "=head2" etc subsections of a
        # synopsis, but a synopsis with subsections usually means different
        # sample bits meant for different places and so probably won't
        # actually run.
        #
        $self->{'within_synopsis'}
          = ($command eq 'head1' && $text =~ /^SYNOPSIS\s*$/);
    }
    return '';
}

sub verbatim {
    my ( $self, $text, $linenum ) = @_;
    if ( $self->{'within_begin'} =~ /^test_synopsis\b/ ) {
        push @{$self->{'test_synopsis_options'}}, $text;

    } elsif ( $self->{'within_synopsis'} && ! $self->{'within_begin'} ) {
        $self->{'test_synopsis_linenum'} = $linenum; # first occurance
        $self->{'test_synopsis'} .= $text;
    }
    return '';
}
sub textblock {
    # ignore text paragraphs, only take "verbatim" blocks to be code
    return '';
}

1;
__END__

=encoding utf-8

=for Pod::Coverage extract_synopsis

=for stopwords Goro blogged Znet Zoffix DOHERTY Doherty
  KRYDE Ryde ZOFFIX Gr nauer GrĂ¼nauer pm HEREDOC HEREDOCs

=for test_synopsis $main::for_checked=1

=head1 NAME

Test::Synopsis - Test your SYNOPSIS code

=head1 SYNOPSIS

  # xt/synopsis.t (with Module::Install::AuthorTests)
  use Test::Synopsis;
  all_synopsis_ok();

  # Or, run safe without Test::Synopsis
  use Test::More;
  eval "use Test::Synopsis";
  plan skip_all => "Test::Synopsis required for testing" if $@;
  all_synopsis_ok();

=head1 DESCRIPTION

Test::Synopsis is an (author) test module to find .pm or .pod files
under your I<lib> directory and then make sure the example snippet
code in your I<SYNOPSIS> section passes the perl compile check.

Note that this module only checks the perl syntax (by wrapping the
code with C<sub>) and doesn't actually run the code, B<UNLESS>
that code is a C<BEGIN {}> block or a C<use> statement.

Suppose you have the following POD in your module.

  =head1 NAME

  Awesome::Template - My awesome template

  =head1 SYNOPSIS

    use Awesome::Template;

    my $template = Awesome::Template->new;
    $tempalte->render("template.at");

  =head1 DESCRIPTION

An user of your module would try copy-paste this synopsis code and
find that this code doesn't compile because there's a typo in your
variable name I<$tempalte>. Test::Synopsis will catch that error
before you ship it.

=head1 VARIABLE DECLARATIONS

Sometimes you might want to put some undeclared variables in your
synopsis, like:

  =head1 SYNOPSIS

    use Data::Dumper::Names;
    print Dumper($scalar, \@array, \%hash);

This assumes these variables like I<$scalar> are defined elsewhere in
module user's code, but Test::Synopsis, by default, will complain that
these variables are not declared:

    Global symbol "$scalar" requires explicit package name at ...

In this case, you can add the following POD sequence elsewhere in your POD:

  =for test_synopsis
  no strict 'vars'

Or more explicitly,

  =for test_synopsis
  my($scalar, @array, %hash);

Test::Synopsis will find these C<=for> blocks and these statements are
prepended before your SYNOPSIS code when being evaluated, so those
variable name errors will go away, without adding unnecessary bits in
SYNOPSIS which might confuse users.

=head1 SKIPPING TEST FROM INSIDE THE POD

You can use a C<BEGIN{}> block in the C<=for test_synopsis> to check for
specific conditions (e.g. if a module is present), and possibly skip
the test.

If you C<die()> inside the C<BEGIN{}> block and the die message begins
with sequence C<SKIP:> (note the colon at the end), the test
will be skipped for that document.

  =head1 SYNOPSIS

  =for test_synopsis BEGIN { die "SKIP: skip this pod, it's horrible!\n"; }

      $x; # undeclared variable, but we skipped the test!

  =end

=head1 EXPORTED SUBROUTINES

=head2 C<all_synopsis_ok>

  all_synopsis_ok();

  all_synopsis_ok( dump_all_code_on_error => 1 );

Checks the SYNOPSIS code in all your modules. Takes B<optional>
arguments as key/value pairs. Possible arguments are as follows:

=head3 C<dump_all_code_on_error>

  all_synopsis_ok( dump_all_code_on_error => 1 );

Takes true or false values as a value. B<Defaults to:> false. When
set to a true value, if an error is discovered in the SYNOPSIS code,
the test will dump the entire snippet of code it tried to test. Use this
if you want to copy/paste and play around with the code until the error
is fixed.

The dumped code will include any of the C<=for> code you specified (see
L<VARIABLE DECLARATIONS> section above) as well as a few internal bits
this test module uses to make SYNOPSIS code checking possible.

B<Note:> you will likely have to remove the C<#> and a space at the start
of each line (C<perl -pi -e 's/^#\s//;' TEMP_FILE_WITH_CODE>)

=head2 C<synopsis_ok>

  use Test::More tests => 1;
  use Test::Synopsis;
  synopsis_ok("t/lib/NoPod.pm");
  synopsis_ok(qw/Pod1.pm  Pod2.pm  Pod3.pm/);

Lets you test a single file. B<Note:> you must setup your own plan if
you use this subroutine (e.g. with C<< use Test::More tests => 1; >>).
B<Takes> a list of filenames for documents containing SYNOPSIS code to test.

=head1 CAVEATS

This module will not check code past the C<__END__> or
C<__DATA__> tokens, if one is
present in the SYNOPSIS code.

This module will actually execute C<use> statements and any code
you specify in the C<BEGIN {}> blocks in the SYNOPSIS.

If you're using HEREDOCs in your SYNOPSIS, you will need to place
the ending of the HEREDOC at the same indent as the
first line of the code of your SYNOPSIS.

The code from multiple files will be executed under the same perl process,
so it's possible to run into issues such as, say, sub redefinition
warnings. Currently, there's no plan to fix this, but patches are welcome.
Redefinition warnings can be turned off with

  =for test_synopsis
  no warnings 'redefine';

=head1 REPOSITORY

Fork this module on GitHub:
L<https://github.com/miyagawa/Test-Synopsis>

=head1 BUGS

To report bugs or request features, please use
L<https://github.com/miyagawa/Test-Synopsis/issues>

If you can't access GitHub, you can email your request
to C<bug-Test-Synopsis at rt.cpan.org>

=head1 AUTHOR

Tatsuhiko Miyagawa E<lt>miyagawa@bulknews.netE<gt>

Goro Fuji blogged about the original idea at
L<http://d.hatena.ne.jp/gfx/20090224/1235449381> based on the testing
code taken from L<Test::Weaken>.

=head1 MAINTAINER

Zoffix Znet <cpan (at) zoffix.com>

=head1 CONTRIBUTORS

=over 4

=item * Kevin Ryde (L<KRYDE|https://metacpan.org/author/KRYDE>)

=item * Marcel GrĂ¼nauer (L<MARCEL|https://metacpan.org/author/MARCEL>)

=item * Mike Doherty (L<DOHERTY|https://metacpan.org/author/DOHERTY>)

=item * Zoffix Znet (L<ZOFFIX|https://metacpan.org/author/ZOFFIX>)

=back

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=head1 COPYRIGHT

This library is Copyright (c) Tatsuhiko Miyagawa

=head1 SEE ALSO

L<Test::Pod>, L<Test::UseAllModules>, L<Test::Inline>

=cut