xref: /openbsd-src/gnu/usr.bin/perl/cpan/podlators/t/lib/Test/RRA.pm (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1# Helper functions for test programs written in Perl.
2#
3# This module provides a collection of helper functions used by test programs
4# written in Perl.  This is a general collection of functions that can be used
5# by both C packages with Automake and by stand-alone Perl modules.  See
6# Test::RRA::Automake for additional functions specifically for C Automake
7# distributions.
8#
9# SPDX-License-Identifier: MIT
10
11package Test::RRA;
12
13use 5.006;
14use strict;
15use warnings;
16
17use Exporter;
18use File::Temp;
19use Test::More;
20
21# For Perl 5.006 compatibility.
22## no critic (ClassHierarchies::ProhibitExplicitISA)
23
24# Declare variables that should be set in BEGIN for robustness.
25our (@EXPORT_OK, @ISA, $VERSION);
26
27# Set $VERSION and everything export-related in a BEGIN block for robustness
28# against circular module loading (not that we load any modules, but
29# consistency is good).
30BEGIN {
31    @ISA       = qw(Exporter);
32    @EXPORT_OK = qw(
33      is_file_contents skip_unless_author skip_unless_automated use_prereq
34    );
35
36    # This version should match the corresponding rra-c-util release, but with
37    # two digits for the minor version, including a leading zero if necessary,
38    # so that it will sort properly.
39    $VERSION = '7.01';
40}
41
42# Compare a string to the contents of a file, similar to the standard is()
43# function, but to show the line-based unified diff between them if they
44# differ.
45#
46# $got      - The output that we received
47# $expected - The path to the file containing the expected output
48# $message  - The message to use when reporting the test results
49#
50# Returns: undef
51#  Throws: Exception on failure to read or write files or run diff
52sub is_file_contents {
53    my ($got, $expected, $message) = @_;
54
55    # If they're equal, this is simple.
56    open(my $fh, '<', $expected) or BAIL_OUT("Cannot open $expected: $!\n");
57    my $data = do { local $/ = undef; <$fh> };
58    close($fh) or BAIL_OUT("Cannot close $expected: $!\n");
59    if ($got eq $data) {
60        is($got, $data, $message);
61        return;
62    }
63
64    # Otherwise, we show a diff, but only if we have IPC::System::Simple.
65    eval { require IPC::System::Simple };
66    if ($@) {
67        ok(0, $message);
68        return;
69    }
70
71    # They're not equal.  Write out what we got so that we can run diff.
72    my $tmp     = File::Temp->new();
73    my $tmpname = $tmp->filename;
74    print {$tmp} $got or BAIL_OUT("Cannot write to $tmpname: $!\n");
75    my @command = ('diff', '-u', $expected, $tmpname);
76    my $diff = IPC::System::Simple::capturex([0 .. 1], @command);
77    diag($diff);
78
79    # Remove the temporary file and report failure.
80    ok(0, $message);
81    return;
82}
83
84# Skip this test unless author tests are requested.  Takes a short description
85# of what tests this script would perform, which is used in the skip message.
86# Calls plan skip_all, which will terminate the program.
87#
88# $description - Short description of the tests
89#
90# Returns: undef
91sub skip_unless_author {
92    my ($description) = @_;
93    if (!$ENV{AUTHOR_TESTING}) {
94        plan skip_all => "$description only run for author";
95    }
96    return;
97}
98
99# Skip this test unless doing automated testing or release testing.  This is
100# used for tests that should be run by CPAN smoke testing or during releases,
101# but not for manual installs by end users.  Takes a short description of what
102# tests this script would perform, which is used in the skip message.  Calls
103# plan skip_all, which will terminate the program.
104#
105# $description - Short description of the tests
106#
107# Returns: undef
108sub skip_unless_automated {
109    my ($description) = @_;
110    for my $env (qw(AUTOMATED_TESTING RELEASE_TESTING AUTHOR_TESTING)) {
111        return if $ENV{$env};
112    }
113    plan skip_all => "$description normally skipped";
114    return;
115}
116
117# Attempt to load a module and skip the test if the module could not be
118# loaded.  If the module could be loaded, call its import function manually.
119# If the module could not be loaded, calls plan skip_all, which will terminate
120# the program.
121#
122# The special logic here is based on Test::More and is required to get the
123# imports to happen in the caller's namespace.
124#
125# $module  - Name of the module to load
126# @imports - Any arguments to import, possibly including a version
127#
128# Returns: undef
129sub use_prereq {
130    my ($module, @imports) = @_;
131
132    # If the first import looks like a version, pass it as a bare string.
133    my $version = q{};
134    if (@imports >= 1 && $imports[0] =~ m{ \A \d+ (?: [.][\d_]+ )* \z }xms) {
135        $version = shift(@imports);
136    }
137
138    # Get caller information to put imports in the correct package.
139    my ($package) = caller;
140
141    # Do the import with eval, and try to isolate it from the surrounding
142    # context as much as possible.  Based heavily on Test::More::_eval.
143    ## no critic (BuiltinFunctions::ProhibitStringyEval)
144    ## no critic (ValuesAndExpressions::ProhibitImplicitNewlines)
145    my ($result, $error, $sigdie);
146    {
147        local $@            = undef;
148        local $!            = undef;
149        local $SIG{__DIE__} = undef;
150        $result = eval qq{
151            package $package;
152            use $module $version \@imports;
153            1;
154        };
155        $error = $@;
156        $sigdie = $SIG{__DIE__} || undef;
157    }
158
159    # If the use failed for any reason, skip the test.
160    if (!$result || $error) {
161        my $name = length($version) > 0 ? "$module $version" : $module;
162        plan skip_all => "$name required for test";
163    }
164
165    # If the module set $SIG{__DIE__}, we cleared that via local.  Restore it.
166    ## no critic (Variables::RequireLocalizedPunctuationVars)
167    if (defined($sigdie)) {
168        $SIG{__DIE__} = $sigdie;
169    }
170    return;
171}
172
1731;
174__END__
175
176=for stopwords
177Allbery Allbery's DESC bareword sublicense MERCHANTABILITY NONINFRINGEMENT
178rra-c-util CPAN
179
180=head1 NAME
181
182Test::RRA - Support functions for Perl tests
183
184=head1 SYNOPSIS
185
186    use Test::RRA
187      qw(skip_unless_author skip_unless_automated use_prereq);
188
189    # Skip this test unless author tests are requested.
190    skip_unless_author('Coding style tests');
191
192    # Skip this test unless doing automated or release testing.
193    skip_unless_automated('POD syntax tests');
194
195    # Load modules, skipping the test if they're not available.
196    use_prereq('Perl6::Slurp', 'slurp');
197    use_prereq('Test::Script::Run', '0.04');
198
199=head1 DESCRIPTION
200
201This module collects utility functions that are useful for Perl test scripts.
202It assumes Russ Allbery's Perl module layout and test conventions and will
203only be useful for other people if they use the same conventions.
204
205=head1 FUNCTIONS
206
207None of these functions are imported by default.  The ones used by a script
208should be explicitly imported.
209
210=over 4
211
212=item skip_unless_author(DESC)
213
214Checks whether AUTHOR_TESTING is set in the environment and skips the whole
215test (by calling C<plan skip_all> from Test::More) if it is not.  DESC is a
216description of the tests being skipped.  A space and C<only run for author>
217will be appended to it and used as the skip reason.
218
219=item skip_unless_automated(DESC)
220
221Checks whether AUTHOR_TESTING, AUTOMATED_TESTING, or RELEASE_TESTING are set
222in the environment and skips the whole test (by calling C<plan skip_all> from
223Test::More) if they are not.  This should be used by tests that should not run
224during end-user installs of the module, but which should run as part of CPAN
225smoke testing and release testing.
226
227DESC is a description of the tests being skipped.  A space and C<normally
228skipped> will be appended to it and used as the skip reason.
229
230=item use_prereq(MODULE[, VERSION][, IMPORT ...])
231
232Attempts to load MODULE with the given VERSION and import arguments.  If this
233fails for any reason, the test will be skipped (by calling C<plan skip_all>
234from Test::More) with a skip reason saying that MODULE is required for the
235test.
236
237VERSION will be passed to C<use> as a version bareword if it looks like a
238version number.  The remaining IMPORT arguments will be passed as the value of
239an array.
240
241=back
242
243=head1 AUTHOR
244
245Russ Allbery <eagle@eyrie.org>
246
247=head1 COPYRIGHT AND LICENSE
248
249Copyright 2013, 2014 The Board of Trustees of the Leland Stanford Junior
250University
251
252Permission is hereby granted, free of charge, to any person obtaining a copy
253of this software and associated documentation files (the "Software"), to deal
254in the Software without restriction, including without limitation the rights
255to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
256copies of the Software, and to permit persons to whom the Software is
257furnished to do so, subject to the following conditions:
258
259The above copyright notice and this permission notice shall be included in all
260copies or substantial portions of the Software.
261
262THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
263IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
264FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
265AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
266LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
267OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
268SOFTWARE.
269
270=head1 SEE ALSO
271
272Test::More(3), Test::RRA::Automake(3), Test::RRA::Config(3)
273
274This module is maintained in the rra-c-util package.  The current version is
275available from L<https://www.eyrie.org/~eagle/software/rra-c-util/>.
276
277The functions to control when tests are run use environment variables defined
278by the L<Lancaster
279Consensus|https://github.com/Perl-Toolchain-Gang/toolchain-site/blob/master/lancaster-consensus.md>.
280
281=cut
282
283# Local Variables:
284# copyright-at-end-flag: t
285# End:
286