1 # (X)Emacs mode: -*- cperl -*-
7 test - tools for helping in test suites (not including running externalprograms).
11 use FindBin 1.42 qw( $Bin );
12 use Test 1.13 qw( ok plan );
14 BEGIN { unshift @INC, $Bin };
26 open my $fh, '>', 'foo';
28 for 'Bulgaria', 'Cholet';
30 }, 'write foo'), 1, 'write foo';
32 save_output('stderr', *STDERR{IO});
34 print restore_output('stderr');
38 This package provides some variables, and sets up an environment, for test
39 scripts, such as those used in F<t/>.
41 This package does not including running external programs; that is provided by
42 C<test2.pm>. This is so that suites not needing that can include only
43 test.pm, and so not require the presence of C<IPC::Run>.
45 Setting up the environment includes:
49 =item Prepending F<blib/script> onto the path
51 =item Pushing the module F<lib/> dir onto the @PERL5LIB var
55 =item Pushing the module F<lib/> dir onto the @INC var
57 For internal C<use> calls.
59 =item Changing directory to a temporary directory
61 To avoid cluttering the local dir, and/or allowing the local directory
62 structure to affect matters.
64 =item Cleaning up the temporary directory afterwards
66 Unless TEST_DEBUG is set in the environment.
72 # ----------------------------------------------------------------------------
74 # Pragmas -----------------------------
78 use vars qw( @EXPORT_OK );
80 # Inheritance -------------------------
82 use base qw( Exporter );
86 The following symbols are exported upon request:
124 @EXPORT_OK = qw( BIN_DIR DATA_DIR REF_DIR LIB_DIR PERL
125 check_req compare evcheck find_exec only_files read_file
126 save_output restore_output tempdir tmpnam );
128 # Utility -----------------------------
130 use Carp qw( carp croak );
131 use Cwd 2.01 qw( cwd );
132 use Env qw( PATH PERL5LIB );
133 use Fatal 1.02 qw( close open seek sysopen unlink );
134 use Fcntl 1.03 qw( :DEFAULT );
135 use File::Basename qw( basename );
136 use File::Compare 1.1002 qw( );
137 use File::Path 1.0401 qw( mkpath rmtree );
138 use File::Spec 0.6 qw( );
139 use FindBin 1.42 qw( $Bin );
140 use POSIX 1.02 qw( );
141 use Test 1.122 qw( ok skip );
143 # ----------------------------------------------------------------------------
146 if ( File::Spec->file_name_is_absolute($_[0]) ) {
149 return catdir(cwd, $_[0]);
154 File::Spec->catdir(@_);
158 File::Spec->catfile(@_);
162 File::Spec->updir(@_);
166 croak "Can't min over 0 args!\n"
177 # -------------------------------------
179 # -------------------------------------
181 use constant BIN_DIR => catdir $Bin, updir, 'bin';
182 use constant DATA_DIR => catdir $Bin, updir, 'data';
183 use constant REF_DIR => catdir $Bin, updir, 'testref';
184 use constant LIB_DIR => catdir $Bin, updir, 'lib';
186 use constant BUILD_SCRIPT_DIR => => catdir $Bin, updir, qw( blib script );
191 for (split /:/, $PATH) {
192 my $try = catfile $_, $exec;
199 use constant PERL => (basename($^X) eq $^X ?
203 # -------------------------------------
205 # -------------------------------------
207 # @PERL5LIB not available in Env for perl 5.00503
208 # unshift @PERL5LIB, LIB_DIR;
209 $PERL5LIB = defined $PERL5LIB ? join(':', LIB_DIR, $PERL5LIB) : LIB_DIR;
210 unshift @INC, LIB_DIR;
212 $PATH = join ':', BUILD_SCRIPT_DIR, split /:/, $PATH;
217 my $tmpdn = tempdir();
221 die "Couldn't create temp dir: $tmpdn: $!\n"
222 unless -r $tmpdn and -w $tmpdn and -x $tmpdn and -o $tmpdn and -d $tmpdn;
224 #@INC = map rel2abs($_), @INC;
227 # -------------------------------------
229 # -------------------------------------
241 Arrayref of names of files to expect to exist.
251 1 if exactly expected files exist, false otherwise.
264 my %files = map { $_ => 1 } readdir MYDIR;
269 for (@$expect, '.', '..') {
270 if ( exists $files{$_} ) {
272 } elsif ( ! -e $_ ) { # $_ might be absolute
273 carp "File not found: $_\n"
280 carp "Extra file found: $_\n"
292 # -------------------------------------
296 Eval code, return status
310 Name to use in error messages
320 1 if eval was okay, 0 if not.
329 my ($code, $name) = @_;
337 carp "Code $name failed: $@\n"
345 # -------------------------------------
349 Redirect a filehandle to temporary storage for later examination.
359 Name to store as (used in L<restore_output>)
363 The filehandle to save
369 # Map from names to saved filehandles.
371 # Values are arrayrefs, being filehandle that was saved (to restore), the
372 # filehandle being printed to in the meantime, and the original filehandle.
373 # This may be treated as a stack; to allow multiple saves... push & pop this
379 croak sprintf("%s takes 2 arguments\n", (caller 0)[3])
381 my ($name, $filehandle) = @_;
383 my $tmpfh = do { local *F; *F; };
384 my $savefh = do { local *F; *F; };
386 (undef, $tmpfh) = test::tmpnam();
387 select((select($tmpfh), $| = 1)[0]);
389 open $savefh, '>&' . fileno $filehandle
390 or die "can't dup $name: $!";
391 open $filehandle, '>&' . fileno $tmpfh
392 or die "can't open $name to tempfile: $!";
394 push @{$grabs{$name}}, $savefh, $tmpfh, $filehandle;
397 # -------------------------------------
399 =head2 restore_output
401 Restore a saved filehandle to its original state, return the saved output.
411 Name of the filehandle to restore (as passed to L<save_output>).
421 A single string being the output saved.
430 croak "$name has not been saved\n"
431 unless exists $grabs{$name};
432 croak "All saved instances of $name have been restored\n"
433 unless @{$grabs{$name}};
434 my ($savefh, $tmpfh, $origfh) = splice @{$grabs{$name}}, -3;
437 or die "cannot close $name opened to tempfile: $!";
438 open $origfh, '>&' . fileno $savefh
439 or die "cannot dup $name back again: $!";
440 select((select($origfh), $| = 1)[0]);
444 my $string = <$tmpfh>;
450 sub _test_save_restore_output {
451 warn "to stderr 1\n";
452 save_output("stderr", *STDERR{IO});
454 print 'SAVED:->:', restore_output("stderr"), ":<-\n";
455 warn "to stderr 2\n";
458 # -------------------------------------
462 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
463 if TEST_DEBUG has SAVE in the value.
473 I<Optional>. If defined, a name by which to refer to the tmpfile in user
484 Name of temporary file.
488 Open filehandle to temp file, in r/w mode. Only created & returned in list
500 my $savewarn = $SIG{__WARN__};
501 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
502 local $SIG{__WARN__} =
505 if defined $savewarn and
506 UNIVERSAL::isa($savewarn,'CODE') and
507 $_[0] !~ /^Subroutine tmpnam redefined/;
511 my $tmpnam = POSIX::tmpnam;
514 push @tmpfns, [ $tmpnam, $_[0] ];
516 push @tmpfns, $tmpnam;
520 sysopen my $tmpfh, $tmpnam, O_RDWR | O_CREAT | O_EXCL;
521 return $tmpnam, $tmpfh;
529 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
532 printf "Used temp file: %s (%s)\n", @$_;
534 print "Used temp file: $_\n";
538 unlink map((ref $_ ? $_->[0] : $_), @tmpfns)
543 # -------------------------------------
547 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
548 if TEST_DEBUG has SAVE in the value (does get deleted otherwise).
562 Name of temporary dir.
572 my $tempdir = POSIX::tmpnam;
574 or die "Failed to create temporary directory $tempdir: $!\n";
577 push @tmpdirs, [ $tempdir, $_[0] ];
579 push @tmpdirs, $tempdir;
588 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
589 printf "Used temp dir: %s (%s)\n", @$_;
591 # Solaris gets narky about removing the pwd.
592 chdir File::Spec->rootdir;
596 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
597 print "Used temp dir: $_\n";
599 # Solaris gets narky about removing the pwd.
600 chdir File::Spec->rootdir;
607 # -------------------------------------
611 compare(+{ fn1 => $fn1, fn2 => $fn2, gzip => 1 });
613 This performs one test.
619 A single argument is taken, considered as a hash ref, with the following keys:
621 In TEST_DEBUG mode, if the files do not compare equal, outputs file info on
628 B<Mandatory> File to compare
632 B<Mandatory> File to compare
636 B<Mandatory> Test name
640 B<Optional> sort files prior to comparison. Requires the C<sort> command to
641 be on C<$PATH> (else skips).
645 B<Optional> gunzip files prior to comparison. Requires the C<gzip> command to
646 be on C<$PATH> (else skips). gzip occurs prior to any sort.
650 B<Optional> untar files prior to comparison. Requires the C<tar> command to
651 be on C<$PATH> (else skips). any gzip occurs prior to any tar. Tar files are
652 considered equal if they each contain the same filenames & each file contained
653 is equal. If the sort flag is present, each file is sorted prior to comparison.
662 #XYZ my ($cmd, $name, $in) = @_;
664 #XYZ my $infn = defined $in ? tmpnam : '/dev/null';
665 #XYZ my $outfn = tmpnam;
666 #XYZ my $errfn = tmpnam;
669 #XYZ croak "Couldn't fork: $!\n"
670 #XYZ unless defined $pid;
672 #XYZ if ( $pid == 0 ) { # Child
673 #XYZ open STDOUT, '>', $outfn;
674 #XYZ open STDERR, '>', $errfn;
675 #XYZ open STDIN, '<', $infn;
680 #XYZ my $rv = waitpid $pid, 0;
681 #XYZ my $status = $?;
683 #XYZ croak "Unexpected waitpid return from child $name: $rv (expected $pid)\n"
684 #XYZ unless $rv == $pid;
686 #XYZ local $/ = undef;
687 #XYZ local (OUT, ERR);
688 #XYZ open *OUT, '<', $outfn;
689 #XYZ open *ERR, '<', $errfn;
690 #XYZ my $out = <OUT>;
691 #XYZ my $err = <ERR>;
695 #XYZ return $status >> 8, $status & 127, $status & 128 , $out, $err
698 # return codes and old-style call semantics left for backwards compatibility
700 my $savewarn = $SIG{__WARN__};
701 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
702 local $SIG{__WARN__} =
705 if defined $savewarn and
706 UNIVERSAL::isa($savewarn,'CODE') and
707 $_[0] !~ /^Subroutine compare redefined/;
711 my ($fn1, $fn2, $sort) = @_;
712 my ($gzip, $tar, $name);
715 if ( @_ == 1 and UNIVERSAL::isa($_[0], 'HASH') ) {
716 ($fn1, $fn2, $name, $sort, $gzip, $tar, $notest) =
717 @{$_[0]}{qw( fn1 fn2 name sort gunzip untar notest )};
718 my @missing = grep ! defined $_[0]->{$_}, qw( fn1 fn2 name );
719 carp "Missing mandatory key(s): " . join(', ', @missing) . "\n"
723 my ($name1, $name2) = ($fn1, $fn2);
725 for ( grep ! defined, $fn1, $fn2 ) {
726 carp 'Usage: compare({fn1 => $fn1, fn2 => $fn2, name => "some name"})' ."\n"
737 my $fn = ($name1, $name2)[$_];
739 carp "Does not exist: $fn\n"
742 } elsif ( ! -r $fn ) {
743 carp "Cannot read: $fn\n"
757 unless ( find_exec('gzip') ) {
758 print "ok # Skip gzip not found in path\n";
764 system "gzip $fn1 -cd > $tmp1"
765 and croak "gzip $fn1 failed: $?\n";
766 system "gzip $fn2 -cd > $tmp2"
767 and croak "gzip $fn2 failed: $?\n";
768 ($fn1, $fn2) = ($tmp1, $tmp2);
772 unless ( find_exec('tar') ) {
773 print "ok # Skip tar not found in path\n";
778 chomp (my @list1 = sort qx( tar tf $fn1 ));
779 croak "tar tf $fn1 failed with wait status: $?\n"
781 chomp(my @list2 = sort qx( tar tf $fn2 ));
782 croak "tar tf $fn2 failed with wait status: $?\n"
785 if ( @list2 > @list1 ) {
787 sprintf("More files (%d) in $name2 than $name1 (%d)\n",
788 scalar @list2, scalar @list1)
790 ok @list1, @list2, $name
793 } elsif ( @list1 > @list2 ) {
795 sprintf("More files (%d) in $name1 than $name2 (%d)\n",
796 scalar @list1, scalar @list2)
798 ok @list1, @list2, $name
803 for (my $i = 0; $i < @list1; $i++) {
804 if ( $list1[$i] lt $list2[$i] ) {
805 carp "File $list1[$i] is present in $name1 but not $name2\n"
807 ok $list1[$i], $list2[$i], $name
810 } elsif ( $list1[$i] gt $list2[$i] ) {
811 carp "File $list2[$i] is present in $name2 but not $name1\n"
813 ok $list2[$i], $list1[$i], $name
819 for my $fn (@list1) {
822 system "tar -xf $fn1 -O $fn > $tmp1"
823 and croak "tar -xf $fn1 -O $fn failed: $?\n";
824 system "tar -xf $fn2 -O $fn > $tmp2"
825 and croak "tar -xf $fn2 -O $fn failed: $?\n";
826 my $ok = compare({ fn1 => $tmp1,
831 qq'Subcheck file "$fn" for compare $name1, $name2',
833 unless ( $ok >= 1 ) {
834 carp qq'Difference found testing file "$fn" in tars $name1 ($tmp1), $name2 ($tmp2)\n'
848 unless ( find_exec('sort') ) {
849 print "ok # Skip sort not found in path\n";
855 system sort => $fn1, -o => $tmp1
856 and croak "Sort $fn1 failed: $?\n";
857 system sort => $fn2, -o => $tmp2
858 and croak "Sort $fn2 failed: $?\n";
859 ($fn1, $fn2) = ($tmp1, $tmp2);
862 unless ( File::Compare::compare($fn1, $fn2) ) {
868 if ( $ENV{TEST_DEBUG} ) {
870 die "Fork failed: $!\n"
873 if ( $pid ) { # Parent
874 my $waitpid = waitpid($pid, 0);
875 die "Waitpid got: $waitpid (expected $pid)\n"
876 unless $waitpid == $pid;
878 open *STDOUT{IO}, ">&" . fileno STDERR;
879 # Uniquify file names
880 my @args = keys %{+{ map {;$_=>1} $name1, $name2, $fn1, $fn2 }};
881 exec qw(ls -l), @args;
884 my $fh1 = IO::File->new($fn1, O_RDONLY)
885 or die "Couldn't open $fn1: $!\n";
886 my $fh2 = IO::File->new($fn2, O_RDONLY)
887 or die "Couldn't open $fn2: $!\n";
892 while ( ! $found and my $line1 = <$fh1> ) {
894 if ( ! defined $line2 ) {
895 print STDERR "$fn2 ended at line: $.\n";
897 } elsif ( $line2 ne $line1 ) {
898 my $maxlength = max(map length($_), $line1, $line2);
899 my $minlength = min(map length($_), $line1, $line2);
901 my @diffchars = grep(substr($line1, $_, 1) ne substr($line2, $_, 1),
903 my $diff = ' ' x $minlength;
904 substr($diff, $_, 1) = '|'
907 my @extrachars, map((length($line1) > length($line2) ? '^' : 'v'),
908 $minlength..$maxlength-1);
910 $diff = join '', $diff, @extrachars;
912 my $diff_count = @diffchars;
913 my $extra_count = @extrachars;
915 print STDERR <<"END";
916 Difference at line $. ($diff_count characters differ) (top line is $extra_count chars longer):
922 Differing characters at positions @{[join ',',@diffchars]} (zero-based)
930 if ( defined $line2 ) {
931 print STDERR "$name1 ended before line: $.\n";
933 print STDERR "Difference between $name1, $name2 not found!\n";
947 # -------------------------------------
951 Perform a requisite check on a given executable. This will skip if the
952 required modules are not present.
954 4+(n+m)*2 tests are performed, where n is the number of prerequisites
955 expected, and m is the number of outputs expected.
961 check_req('ccu-touch',
963 [[REQ_FILE, '/etc/passwd']],
964 [[REQ_FILE, 'passwd.foo']],
974 The name of the command to run. It is assumed that this command is in
975 blib/script; hence it should be an executable in this package, and C<make>
976 shuold have been run recently.
980 The arguments to pass to the cmd_name, as an arrayref.
984 The expected prerequisites, as an arrayref, wherein every member is a
985 two-element arrayref, the members being the requisite type, and the requisite
990 The expected outputs, in the same format as the L<epres|"epres">.
994 The name to use in error messages.
1003 my ($cmd_name, $args, $epres, $eouts, $testname) = @_;
1005 eval "use Pipeline::DataFlow 1.03 qw( :req_types );";
1009 if $ENV{TEST_DEBUG};
1010 $skip = 'Skipped: Pipeline::DataFlow 1.03 not found';
1017 my ($code, $expect) = @_;
1018 my $name = sprintf "%s (%2d)", $testname, $count++;
1019 my $value = UNIVERSAL::isa($code, 'CODE') ? $code->($name) : $code;
1020 skip $skip, $value, $expect, $name;
1023 # Initialize nicely to cope when read_reqs fails
1024 my ($pres, $outs) = ([], []);
1028 ($pres, $outs) = Pipeline::DataFlow->read_reqs
1029 ([catfile($Bin, updir, 'blib', 'script', $cmd_name),
1034 $test->(scalar @$pres, scalar @$epres);
1037 @epres = sort { $a->[1] cmp $b->[1] } @$epres;
1038 @pres = sort { $a->[1] cmp $b->[1] } @$pres;
1040 for (my $i = 0; $i < @epres; $i++) {
1041 my ($type, $value) = @{$epres[$i]};
1042 $test->($type, @pres > $i ? $pres[$i]->[0] : undef);
1043 $test->($value, @pres > $i ? $pres[$i]->[1] : undef);
1046 $test->(scalar @$outs, scalar @$eouts);
1049 @eouts = sort { $a->[1] cmp $b->[1] } @$eouts;
1050 @outs = sort { $a->[1] cmp $b->[1] } @$outs;
1052 for (my $i = 0; $i < @eouts; $i++) {
1053 my ($type, $value) = @{$eouts[$i]};
1054 $test->($type, @outs > $i ? $outs[$i]->[0] : undef);
1055 $test->($value, @outs > $i ? $outs[$i]->[1] : undef);
1058 $test->(only_files([]), 1);
1061 # -------------------------------------
1073 The name of the program
1083 The path to the first executable file with the given name on C<$PATH>. Or
1084 nothing, if no such file exists.
1092 # defined further up to use in constants
1094 # -------------------------------------
1108 =item line-terminator
1110 B<Optional>. Value of C<$/>. Defaults to C<"\n">.
1120 A list of lines in the file (lines determined by the value of
1121 line-terminator), as an arrayref.
1130 my ($fn, $term) = @_;
1133 unless defined $term;
1135 my $fh = do { local *F; *F };
1136 sysopen $fh, $fn, O_RDONLY;
1144 # ----------------------------------------------------------------------------
1154 =head1 REPORTING BUGS
1160 Martyn J. Pearce C<fluffy@cpan.org>
1164 Copyright (c) 2001, 2002, 2004 Martyn J. Pearce. This program is free
1165 software; you can redistribute it and/or modify it under the same terms as
1174 1; # keep require happy.