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 @INC var
52 For internal C<use> calls.
54 =item Changing directory to a temporary directory
56 To avoid cluttering the local dir, and/or allowing the local directory
57 structure to affect matters.
59 =item Cleaning up the temporary directory afterwards
61 Unless TEST_DEBUG is set in the environment.
67 # ----------------------------------------------------------------------------
69 # Pragmas -----------------------------
73 use vars qw( @EXPORT_OK );
75 # Inheritance -------------------------
77 use base qw( Exporter );
81 The following symbols are exported upon request:
109 @EXPORT_OK = qw( check_req compare evcheck find_exec only_files read_file
110 save_output restore_output tempdir tmpnam );
112 # Utility -----------------------------
114 use Carp qw( carp croak );
115 use Cwd 2.01 qw( cwd );
117 use Fatal 1.02 qw( close open seek sysopen unlink );
118 use Fcntl 1.03 qw( :DEFAULT );
119 use File::Basename qw( basename );
120 use File::Compare 1.1002 qw( );
121 use File::Path 1.0401 qw( mkpath rmtree );
122 use File::Spec 0.6 qw( );
123 use FindBin 1.42 qw( $Bin );
124 use POSIX 1.02 qw( );
125 use Test 1.122 qw( ok skip );
127 # ----------------------------------------------------------------------------
130 if ( File::Spec->file_name_is_absolute($_[0]) ) {
133 return catdir(cwd, $_[0]);
138 File::Spec->catdir(@_);
142 File::Spec->catfile(@_);
146 File::Spec->updir(@_);
150 croak "Can't min over 0 args!\n"
161 # -------------------------------------
163 # -------------------------------------
165 use constant BUILD_SCRIPT_DIR => => catdir $Bin, updir, qw( blib script );
170 for (split /:/, $PATH) {
171 my $try = catfile $_, $exec;
178 # -------------------------------------
180 # -------------------------------------
182 $PATH = join ':', BUILD_SCRIPT_DIR, split /:/, $PATH;
187 my $tmpdn = tempdir();
191 die "Couldn't create temp dir: $tmpdn: $!\n"
192 unless -r $tmpdn and -w $tmpdn and -x $tmpdn and -o $tmpdn and -d $tmpdn;
194 #@INC = map rel2abs($_), @INC;
197 # -------------------------------------
199 # -------------------------------------
211 Arrayref of names of files to expect to exist.
221 1 if exactly expected files exist, false otherwise.
234 my %files = map { $_ => 1 } readdir MYDIR;
239 for (@$expect, '.', '..') {
240 if ( exists $files{$_} ) {
242 } elsif ( ! -e $_ ) { # $_ might be absolute
243 carp "File not found: $_\n"
250 carp "Extra file found: $_\n"
262 # -------------------------------------
266 Eval code, return status
280 Name to use in error messages
290 1 if eval was okay, 0 if not.
299 my ($code, $name) = @_;
307 carp "Code $name failed: $@\n"
315 # -------------------------------------
319 Redirect a filehandle to temporary storage for later examination.
329 Name to store as (used in L<restore_output>)
333 The filehandle to save
339 # Map from names to saved filehandles.
341 # Values are arrayrefs, being filehandle that was saved (to restore), the
342 # filehandle being printed to in the meantime, and the original filehandle.
343 # This may be treated as a stack; to allow multiple saves... push & pop this
349 croak sprintf("%s takes 2 arguments\n", (caller 0)[3])
351 my ($name, $filehandle) = @_;
353 my $tmpfh = do { local *F; *F; };
354 my $savefh = do { local *F; *F; };
356 (undef, $tmpfh) = test::tmpnam();
357 select((select($tmpfh), $| = 1)[0]);
359 open $savefh, '>&' . fileno $filehandle
360 or die "can't dup $name: $!";
361 open $filehandle, '>&' . fileno $tmpfh
362 or die "can't open $name to tempfile: $!";
364 push @{$grabs{$name}}, $savefh, $tmpfh, $filehandle;
367 # -------------------------------------
369 =head2 restore_output
371 Restore a saved filehandle to its original state, return the saved output.
381 Name of the filehandle to restore (as passed to L<save_output>).
391 A single string being the output saved.
400 croak "$name has not been saved\n"
401 unless exists $grabs{$name};
402 croak "All saved instances of $name have been restored\n"
403 unless @{$grabs{$name}};
404 my ($savefh, $tmpfh, $origfh) = splice @{$grabs{$name}}, -3;
407 or die "cannot close $name opened to tempfile: $!";
408 open $origfh, '>&' . fileno $savefh
409 or die "cannot dup $name back again: $!";
410 select((select($origfh), $| = 1)[0]);
414 my $string = <$tmpfh>;
420 sub _test_save_restore_output {
421 warn "to stderr 1\n";
422 save_output("stderr", *STDERR{IO});
424 print 'SAVED:->:', restore_output("stderr"), ":<-\n";
425 warn "to stderr 2\n";
428 # -------------------------------------
432 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
433 if TEST_DEBUG has SAVE in the value.
443 I<Optional>. If defined, a name by which to refer to the tmpfile in user
454 Name of temporary file.
458 Open filehandle to temp file, in r/w mode. Only created & returned in list
470 my $savewarn = $SIG{__WARN__};
471 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
472 local $SIG{__WARN__} =
475 if defined $savewarn and
476 UNIVERSAL::isa($savewarn,'CODE') and
477 $_[0] !~ /^Subroutine tmpnam redefined/;
481 my $tmpnam = POSIX::tmpnam;
484 push @tmpfns, [ $tmpnam, $_[0] ];
486 push @tmpfns, $tmpnam;
490 sysopen my $tmpfh, $tmpnam, O_RDWR | O_CREAT | O_EXCL;
491 return $tmpnam, $tmpfh;
499 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
502 printf "Used temp file: %s (%s)\n", @$_;
504 print "Used temp file: $_\n";
508 unlink map((ref $_ ? $_->[0] : $_), @tmpfns)
513 # -------------------------------------
517 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
518 if TEST_DEBUG has SAVE in the value (does get deleted otherwise).
532 Name of temporary dir.
542 my $tempdir = POSIX::tmpnam;
544 or die "Failed to create temporary directory $tempdir: $!\n";
547 push @tmpdirs, [ $tempdir, $_[0] ];
549 push @tmpdirs, $tempdir;
558 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
559 printf "Used temp dir: %s (%s)\n", @$_;
561 # Solaris gets narky about removing the pwd.
562 chdir File::Spec->rootdir;
566 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
567 print "Used temp dir: $_\n";
569 # Solaris gets narky about removing the pwd.
570 chdir File::Spec->rootdir;
577 # -------------------------------------
581 compare(+{ fn1 => $fn1, fn2 => $fn2, gzip => 1 });
583 This performs one test.
589 A single argument is taken, considered as a hash ref, with the following keys:
591 In TEST_DEBUG mode, if the files do not compare equal, outputs file info on
598 B<Mandatory> File to compare
602 B<Mandatory> File to compare
606 B<Mandatory> Test name
610 B<Optional> sort files prior to comparison. Requires the C<sort> command to
611 be on C<$PATH> (else skips).
615 B<Optional> gunzip files prior to comparison. Requires the C<gzip> command to
616 be on C<$PATH> (else skips). gzip occurs prior to any sort.
620 B<Optional> untar files prior to comparison. Requires the C<tar> command to
621 be on C<$PATH> (else skips). any gzip occurs prior to any tar. Tar files are
622 considered equal if they each contain the same filenames & each file contained
623 is equal. If the sort flag is present, each file is sorted prior to comparison.
632 #XYZ my ($cmd, $name, $in) = @_;
634 #XYZ my $infn = defined $in ? tmpnam : '/dev/null';
635 #XYZ my $outfn = tmpnam;
636 #XYZ my $errfn = tmpnam;
639 #XYZ croak "Couldn't fork: $!\n"
640 #XYZ unless defined $pid;
642 #XYZ if ( $pid == 0 ) { # Child
643 #XYZ open STDOUT, '>', $outfn;
644 #XYZ open STDERR, '>', $errfn;
645 #XYZ open STDIN, '<', $infn;
650 #XYZ my $rv = waitpid $pid, 0;
651 #XYZ my $status = $?;
653 #XYZ croak "Unexpected waitpid return from child $name: $rv (expected $pid)\n"
654 #XYZ unless $rv == $pid;
656 #XYZ local $/ = undef;
657 #XYZ local (OUT, ERR);
658 #XYZ open *OUT, '<', $outfn;
659 #XYZ open *ERR, '<', $errfn;
660 #XYZ my $out = <OUT>;
661 #XYZ my $err = <ERR>;
665 #XYZ return $status >> 8, $status & 127, $status & 128 , $out, $err
668 # return codes and old-style call semantics left for backwards compatibility
670 my $savewarn = $SIG{__WARN__};
671 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
672 local $SIG{__WARN__} =
675 if defined $savewarn and
676 UNIVERSAL::isa($savewarn,'CODE') and
677 $_[0] !~ /^Subroutine compare redefined/;
681 my ($fn1, $fn2, $sort) = @_;
682 my ($gzip, $tar, $name);
685 if ( @_ == 1 and UNIVERSAL::isa($_[0], 'HASH') ) {
686 ($fn1, $fn2, $name, $sort, $gzip, $tar, $notest) =
687 @{$_[0]}{qw( fn1 fn2 name sort gunzip untar notest )};
688 my @missing = grep ! defined $_[0]->{$_}, qw( fn1 fn2 name );
689 carp "Missing mandatory key(s): " . join(', ', @missing) . "\n"
693 my ($name1, $name2) = ($fn1, $fn2);
695 for ( grep ! defined, $fn1, $fn2 ) {
696 carp 'Usage: compare({fn1 => $fn1, fn2 => $fn2, name => "some name"})' ."\n"
707 my $fn = ($name1, $name2)[$_];
709 carp "Does not exist: $fn\n"
712 } elsif ( ! -r $fn ) {
713 carp "Cannot read: $fn\n"
727 unless ( find_exec('gzip') ) {
728 print "ok # Skip gzip not found in path\n";
734 system "gzip $fn1 -cd > $tmp1"
735 and croak "gzip $fn1 failed: $?\n";
736 system "gzip $fn2 -cd > $tmp2"
737 and croak "gzip $fn2 failed: $?\n";
738 ($fn1, $fn2) = ($tmp1, $tmp2);
742 unless ( find_exec('tar') ) {
743 print "ok # Skip tar not found in path\n";
748 chomp (my @list1 = sort qx( tar tf $fn1 ));
749 croak "tar tf $fn1 failed with wait status: $?\n"
751 chomp(my @list2 = sort qx( tar tf $fn2 ));
752 croak "tar tf $fn2 failed with wait status: $?\n"
755 if ( @list2 > @list1 ) {
757 sprintf("More files (%d) in $name2 than $name1 (%d)\n",
758 scalar @list2, scalar @list1)
760 ok @list1, @list2, $name
763 } elsif ( @list1 > @list2 ) {
765 sprintf("More files (%d) in $name1 than $name2 (%d)\n",
766 scalar @list1, scalar @list2)
768 ok @list1, @list2, $name
773 for (my $i = 0; $i < @list1; $i++) {
774 if ( $list1[$i] lt $list2[$i] ) {
775 carp "File $list1[$i] is present in $name1 but not $name2\n"
777 ok $list1[$i], $list2[$i], $name
780 } elsif ( $list1[$i] gt $list2[$i] ) {
781 carp "File $list2[$i] is present in $name2 but not $name1\n"
783 ok $list2[$i], $list1[$i], $name
789 for my $fn (@list1) {
792 system "tar -xf $fn1 -O $fn > $tmp1"
793 and croak "tar -xf $fn1 -O $fn failed: $?\n";
794 system "tar -xf $fn2 -O $fn > $tmp2"
795 and croak "tar -xf $fn2 -O $fn failed: $?\n";
796 my $ok = compare({ fn1 => $tmp1,
801 qq'Subcheck file "$fn" for compare $name1, $name2',
803 unless ( $ok >= 1 ) {
804 carp qq'Difference found testing file "$fn" in tars $name1 ($tmp1), $name2 ($tmp2)\n'
818 unless ( find_exec('sort') ) {
819 print "ok # Skip sort not found in path\n";
825 system sort => $fn1, -o => $tmp1
826 and croak "Sort $fn1 failed: $?\n";
827 system sort => $fn2, -o => $tmp2
828 and croak "Sort $fn2 failed: $?\n";
829 ($fn1, $fn2) = ($tmp1, $tmp2);
832 unless ( File::Compare::compare($fn1, $fn2) ) {
838 if ( $ENV{TEST_DEBUG} ) {
840 die "Fork failed: $!\n"
843 if ( $pid ) { # Parent
844 my $waitpid = waitpid($pid, 0);
845 die "Waitpid got: $waitpid (expected $pid)\n"
846 unless $waitpid == $pid;
848 open *STDOUT{IO}, ">&" . fileno STDERR;
849 # Uniquify file names
850 my @args = keys %{+{ map {;$_=>1} $name1, $name2, $fn1, $fn2 }};
851 exec qw(ls -l), @args;
854 my $fh1 = IO::File->new($fn1, O_RDONLY)
855 or die "Couldn't open $fn1: $!\n";
856 my $fh2 = IO::File->new($fn2, O_RDONLY)
857 or die "Couldn't open $fn2: $!\n";
862 while ( ! $found and my $line1 = <$fh1> ) {
864 if ( ! defined $line2 ) {
865 print STDERR "$fn2 ended at line: $.\n";
867 } elsif ( $line2 ne $line1 ) {
868 my $maxlength = max(map length($_), $line1, $line2);
869 my $minlength = min(map length($_), $line1, $line2);
871 my @diffchars = grep(substr($line1, $_, 1) ne substr($line2, $_, 1),
873 my $diff = ' ' x $minlength;
874 substr($diff, $_, 1) = '|'
877 my @extrachars, map((length($line1) > length($line2) ? '^' : 'v'),
878 $minlength..$maxlength-1);
880 $diff = join '', $diff, @extrachars;
882 my $diff_count = @diffchars;
883 my $extra_count = @extrachars;
885 print STDERR <<"END";
886 Difference at line $. ($diff_count characters differ) (top line is $extra_count chars longer):
892 Differing characters at positions @{[join ',',@diffchars]} (zero-based)
900 if ( defined $line2 ) {
901 print STDERR "$name1 ended before line: $.\n";
903 print STDERR "Difference between $name1, $name2 not found!\n";
917 # -------------------------------------
921 Perform a requisite check on a given executable. This will skip if the
922 required modules are not present.
924 4+(n+m)*2 tests are performed, where n is the number of prerequisites
925 expected, and m is the number of outputs expected.
931 check_req('ccu-touch',
933 [[REQ_FILE, '/etc/passwd']],
934 [[REQ_FILE, 'passwd.foo']],
944 The name of the command to run. It is assumed that this command is in
945 blib/script; hence it should be an executable in this package, and C<make>
946 shuold have been run recently.
950 The arguments to pass to the cmd_name, as an arrayref.
954 The expected prerequisites, as an arrayref, wherein every member is a
955 two-element arrayref, the members being the requisite type, and the requisite
960 The expected outputs, in the same format as the L<epres|"epres">.
964 The name to use in error messages.
973 my ($cmd_name, $args, $epres, $eouts, $testname) = @_;
975 eval "use Pipeline::DataFlow 1.03 qw( :req_types );";
980 $skip = 'Skipped: Pipeline::DataFlow 1.03 not found';
987 my ($code, $expect) = @_;
988 my $name = sprintf "%s (%2d)", $testname, $count++;
989 my $value = UNIVERSAL::isa($code, 'CODE') ? $code->($name) : $code;
990 skip $skip, $value, $expect, $name;
993 # Initialize nicely to cope when read_reqs fails
994 my ($pres, $outs) = ([], []);
998 ($pres, $outs) = Pipeline::DataFlow->read_reqs
999 ([catfile($Bin, updir, 'blib', 'script', $cmd_name),
1004 $test->(scalar @$pres, scalar @$epres);
1007 @epres = sort { $a->[1] cmp $b->[1] } @$epres;
1008 @pres = sort { $a->[1] cmp $b->[1] } @$pres;
1010 for (my $i = 0; $i < @epres; $i++) {
1011 my ($type, $value) = @{$epres[$i]};
1012 $test->($type, @pres > $i ? $pres[$i]->[0] : undef);
1013 $test->($value, @pres > $i ? $pres[$i]->[1] : undef);
1016 $test->(scalar @$outs, scalar @$eouts);
1019 @eouts = sort { $a->[1] cmp $b->[1] } @$eouts;
1020 @outs = sort { $a->[1] cmp $b->[1] } @$outs;
1022 for (my $i = 0; $i < @eouts; $i++) {
1023 my ($type, $value) = @{$eouts[$i]};
1024 $test->($type, @outs > $i ? $outs[$i]->[0] : undef);
1025 $test->($value, @outs > $i ? $outs[$i]->[1] : undef);
1028 $test->(only_files([]), 1);
1031 # -------------------------------------
1043 The name of the program
1053 The path to the first executable file with the given name on C<$PATH>. Or
1054 nothing, if no such file exists.
1062 # defined further up to use in constants
1064 # -------------------------------------
1078 =item line-terminator
1080 B<Optional>. Value of C<$/>. Defaults to C<"\n">.
1090 A list of lines in the file (lines determined by the value of
1091 line-terminator), as an arrayref.
1100 my ($fn, $term) = @_;
1103 unless defined $term;
1105 my $fh = do { local *F; *F };
1106 sysopen $fh, $fn, O_RDONLY;
1114 # ----------------------------------------------------------------------------
1124 =head1 REPORTING BUGS
1130 Martyn J. Pearce C<fluffy@cpan.org>
1134 Copyright (c) 2001, 2002, 2004 Martyn J. Pearce. This program is free
1135 software; you can redistribute it and/or modify it under the same terms as
1144 1; # keep require happy.