]> eyrie.org Git - kerberos/krb5-strength.git/blob - tests/tap/perl/Test/RRA/Automake.pm
New upstream version 3.1
[kerberos/krb5-strength.git] / tests / tap / perl / Test / RRA / Automake.pm
1 # Helper functions for Perl test programs in Automake distributions.
2 #
3 # This module provides a collection of helper functions used by test programs
4 # written in Perl and included in C source distributions that use Automake.
5 # They embed knowledge of how I lay out my source trees and test suites with
6 # Autoconf and Automake.  They may be usable by others, but doing so will
7 # require closely following the conventions implemented by the rra-c-util
8 # utility collection.
9 #
10 # All the functions here assume that C_TAP_BUILD and C_TAP_SOURCE are set in
11 # the environment.  This is normally done via the C TAP Harness runtests
12 # wrapper.
13
14 package Test::RRA::Automake;
15
16 use 5.006;
17 use strict;
18 use warnings;
19
20 # For Perl 5.006 compatibility.
21 ## no critic (ClassHierarchies::ProhibitExplicitISA)
22
23 use Exporter;
24 use File::Find qw(find);
25 use File::Spec;
26 use Test::More;
27 use Test::RRA::Config qw($LIBRARY_PATH);
28
29 # Used below for use lib calls.
30 my ($PERL_BLIB_ARCH, $PERL_BLIB_LIB);
31
32 # Determine the path to the build tree of any embedded Perl module package in
33 # this source package.  We do this in a BEGIN block because we're going to use
34 # the results in a use lib command below.
35 BEGIN {
36     $PERL_BLIB_ARCH = File::Spec->catdir(qw(perl blib arch));
37     $PERL_BLIB_LIB  = File::Spec->catdir(qw(perl blib lib));
38
39     # If C_TAP_BUILD is set, we can come up with better values.
40     if (defined($ENV{C_TAP_BUILD})) {
41         my ($vol, $dirs) = File::Spec->splitpath($ENV{C_TAP_BUILD}, 1);
42         my @dirs = File::Spec->splitdir($dirs);
43         pop(@dirs);
44         $PERL_BLIB_ARCH = File::Spec->catdir(@dirs, qw(perl blib arch));
45         $PERL_BLIB_LIB  = File::Spec->catdir(@dirs, qw(perl blib lib));
46     }
47 }
48
49 # Prefer the modules built as part of our source package.  Otherwise, we may
50 # not find Perl modules while testing, or find the wrong versions.
51 use lib $PERL_BLIB_ARCH;
52 use lib $PERL_BLIB_LIB;
53
54 # Declare variables that should be set in BEGIN for robustness.
55 our (@EXPORT_OK, @ISA, $VERSION);
56
57 # Set $VERSION and everything export-related in a BEGIN block for robustness
58 # against circular module loading (not that we load any modules, but
59 # consistency is good).
60 BEGIN {
61     @ISA       = qw(Exporter);
62     @EXPORT_OK = qw(
63       all_files automake_setup perl_dirs test_file_path test_tmpdir
64     );
65
66     # This version should match the corresponding rra-c-util release, but with
67     # two digits for the minor version, including a leading zero if necessary,
68     # so that it will sort properly.
69     $VERSION = '6.02';
70 }
71
72 # Directories to skip globally when looking for all files, or for directories
73 # that could contain Perl files.
74 my @GLOBAL_SKIP = qw(.git _build autom4te.cache build-aux);
75
76 # Additional paths to skip when building a list of all files in the
77 # distribution.  This primarily skips build artifacts that aren't interesting
78 # to any of the tests.  These match any path component.
79 my @FILES_SKIP = qw(.deps .dirstamp .libs config.h.in~ configure);
80
81 # The temporary directory created by test_tmpdir, if any.  If this is set,
82 # attempt to remove the directory stored here on program exit (but ignore
83 # failure to do so).
84 my $TMPDIR;
85
86 # Returns a list of all files in the distribution.
87 #
88 # Returns: List of files
89 sub all_files {
90     my @files;
91
92     # Turn the skip lists into hashes for ease of querying.
93     my %skip       = map { $_ => 1 } @GLOBAL_SKIP;
94     my %files_skip = map { $_ => 1 } @FILES_SKIP;
95
96     # Wanted function for find.  Prune anything matching either of the skip
97     # lists, or *.lo files, and then add all regular files to the list.
98     my $wanted = sub {
99         my $file = $_;
100         my $path = $File::Find::name;
101         $path =~ s{ \A [.]/ }{}xms;
102         if ($skip{$path} or $files_skip{$file} or $file =~ m{ [.] lo \z }xms) {
103             $File::Find::prune = 1;
104             return;
105         }
106         if (-f $file) {
107             push(@files, $path);
108         }
109     };
110
111     # Do the recursive search and return the results.
112     find($wanted, q{.});
113     return @files;
114 }
115
116 # Perform initial test setup for running a Perl test in an Automake package.
117 # This verifies that C_TAP_BUILD and C_TAP_SOURCE are set and then changes
118 # directory to the C_TAP_SOURCE directory by default.  Sets LD_LIBRARY_PATH if
119 # the $LIBRARY_PATH configuration option is set.  Calls BAIL_OUT if
120 # C_TAP_BUILD or C_TAP_SOURCE are missing or if anything else fails.
121 #
122 # $args_ref - Reference to a hash of arguments to configure behavior:
123 #   chdir_build - If set to a true value, changes to C_TAP_BUILD instead of
124 #                 C_TAP_SOURCE
125 #
126 # Returns: undef
127 sub automake_setup {
128     my ($args_ref) = @_;
129
130     # Bail if C_TAP_BUILD or C_TAP_SOURCE are not set.
131     if (!$ENV{C_TAP_BUILD}) {
132         BAIL_OUT('C_TAP_BUILD not defined (run under runtests)');
133     }
134     if (!$ENV{C_TAP_SOURCE}) {
135         BAIL_OUT('C_TAP_SOURCE not defined (run under runtests)');
136     }
137
138     # C_TAP_BUILD or C_TAP_SOURCE will be the test directory.  Change to the
139     # parent.
140     my $start;
141     if ($args_ref->{chdir_build}) {
142         $start = $ENV{C_TAP_BUILD};
143     } else {
144         $start = $ENV{C_TAP_SOURCE};
145     }
146     my ($vol, $dirs) = File::Spec->splitpath($start, 1);
147     my @dirs = File::Spec->splitdir($dirs);
148     pop(@dirs);
149
150     # Simplify relative paths at the end of the directory.
151     my $ups = 0;
152     my $i   = $#dirs;
153     while ($i > 2 && $dirs[$i] eq File::Spec->updir) {
154         $ups++;
155         $i--;
156     }
157     for (1 .. $ups) {
158         pop(@dirs);
159         pop(@dirs);
160     }
161     my $root = File::Spec->catpath($vol, File::Spec->catdir(@dirs), q{});
162     chdir($root) or BAIL_OUT("cannot chdir to $root: $!");
163
164     # If C_TAP_BUILD is a subdirectory of C_TAP_SOURCE, add it to the global
165     # ignore list.
166     my ($buildvol, $builddirs) = File::Spec->splitpath($ENV{C_TAP_BUILD}, 1);
167     my @builddirs = File::Spec->splitdir($builddirs);
168     pop(@builddirs);
169     if ($buildvol eq $vol && @builddirs == @dirs + 1) {
170         while (@dirs && $builddirs[0] eq $dirs[0]) {
171             shift(@builddirs);
172             shift(@dirs);
173         }
174         if (@builddirs == 1) {
175             push(@GLOBAL_SKIP, $builddirs[0]);
176         }
177     }
178
179     # Set LD_LIBRARY_PATH if the $LIBRARY_PATH configuration option is set.
180     ## no critic (Variables::RequireLocalizedPunctuationVars)
181     if (defined($LIBRARY_PATH)) {
182         @builddirs = File::Spec->splitdir($builddirs);
183         pop(@builddirs);
184         my $libdir = File::Spec->catdir(@builddirs, $LIBRARY_PATH);
185         my $path = File::Spec->catpath($buildvol, $libdir, q{});
186         if (-d "$path/.libs") {
187             $path .= '/.libs';
188         }
189         if ($ENV{LD_LIBRARY_PATH}) {
190             $ENV{LD_LIBRARY_PATH} .= ":$path";
191         } else {
192             $ENV{LD_LIBRARY_PATH} = $path;
193         }
194     }
195     return;
196 }
197
198 # Returns a list of directories that may contain Perl scripts and that should
199 # be passed to Perl test infrastructure that expects a list of directories to
200 # recursively check.  The list will be all eligible top-level directories in
201 # the package except for the tests directory, which is broken out to one
202 # additional level.  Calls BAIL_OUT on any problems
203 #
204 # $args_ref - Reference to a hash of arguments to configure behavior:
205 #   skip - A reference to an array of directories to skip
206 #
207 # Returns: List of directories possibly containing Perl scripts to test
208 sub perl_dirs {
209     my ($args_ref) = @_;
210
211     # Add the global skip list.  We also ignore the perl directory if it
212     # exists since, in my packages, it is treated as a Perl module
213     # distribution and has its own standalone test suite.
214     my @skip = $args_ref->{skip} ? @{ $args_ref->{skip} } : ();
215     push(@skip, @GLOBAL_SKIP, 'perl');
216
217     # Separate directories to skip under tests from top-level directories.
218     my @skip_tests = grep { m{ \A tests/ }xms } @skip;
219     @skip = grep { !m{ \A tests }xms } @skip;
220     for my $skip_dir (@skip_tests) {
221         $skip_dir =~ s{ \A tests/ }{}xms;
222     }
223
224     # Convert the skip lists into hashes for convenience.
225     my %skip = map { $_ => 1 } @skip, 'tests';
226     my %skip_tests = map { $_ => 1 } @skip_tests;
227
228     # Build the list of top-level directories to test.
229     opendir(my $rootdir, q{.}) or BAIL_OUT("cannot open .: $!");
230     my @dirs = grep { -d && !$skip{$_} } readdir($rootdir);
231     closedir($rootdir);
232     @dirs = File::Spec->no_upwards(@dirs);
233
234     # Add the list of subdirectories of the tests directory.
235     if (-d 'tests') {
236         opendir(my $testsdir, q{tests}) or BAIL_OUT("cannot open tests: $!");
237
238         # Skip if found in %skip_tests or if not a directory.
239         my $is_skipped = sub {
240             my ($dir) = @_;
241             return 1 if $skip_tests{$dir};
242             $dir = File::Spec->catdir('tests', $dir);
243             return -d $dir ? 0 : 1;
244         };
245
246         # Build the filtered list of subdirectories of tests.
247         my @test_dirs = grep { !$is_skipped->($_) } readdir($testsdir);
248         closedir($testsdir);
249         @test_dirs = File::Spec->no_upwards(@test_dirs);
250
251         # Add the tests directory to the start of the directory name.
252         push(@dirs, map { File::Spec->catdir('tests', $_) } @test_dirs);
253     }
254     return @dirs;
255 }
256
257 # Find a configuration file for the test suite.  Searches relative to
258 # C_TAP_BUILD first and then C_TAP_SOURCE and returns whichever is found
259 # first.  Calls BAIL_OUT if the file could not be found.
260 #
261 # $file - Partial path to the file
262 #
263 # Returns: Full path to the file
264 sub test_file_path {
265     my ($file) = @_;
266   BASE:
267     for my $base ($ENV{C_TAP_BUILD}, $ENV{C_TAP_SOURCE}) {
268         next if !defined($base);
269         if (-f "$base/$file") {
270             return "$base/$file";
271         }
272     }
273     BAIL_OUT("cannot find $file");
274     return;
275 }
276
277 # Create a temporary directory for tests to use for transient files and return
278 # the path to that directory.  The directory is automatically removed on
279 # program exit.  The directory permissions use the current umask.  Calls
280 # BAIL_OUT if the directory could not be created.
281 #
282 # Returns: Path to a writable temporary directory
283 sub test_tmpdir {
284     my $path;
285
286     # If we already figured out what directory to use, reuse the same path.
287     # Otherwise, create a directory relative to C_TAP_BUILD if set.
288     if (defined($TMPDIR)) {
289         $path = $TMPDIR;
290     } else {
291         my $base;
292         if (defined($ENV{C_TAP_BUILD})) {
293             $base = $ENV{C_TAP_BUILD};
294         } else {
295             $base = File::Spec->curdir;
296         }
297         $path = File::Spec->catdir($base, 'tmp');
298     }
299
300     # Create the directory if it doesn't exist.
301     if (!-d $path) {
302         if (!mkdir($path, 0777)) {
303             BAIL_OUT("cannot create directory $path: $!");
304         }
305     }
306
307     # Store the directory name for cleanup and return it.
308     $TMPDIR = $path;
309     return $path;
310 }
311
312 # On program exit, remove $TMPDIR if set and if possible.  Report errors with
313 # diag but otherwise ignore them.
314 END {
315     if (defined($TMPDIR) && -d $TMPDIR) {
316         local $! = undef;
317         if (!rmdir($TMPDIR)) {
318             diag("cannot remove temporary directory $TMPDIR: $!");
319         }
320     }
321 }
322
323 1;
324 __END__
325
326 =for stopwords
327 Allbery Automake Automake-aware Automake-based rra-c-util ARGS subdirectories
328 sublicense MERCHANTABILITY NONINFRINGEMENT umask
329
330 =head1 NAME
331
332 Test::RRA::Automake - Automake-aware support functions for Perl tests
333
334 =head1 SYNOPSIS
335
336     use Test::RRA::Automake qw(automake_setup perl_dirs test_file_path);
337     automake_setup({ chdir_build => 1 });
338
339     # Paths to directories that may contain Perl scripts.
340     my @dirs = perl_dirs({ skip => [qw(lib)] });
341
342     # Configuration for Kerberos tests.
343     my $keytab = test_file_path('config/keytab');
344
345 =head1 DESCRIPTION
346
347 This module collects utility functions that are useful for test scripts
348 written in Perl and included in a C Automake-based package.  They assume the
349 layout of a package that uses rra-c-util and C TAP Harness for the test
350 structure.
351
352 Loading this module will also add the directories C<perl/blib/arch> and
353 C<perl/blib/lib> to the Perl library search path, relative to C_TAP_BUILD if
354 that environment variable is set.  This is harmless for C Automake projects
355 that don't contain an embedded Perl module, and for those projects that do,
356 this will allow subsequent C<use> calls to find modules that are built as part
357 of the package build process.
358
359 The automake_setup() function should be called before calling any other
360 functions provided by this module.
361
362 =head1 FUNCTIONS
363
364 None of these functions are imported by default.  The ones used by a script
365 should be explicitly imported.  On failure, all of these functions call
366 BAIL_OUT (from Test::More).
367
368 =over 4
369
370 =item all_files()
371
372 Returns a list of all "interesting" files in the distribution that a test
373 suite may want to look at.  This excludes various products of the build system,
374 the build directory if it's under the source directory, and a few other
375 uninteresting directories like F<.git>.  The returned paths will be paths
376 relative to the root of the package.
377
378 =item automake_setup([ARGS])
379
380 Verifies that the C_TAP_BUILD and C_TAP_SOURCE environment variables are set
381 and then changes directory to the top of the source tree (which is one
382 directory up from the C_TAP_SOURCE path, since C_TAP_SOURCE points to the top
383 of the tests directory).
384
385 If ARGS is given, it should be a reference to a hash of configuration options.
386 Only one option is supported: C<chdir_build>.  If it is set to a true value,
387 automake_setup() changes directories to the top of the build tree instead.
388
389 =item perl_dirs([ARGS])
390
391 Returns a list of directories that may contain Perl scripts that should be
392 tested by test scripts that test all Perl in the source tree (such as syntax
393 or coding style checks).  The paths will be simple directory names relative to
394 the current directory or two-part directory names under the F<tests>
395 directory.  (Directories under F<tests> are broken out separately since it's
396 common to want to apply different policies to different subdirectories of
397 F<tests>.)
398
399 If ARGS is given, it should be a reference to a hash of configuration options.
400 Only one option is supported: C<skip>, whose value should be a reference to an
401 array of additional top-level directories or directories starting with
402 C<tests/> that should be skipped.
403
404 =item test_file_path(FILE)
405
406 Given FILE, which should be a relative path, locates that file relative to the
407 test directory in either the source or build tree.  FILE will be checked for
408 relative to the environment variable C_TAP_BUILD first, and then relative to
409 C_TAP_SOURCE.  test_file_path() returns the full path to FILE or calls
410 BAIL_OUT if FILE could not be found.
411
412 =item test_tmpdir()
413
414 Create a temporary directory for tests to use for transient files and return
415 the path to that directory.  The directory is created relative to the
416 C_TAP_BUILD environment variable, which must be set.  Permissions on the
417 directory are set using the current umask.  test_tmpdir() returns the full
418 path to the temporary directory or calls BAIL_OUT if it could not be created.
419
420 The directory is automatically removed if possible on program exit.  Failure
421 to remove the directory on exit is reported with diag() and otherwise ignored.
422
423 =back
424
425 =head1 ENVIRONMENT
426
427 =over 4
428
429 =item C_TAP_BUILD
430
431 The root of the tests directory in Automake build directory for this package,
432 used to find files as documented above.
433
434 =item C_TAP_SOURCE
435
436 The root of the tests directory in the source tree for this package, used to
437 find files as documented above.
438
439 =back
440
441 =head1 AUTHOR
442
443 Russ Allbery <eagle@eyrie.org>
444
445 =head1 COPYRIGHT AND LICENSE
446
447 Copyright 2014, 2015 Russ Allbery <eagle@eyrie.org>
448
449 Copyright 2013 The Board of Trustees of the Leland Stanford Junior University
450
451 Permission is hereby granted, free of charge, to any person obtaining a copy
452 of this software and associated documentation files (the "Software"), to deal
453 in the Software without restriction, including without limitation the rights
454 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
455 copies of the Software, and to permit persons to whom the Software is
456 furnished to do so, subject to the following conditions:
457
458 The above copyright notice and this permission notice shall be included in all
459 copies or substantial portions of the Software.
460
461 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
462 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
463 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
464 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
465 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
466 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
467 SOFTWARE.
468
469 =head1 SEE ALSO
470
471 Test::More(3), Test::RRA(3), Test::RRA::Config(3)
472
473 This module is maintained in the rra-c-util package.  The current version is
474 available from L<https://www.eyrie.org/~eagle/software/rra-c-util/>.
475
476 The C TAP Harness test driver and libraries for TAP-based C testing are
477 available from L<https://www.eyrie.org/~eagle/software/c-tap-harness/>.
478
479 =cut