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:
105 @EXPORT_OK = qw( compare evcheck
106 save_output restore_output tempdir tmpnam );
108 # Utility -----------------------------
110 use Carp qw( carp croak );
111 use Cwd 2.01 qw( cwd );
113 use Fatal 1.02 qw( close open seek sysopen unlink );
114 use Fcntl 1.03 qw( :DEFAULT );
115 use File::Basename qw( basename );
116 use File::Compare 1.1002 qw( );
117 use File::Path 1.0401 qw( mkpath rmtree );
118 use File::Spec 0.6 qw( );
119 use FindBin 1.42 qw( $Bin );
120 use POSIX 1.02 qw( );
121 use Test 1.122 qw( ok skip );
123 # ----------------------------------------------------------------------------
126 if ( File::Spec->file_name_is_absolute($_[0]) ) {
129 return catdir(cwd, $_[0]);
134 File::Spec->catdir(@_);
138 File::Spec->catfile(@_);
142 File::Spec->updir(@_);
146 croak "Can't min over 0 args!\n"
157 # -------------------------------------
159 # -------------------------------------
161 use constant BUILD_SCRIPT_DIR => => catdir $Bin, updir, qw( blib script );
166 for (split /:/, $PATH) {
167 my $try = catfile $_, $exec;
174 # -------------------------------------
176 # -------------------------------------
178 $PATH = join ':', BUILD_SCRIPT_DIR, split /:/, $PATH;
183 my $tmpdn = tempdir();
187 die "Couldn't create temp dir: $tmpdn: $!\n"
188 unless -r $tmpdn and -w $tmpdn and -x $tmpdn and -o $tmpdn and -d $tmpdn;
190 #@INC = map rel2abs($_), @INC;
193 # -------------------------------------
195 # -------------------------------------
207 Arrayref of names of files to expect to exist.
217 1 if exactly expected files exist, false otherwise.
230 my %files = map { $_ => 1 } readdir MYDIR;
235 for (@$expect, '.', '..') {
236 if ( exists $files{$_} ) {
238 } elsif ( ! -e $_ ) { # $_ might be absolute
239 carp "File not found: $_\n"
246 carp "Extra file found: $_\n"
258 # -------------------------------------
262 Eval code, return status
276 Name to use in error messages
286 1 if eval was okay, 0 if not.
295 my ($code, $name) = @_;
303 carp "Code $name failed: $@\n"
311 # -------------------------------------
315 Redirect a filehandle to temporary storage for later examination.
325 Name to store as (used in L<restore_output>)
329 The filehandle to save
335 # Map from names to saved filehandles.
337 # Values are arrayrefs, being filehandle that was saved (to restore), the
338 # filehandle being printed to in the meantime, and the original filehandle.
339 # This may be treated as a stack; to allow multiple saves... push & pop this
345 croak sprintf("%s takes 2 arguments\n", (caller 0)[3])
347 my ($name, $filehandle) = @_;
349 my $tmpfh = do { local *F; *F; };
350 my $savefh = do { local *F; *F; };
352 (undef, $tmpfh) = test::tmpnam();
353 select((select($tmpfh), $| = 1)[0]);
355 open $savefh, '>&' . fileno $filehandle
356 or die "can't dup $name: $!";
357 open $filehandle, '>&' . fileno $tmpfh
358 or die "can't open $name to tempfile: $!";
360 push @{$grabs{$name}}, $savefh, $tmpfh, $filehandle;
363 # -------------------------------------
365 =head2 restore_output
367 Restore a saved filehandle to its original state, return the saved output.
377 Name of the filehandle to restore (as passed to L<save_output>).
387 A single string being the output saved.
396 croak "$name has not been saved\n"
397 unless exists $grabs{$name};
398 croak "All saved instances of $name have been restored\n"
399 unless @{$grabs{$name}};
400 my ($savefh, $tmpfh, $origfh) = splice @{$grabs{$name}}, -3;
403 or die "cannot close $name opened to tempfile: $!";
404 open $origfh, '>&' . fileno $savefh
405 or die "cannot dup $name back again: $!";
406 select((select($origfh), $| = 1)[0]);
410 my $string = <$tmpfh>;
416 sub _test_save_restore_output {
417 warn "to stderr 1\n";
418 save_output("stderr", *STDERR{IO});
420 print 'SAVED:->:', restore_output("stderr"), ":<-\n";
421 warn "to stderr 2\n";
424 # -------------------------------------
428 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
429 if TEST_DEBUG has SAVE in the value.
439 I<Optional>. If defined, a name by which to refer to the tmpfile in user
450 Name of temporary file.
454 Open filehandle to temp file, in r/w mode. Only created & returned in list
466 my $savewarn = $SIG{__WARN__};
467 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
468 local $SIG{__WARN__} =
471 if defined $savewarn and
472 UNIVERSAL::isa($savewarn,'CODE') and
473 $_[0] !~ /^Subroutine tmpnam redefined/;
477 my $tmpnam = POSIX::tmpnam;
480 push @tmpfns, [ $tmpnam, $_[0] ];
482 push @tmpfns, $tmpnam;
486 sysopen my $tmpfh, $tmpnam, O_RDWR | O_CREAT | O_EXCL;
487 return $tmpnam, $tmpfh;
495 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
498 printf "Used temp file: %s (%s)\n", @$_;
500 print "Used temp file: $_\n";
504 unlink map((ref $_ ? $_->[0] : $_), @tmpfns)
509 # -------------------------------------
513 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
514 if TEST_DEBUG has SAVE in the value (does get deleted otherwise).
528 Name of temporary dir.
538 my $tempdir = POSIX::tmpnam;
540 or die "Failed to create temporary directory $tempdir: $!\n";
543 push @tmpdirs, [ $tempdir, $_[0] ];
545 push @tmpdirs, $tempdir;
554 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
555 printf "Used temp dir: %s (%s)\n", @$_;
557 # Solaris gets narky about removing the pwd.
558 chdir File::Spec->rootdir;
562 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
563 print "Used temp dir: $_\n";
565 # Solaris gets narky about removing the pwd.
566 chdir File::Spec->rootdir;
573 # -------------------------------------
577 compare(+{ fn1 => $fn1, fn2 => $fn2, gzip => 1 });
579 This performs one test.
585 A single argument is taken, considered as a hash ref, with the following keys:
587 In TEST_DEBUG mode, if the files do not compare equal, outputs file info on
594 B<Mandatory> File to compare
598 B<Mandatory> File to compare
602 B<Mandatory> Test name
606 B<Optional> sort files prior to comparison. Requires the C<sort> command to
607 be on C<$PATH> (else skips).
611 B<Optional> gunzip files prior to comparison. Requires the C<gzip> command to
612 be on C<$PATH> (else skips). gzip occurs prior to any sort.
616 B<Optional> untar files prior to comparison. Requires the C<tar> command to
617 be on C<$PATH> (else skips). any gzip occurs prior to any tar. Tar files are
618 considered equal if they each contain the same filenames & each file contained
619 is equal. If the sort flag is present, each file is sorted prior to comparison.
627 # return codes and old-style call semantics left for backwards compatibility
629 my $savewarn = $SIG{__WARN__};
630 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
631 local $SIG{__WARN__} =
634 if defined $savewarn and
635 UNIVERSAL::isa($savewarn,'CODE') and
636 $_[0] !~ /^Subroutine compare redefined/;
640 my ($fn1, $fn2, $sort) = @_;
641 my ($gzip, $tar, $name);
644 if ( @_ == 1 and UNIVERSAL::isa($_[0], 'HASH') ) {
645 ($fn1, $fn2, $name, $sort, $gzip, $tar, $notest) =
646 @{$_[0]}{qw( fn1 fn2 name sort gunzip untar notest )};
647 my @missing = grep ! defined $_[0]->{$_}, qw( fn1 fn2 name );
648 carp "Missing mandatory key(s): " . join(', ', @missing) . "\n"
652 my ($name1, $name2) = ($fn1, $fn2);
654 for ( grep ! defined, $fn1, $fn2 ) {
655 carp 'Usage: compare({fn1 => $fn1, fn2 => $fn2, name => "some name"})' ."\n"
666 my $fn = ($name1, $name2)[$_];
668 carp "Does not exist: $fn\n"
671 } elsif ( ! -r $fn ) {
672 carp "Cannot read: $fn\n"
686 unless ( find_exec('gzip') ) {
687 print "ok # Skip gzip not found in path\n";
693 system "gzip $fn1 -cd > $tmp1"
694 and croak "gzip $fn1 failed: $?\n";
695 system "gzip $fn2 -cd > $tmp2"
696 and croak "gzip $fn2 failed: $?\n";
697 ($fn1, $fn2) = ($tmp1, $tmp2);
701 unless ( find_exec('tar') ) {
702 print "ok # Skip tar not found in path\n";
707 chomp (my @list1 = sort qx( tar tf $fn1 ));
708 croak "tar tf $fn1 failed with wait status: $?\n"
710 chomp(my @list2 = sort qx( tar tf $fn2 ));
711 croak "tar tf $fn2 failed with wait status: $?\n"
714 if ( @list2 > @list1 ) {
716 sprintf("More files (%d) in $name2 than $name1 (%d)\n",
717 scalar @list2, scalar @list1)
719 ok @list1, @list2, $name
722 } elsif ( @list1 > @list2 ) {
724 sprintf("More files (%d) in $name1 than $name2 (%d)\n",
725 scalar @list1, scalar @list2)
727 ok @list1, @list2, $name
732 for (my $i = 0; $i < @list1; $i++) {
733 if ( $list1[$i] lt $list2[$i] ) {
734 carp "File $list1[$i] is present in $name1 but not $name2\n"
736 ok $list1[$i], $list2[$i], $name
739 } elsif ( $list1[$i] gt $list2[$i] ) {
740 carp "File $list2[$i] is present in $name2 but not $name1\n"
742 ok $list2[$i], $list1[$i], $name
748 for my $fn (@list1) {
751 system "tar -xf $fn1 -O $fn > $tmp1"
752 and croak "tar -xf $fn1 -O $fn failed: $?\n";
753 system "tar -xf $fn2 -O $fn > $tmp2"
754 and croak "tar -xf $fn2 -O $fn failed: $?\n";
755 my $ok = compare({ fn1 => $tmp1,
760 qq'Subcheck file "$fn" for compare $name1, $name2',
762 unless ( $ok >= 1 ) {
763 carp qq'Difference found testing file "$fn" in tars $name1 ($tmp1), $name2 ($tmp2)\n'
777 unless ( find_exec('sort') ) {
778 print "ok # Skip sort not found in path\n";
784 system sort => $fn1, -o => $tmp1
785 and croak "Sort $fn1 failed: $?\n";
786 system sort => $fn2, -o => $tmp2
787 and croak "Sort $fn2 failed: $?\n";
788 ($fn1, $fn2) = ($tmp1, $tmp2);
791 unless ( File::Compare::compare($fn1, $fn2) ) {
797 if ( $ENV{TEST_DEBUG} ) {
799 die "Fork failed: $!\n"
802 if ( $pid ) { # Parent
803 my $waitpid = waitpid($pid, 0);
804 die "Waitpid got: $waitpid (expected $pid)\n"
805 unless $waitpid == $pid;
807 open *STDOUT{IO}, ">&" . fileno STDERR;
808 # Uniquify file names
809 my @args = keys %{+{ map {;$_=>1} $name1, $name2, $fn1, $fn2 }};
810 exec qw(ls -l), @args;
813 my $fh1 = IO::File->new($fn1, O_RDONLY)
814 or die "Couldn't open $fn1: $!\n";
815 my $fh2 = IO::File->new($fn2, O_RDONLY)
816 or die "Couldn't open $fn2: $!\n";
821 while ( ! $found and my $line1 = <$fh1> ) {
823 if ( ! defined $line2 ) {
824 print STDERR "$fn2 ended at line: $.\n";
826 } elsif ( $line2 ne $line1 ) {
827 my $maxlength = max(map length($_), $line1, $line2);
828 my $minlength = min(map length($_), $line1, $line2);
830 my @diffchars = grep(substr($line1, $_, 1) ne substr($line2, $_, 1),
832 my $diff = ' ' x $minlength;
833 substr($diff, $_, 1) = '|'
836 my @extrachars, map((length($line1) > length($line2) ? '^' : 'v'),
837 $minlength..$maxlength-1);
839 $diff = join '', $diff, @extrachars;
841 my $diff_count = @diffchars;
842 my $extra_count = @extrachars;
844 print STDERR <<"END";
845 Difference at line $. ($diff_count characters differ) (top line is $extra_count chars longer):
851 Differing characters at positions @{[join ',',@diffchars]} (zero-based)
859 if ( defined $line2 ) {
860 print STDERR "$name1 ended before line: $.\n";
862 print STDERR "Difference between $name1, $name2 not found!\n";
876 # -------------------------------------
888 The name of the program
898 The path to the first executable file with the given name on C<$PATH>. Or
899 nothing, if no such file exists.
907 # defined further up to use in constants
909 # ----------------------------------------------------------------------------
919 =head1 REPORTING BUGS
925 Martyn J. Pearce C<fluffy@cpan.org>
929 Copyright (c) 2001, 2002, 2004 Martyn J. Pearce. This program is free
930 software; you can redistribute it and/or modify it under the same terms as
939 1; # keep require happy.