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