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 };
16 use test qw( evcheck runcheck );
25 open my $fh, '>', 'foo';
27 for 'Bulgaria', 'Cholet';
29 }, 'write foo'), 1, 'write foo';
31 save_output('stderr', *STDERR{IO});
33 print restore_output('stderr');
37 This package provides some variables, and sets up an environment, for test
38 scripts, such as those used in F<t/>.
40 This package does not including running external programs; that is provided by
41 C<test2.pm>. This is so that suites not needing that can include only
42 test.pm, and so not require the presence of C<IPC::Run>.
44 Setting up the environment includes:
48 =item Prepending F<blib/script> onto the path
50 =item Pushing the module F<lib/> dir onto the @PERL5LIB var
54 =item Pushing the module F<lib/> dir onto the @INC var
56 For internal C<use> calls.
58 =item Changing directory to a temporary directory
60 To avoid cluttering the local dir, and/or allowing the local directory
61 structure to affect matters.
63 =item Cleaning up the temporary directory afterwards
65 Unless TEST_DEBUG is set in the environment.
71 # ----------------------------------------------------------------------------
73 # Pragmas -----------------------------
77 use vars qw( @EXPORT_OK );
79 # Inheritance -------------------------
81 use base qw( Exporter );
85 The following symbols are exported upon request:
115 @EXPORT_OK = qw( LIB_DIR
116 check_req compare evcheck find_exec only_files read_file
117 save_output restore_output tempdir tmpnam );
119 # Utility -----------------------------
121 use Carp qw( carp croak );
122 use Cwd 2.01 qw( cwd );
123 use Env qw( PATH PERL5LIB );
124 use Fatal 1.02 qw( close open seek sysopen unlink );
125 use Fcntl 1.03 qw( :DEFAULT );
126 use File::Basename qw( basename );
127 use File::Compare 1.1002 qw( );
128 use File::Path 1.0401 qw( mkpath rmtree );
129 use File::Spec 0.6 qw( );
130 use FindBin 1.42 qw( $Bin );
131 use POSIX 1.02 qw( );
132 use Test 1.122 qw( ok skip );
134 # ----------------------------------------------------------------------------
137 if ( File::Spec->file_name_is_absolute($_[0]) ) {
140 return catdir(cwd, $_[0]);
145 File::Spec->catdir(@_);
149 File::Spec->catfile(@_);
153 File::Spec->updir(@_);
157 croak "Can't min over 0 args!\n"
168 # -------------------------------------
170 # -------------------------------------
172 use constant LIB_DIR => catdir $Bin, updir, 'lib';
174 use constant BUILD_SCRIPT_DIR => => catdir $Bin, updir, qw( blib script );
179 for (split /:/, $PATH) {
180 my $try = catfile $_, $exec;
187 # -------------------------------------
189 # -------------------------------------
191 # @PERL5LIB not available in Env for perl 5.00503
192 # unshift @PERL5LIB, LIB_DIR;
193 $PERL5LIB = defined $PERL5LIB ? join(':', LIB_DIR, $PERL5LIB) : LIB_DIR;
194 unshift @INC, LIB_DIR;
196 $PATH = join ':', BUILD_SCRIPT_DIR, split /:/, $PATH;
201 my $tmpdn = tempdir();
205 die "Couldn't create temp dir: $tmpdn: $!\n"
206 unless -r $tmpdn and -w $tmpdn and -x $tmpdn and -o $tmpdn and -d $tmpdn;
208 #@INC = map rel2abs($_), @INC;
211 # -------------------------------------
213 # -------------------------------------
225 Arrayref of names of files to expect to exist.
235 1 if exactly expected files exist, false otherwise.
248 my %files = map { $_ => 1 } readdir MYDIR;
253 for (@$expect, '.', '..') {
254 if ( exists $files{$_} ) {
256 } elsif ( ! -e $_ ) { # $_ might be absolute
257 carp "File not found: $_\n"
264 carp "Extra file found: $_\n"
276 # -------------------------------------
280 Eval code, return status
294 Name to use in error messages
304 1 if eval was okay, 0 if not.
313 my ($code, $name) = @_;
321 carp "Code $name failed: $@\n"
329 # -------------------------------------
333 Redirect a filehandle to temporary storage for later examination.
343 Name to store as (used in L<restore_output>)
347 The filehandle to save
353 # Map from names to saved filehandles.
355 # Values are arrayrefs, being filehandle that was saved (to restore), the
356 # filehandle being printed to in the meantime, and the original filehandle.
357 # This may be treated as a stack; to allow multiple saves... push & pop this
363 croak sprintf("%s takes 2 arguments\n", (caller 0)[3])
365 my ($name, $filehandle) = @_;
367 my $tmpfh = do { local *F; *F; };
368 my $savefh = do { local *F; *F; };
370 (undef, $tmpfh) = test::tmpnam();
371 select((select($tmpfh), $| = 1)[0]);
373 open $savefh, '>&' . fileno $filehandle
374 or die "can't dup $name: $!";
375 open $filehandle, '>&' . fileno $tmpfh
376 or die "can't open $name to tempfile: $!";
378 push @{$grabs{$name}}, $savefh, $tmpfh, $filehandle;
381 # -------------------------------------
383 =head2 restore_output
385 Restore a saved filehandle to its original state, return the saved output.
395 Name of the filehandle to restore (as passed to L<save_output>).
405 A single string being the output saved.
414 croak "$name has not been saved\n"
415 unless exists $grabs{$name};
416 croak "All saved instances of $name have been restored\n"
417 unless @{$grabs{$name}};
418 my ($savefh, $tmpfh, $origfh) = splice @{$grabs{$name}}, -3;
421 or die "cannot close $name opened to tempfile: $!";
422 open $origfh, '>&' . fileno $savefh
423 or die "cannot dup $name back again: $!";
424 select((select($origfh), $| = 1)[0]);
428 my $string = <$tmpfh>;
434 sub _test_save_restore_output {
435 warn "to stderr 1\n";
436 save_output("stderr", *STDERR{IO});
438 print 'SAVED:->:', restore_output("stderr"), ":<-\n";
439 warn "to stderr 2\n";
442 # -------------------------------------
446 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
447 if TEST_DEBUG has SAVE in the value.
457 I<Optional>. If defined, a name by which to refer to the tmpfile in user
468 Name of temporary file.
472 Open filehandle to temp file, in r/w mode. Only created & returned in list
484 my $savewarn = $SIG{__WARN__};
485 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
486 local $SIG{__WARN__} =
489 if defined $savewarn and
490 UNIVERSAL::isa($savewarn,'CODE') and
491 $_[0] !~ /^Subroutine tmpnam redefined/;
495 my $tmpnam = POSIX::tmpnam;
498 push @tmpfns, [ $tmpnam, $_[0] ];
500 push @tmpfns, $tmpnam;
504 sysopen my $tmpfh, $tmpnam, O_RDWR | O_CREAT | O_EXCL;
505 return $tmpnam, $tmpfh;
513 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
516 printf "Used temp file: %s (%s)\n", @$_;
518 print "Used temp file: $_\n";
522 unlink map((ref $_ ? $_->[0] : $_), @tmpfns)
527 # -------------------------------------
531 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
532 if TEST_DEBUG has SAVE in the value (does get deleted otherwise).
546 Name of temporary dir.
556 my $tempdir = POSIX::tmpnam;
558 or die "Failed to create temporary directory $tempdir: $!\n";
561 push @tmpdirs, [ $tempdir, $_[0] ];
563 push @tmpdirs, $tempdir;
572 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
573 printf "Used temp dir: %s (%s)\n", @$_;
575 # Solaris gets narky about removing the pwd.
576 chdir File::Spec->rootdir;
580 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
581 print "Used temp dir: $_\n";
583 # Solaris gets narky about removing the pwd.
584 chdir File::Spec->rootdir;
591 # -------------------------------------
595 compare(+{ fn1 => $fn1, fn2 => $fn2, gzip => 1 });
597 This performs one test.
603 A single argument is taken, considered as a hash ref, with the following keys:
605 In TEST_DEBUG mode, if the files do not compare equal, outputs file info on
612 B<Mandatory> File to compare
616 B<Mandatory> File to compare
620 B<Mandatory> Test name
624 B<Optional> sort files prior to comparison. Requires the C<sort> command to
625 be on C<$PATH> (else skips).
629 B<Optional> gunzip files prior to comparison. Requires the C<gzip> command to
630 be on C<$PATH> (else skips). gzip occurs prior to any sort.
634 B<Optional> untar files prior to comparison. Requires the C<tar> command to
635 be on C<$PATH> (else skips). any gzip occurs prior to any tar. Tar files are
636 considered equal if they each contain the same filenames & each file contained
637 is equal. If the sort flag is present, each file is sorted prior to comparison.
646 #XYZ my ($cmd, $name, $in) = @_;
648 #XYZ my $infn = defined $in ? tmpnam : '/dev/null';
649 #XYZ my $outfn = tmpnam;
650 #XYZ my $errfn = tmpnam;
653 #XYZ croak "Couldn't fork: $!\n"
654 #XYZ unless defined $pid;
656 #XYZ if ( $pid == 0 ) { # Child
657 #XYZ open STDOUT, '>', $outfn;
658 #XYZ open STDERR, '>', $errfn;
659 #XYZ open STDIN, '<', $infn;
664 #XYZ my $rv = waitpid $pid, 0;
665 #XYZ my $status = $?;
667 #XYZ croak "Unexpected waitpid return from child $name: $rv (expected $pid)\n"
668 #XYZ unless $rv == $pid;
670 #XYZ local $/ = undef;
671 #XYZ local (OUT, ERR);
672 #XYZ open *OUT, '<', $outfn;
673 #XYZ open *ERR, '<', $errfn;
674 #XYZ my $out = <OUT>;
675 #XYZ my $err = <ERR>;
679 #XYZ return $status >> 8, $status & 127, $status & 128 , $out, $err
682 # return codes and old-style call semantics left for backwards compatibility
684 my $savewarn = $SIG{__WARN__};
685 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
686 local $SIG{__WARN__} =
689 if defined $savewarn and
690 UNIVERSAL::isa($savewarn,'CODE') and
691 $_[0] !~ /^Subroutine compare redefined/;
695 my ($fn1, $fn2, $sort) = @_;
696 my ($gzip, $tar, $name);
699 if ( @_ == 1 and UNIVERSAL::isa($_[0], 'HASH') ) {
700 ($fn1, $fn2, $name, $sort, $gzip, $tar, $notest) =
701 @{$_[0]}{qw( fn1 fn2 name sort gunzip untar notest )};
702 my @missing = grep ! defined $_[0]->{$_}, qw( fn1 fn2 name );
703 carp "Missing mandatory key(s): " . join(', ', @missing) . "\n"
707 my ($name1, $name2) = ($fn1, $fn2);
709 for ( grep ! defined, $fn1, $fn2 ) {
710 carp 'Usage: compare({fn1 => $fn1, fn2 => $fn2, name => "some name"})' ."\n"
721 my $fn = ($name1, $name2)[$_];
723 carp "Does not exist: $fn\n"
726 } elsif ( ! -r $fn ) {
727 carp "Cannot read: $fn\n"
741 unless ( find_exec('gzip') ) {
742 print "ok # Skip gzip not found in path\n";
748 system "gzip $fn1 -cd > $tmp1"
749 and croak "gzip $fn1 failed: $?\n";
750 system "gzip $fn2 -cd > $tmp2"
751 and croak "gzip $fn2 failed: $?\n";
752 ($fn1, $fn2) = ($tmp1, $tmp2);
756 unless ( find_exec('tar') ) {
757 print "ok # Skip tar not found in path\n";
762 chomp (my @list1 = sort qx( tar tf $fn1 ));
763 croak "tar tf $fn1 failed with wait status: $?\n"
765 chomp(my @list2 = sort qx( tar tf $fn2 ));
766 croak "tar tf $fn2 failed with wait status: $?\n"
769 if ( @list2 > @list1 ) {
771 sprintf("More files (%d) in $name2 than $name1 (%d)\n",
772 scalar @list2, scalar @list1)
774 ok @list1, @list2, $name
777 } elsif ( @list1 > @list2 ) {
779 sprintf("More files (%d) in $name1 than $name2 (%d)\n",
780 scalar @list1, scalar @list2)
782 ok @list1, @list2, $name
787 for (my $i = 0; $i < @list1; $i++) {
788 if ( $list1[$i] lt $list2[$i] ) {
789 carp "File $list1[$i] is present in $name1 but not $name2\n"
791 ok $list1[$i], $list2[$i], $name
794 } elsif ( $list1[$i] gt $list2[$i] ) {
795 carp "File $list2[$i] is present in $name2 but not $name1\n"
797 ok $list2[$i], $list1[$i], $name
803 for my $fn (@list1) {
806 system "tar -xf $fn1 -O $fn > $tmp1"
807 and croak "tar -xf $fn1 -O $fn failed: $?\n";
808 system "tar -xf $fn2 -O $fn > $tmp2"
809 and croak "tar -xf $fn2 -O $fn failed: $?\n";
810 my $ok = compare({ fn1 => $tmp1,
815 qq'Subcheck file "$fn" for compare $name1, $name2',
817 unless ( $ok >= 1 ) {
818 carp qq'Difference found testing file "$fn" in tars $name1 ($tmp1), $name2 ($tmp2)\n'
832 unless ( find_exec('sort') ) {
833 print "ok # Skip sort not found in path\n";
839 system sort => $fn1, -o => $tmp1
840 and croak "Sort $fn1 failed: $?\n";
841 system sort => $fn2, -o => $tmp2
842 and croak "Sort $fn2 failed: $?\n";
843 ($fn1, $fn2) = ($tmp1, $tmp2);
846 unless ( File::Compare::compare($fn1, $fn2) ) {
852 if ( $ENV{TEST_DEBUG} ) {
854 die "Fork failed: $!\n"
857 if ( $pid ) { # Parent
858 my $waitpid = waitpid($pid, 0);
859 die "Waitpid got: $waitpid (expected $pid)\n"
860 unless $waitpid == $pid;
862 open *STDOUT{IO}, ">&" . fileno STDERR;
863 # Uniquify file names
864 my @args = keys %{+{ map {;$_=>1} $name1, $name2, $fn1, $fn2 }};
865 exec qw(ls -l), @args;
868 my $fh1 = IO::File->new($fn1, O_RDONLY)
869 or die "Couldn't open $fn1: $!\n";
870 my $fh2 = IO::File->new($fn2, O_RDONLY)
871 or die "Couldn't open $fn2: $!\n";
876 while ( ! $found and my $line1 = <$fh1> ) {
878 if ( ! defined $line2 ) {
879 print STDERR "$fn2 ended at line: $.\n";
881 } elsif ( $line2 ne $line1 ) {
882 my $maxlength = max(map length($_), $line1, $line2);
883 my $minlength = min(map length($_), $line1, $line2);
885 my @diffchars = grep(substr($line1, $_, 1) ne substr($line2, $_, 1),
887 my $diff = ' ' x $minlength;
888 substr($diff, $_, 1) = '|'
891 my @extrachars, map((length($line1) > length($line2) ? '^' : 'v'),
892 $minlength..$maxlength-1);
894 $diff = join '', $diff, @extrachars;
896 my $diff_count = @diffchars;
897 my $extra_count = @extrachars;
899 print STDERR <<"END";
900 Difference at line $. ($diff_count characters differ) (top line is $extra_count chars longer):
906 Differing characters at positions @{[join ',',@diffchars]} (zero-based)
914 if ( defined $line2 ) {
915 print STDERR "$name1 ended before line: $.\n";
917 print STDERR "Difference between $name1, $name2 not found!\n";
931 # -------------------------------------
935 Perform a requisite check on a given executable. This will skip if the
936 required modules are not present.
938 4+(n+m)*2 tests are performed, where n is the number of prerequisites
939 expected, and m is the number of outputs expected.
945 check_req('ccu-touch',
947 [[REQ_FILE, '/etc/passwd']],
948 [[REQ_FILE, 'passwd.foo']],
958 The name of the command to run. It is assumed that this command is in
959 blib/script; hence it should be an executable in this package, and C<make>
960 shuold have been run recently.
964 The arguments to pass to the cmd_name, as an arrayref.
968 The expected prerequisites, as an arrayref, wherein every member is a
969 two-element arrayref, the members being the requisite type, and the requisite
974 The expected outputs, in the same format as the L<epres|"epres">.
978 The name to use in error messages.
987 my ($cmd_name, $args, $epres, $eouts, $testname) = @_;
989 eval "use Pipeline::DataFlow 1.03 qw( :req_types );";
994 $skip = 'Skipped: Pipeline::DataFlow 1.03 not found';
1001 my ($code, $expect) = @_;
1002 my $name = sprintf "%s (%2d)", $testname, $count++;
1003 my $value = UNIVERSAL::isa($code, 'CODE') ? $code->($name) : $code;
1004 skip $skip, $value, $expect, $name;
1007 # Initialize nicely to cope when read_reqs fails
1008 my ($pres, $outs) = ([], []);
1012 ($pres, $outs) = Pipeline::DataFlow->read_reqs
1013 ([catfile($Bin, updir, 'blib', 'script', $cmd_name),
1018 $test->(scalar @$pres, scalar @$epres);
1021 @epres = sort { $a->[1] cmp $b->[1] } @$epres;
1022 @pres = sort { $a->[1] cmp $b->[1] } @$pres;
1024 for (my $i = 0; $i < @epres; $i++) {
1025 my ($type, $value) = @{$epres[$i]};
1026 $test->($type, @pres > $i ? $pres[$i]->[0] : undef);
1027 $test->($value, @pres > $i ? $pres[$i]->[1] : undef);
1030 $test->(scalar @$outs, scalar @$eouts);
1033 @eouts = sort { $a->[1] cmp $b->[1] } @$eouts;
1034 @outs = sort { $a->[1] cmp $b->[1] } @$outs;
1036 for (my $i = 0; $i < @eouts; $i++) {
1037 my ($type, $value) = @{$eouts[$i]};
1038 $test->($type, @outs > $i ? $outs[$i]->[0] : undef);
1039 $test->($value, @outs > $i ? $outs[$i]->[1] : undef);
1042 $test->(only_files([]), 1);
1045 # -------------------------------------
1057 The name of the program
1067 The path to the first executable file with the given name on C<$PATH>. Or
1068 nothing, if no such file exists.
1076 # defined further up to use in constants
1078 # -------------------------------------
1092 =item line-terminator
1094 B<Optional>. Value of C<$/>. Defaults to C<"\n">.
1104 A list of lines in the file (lines determined by the value of
1105 line-terminator), as an arrayref.
1114 my ($fn, $term) = @_;
1117 unless defined $term;
1119 my $fh = do { local *F; *F };
1120 sysopen $fh, $fn, O_RDONLY;
1128 # ----------------------------------------------------------------------------
1138 =head1 REPORTING BUGS
1144 Martyn J. Pearce C<fluffy@cpan.org>
1148 Copyright (c) 2001, 2002, 2004 Martyn J. Pearce. This program is free
1149 software; you can redistribute it and/or modify it under the same terms as
1158 1; # keep require happy.