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