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:
103 @EXPORT_OK = qw( compare evcheck
104 save_output restore_output tempdir tmpnam );
106 # Utility -----------------------------
108 use Carp qw( carp croak );
109 use Cwd 2.01 qw( cwd );
111 use Fatal 1.02 qw( close open seek sysopen unlink );
112 use Fcntl 1.03 qw( :DEFAULT );
113 use File::Basename qw( basename );
114 use File::Compare 1.1002 qw( );
115 use File::Path 1.0401 qw( mkpath rmtree );
116 use File::Spec 0.6 qw( );
117 use FindBin 1.42 qw( $Bin );
118 use POSIX 1.02 qw( );
119 use Test 1.122 qw( ok skip );
121 # ----------------------------------------------------------------------------
124 if ( File::Spec->file_name_is_absolute($_[0]) ) {
127 return catdir(cwd, $_[0]);
132 File::Spec->catdir(@_);
136 File::Spec->catfile(@_);
140 File::Spec->updir(@_);
144 croak "Can't min over 0 args!\n"
155 # -------------------------------------
157 # -------------------------------------
159 use constant BUILD_SCRIPT_DIR => => catdir $Bin, updir, qw( blib script );
164 for (split /:/, $PATH) {
165 my $try = catfile $_, $exec;
172 # -------------------------------------
174 # -------------------------------------
176 $PATH = join ':', BUILD_SCRIPT_DIR, split /:/, $PATH;
181 my $tmpdn = tempdir();
185 die "Couldn't create temp dir: $tmpdn: $!\n"
186 unless -r $tmpdn and -w $tmpdn and -x $tmpdn and -o $tmpdn and -d $tmpdn;
188 #@INC = map rel2abs($_), @INC;
191 # -------------------------------------
193 # -------------------------------------
197 Eval code, return status
211 Name to use in error messages
221 1 if eval was okay, 0 if not.
230 my ($code, $name) = @_;
238 carp "Code $name failed: $@\n"
246 # -------------------------------------
250 Redirect a filehandle to temporary storage for later examination.
260 Name to store as (used in L<restore_output>)
264 The filehandle to save
270 # Map from names to saved filehandles.
272 # Values are arrayrefs, being filehandle that was saved (to restore), the
273 # filehandle being printed to in the meantime, and the original filehandle.
274 # This may be treated as a stack; to allow multiple saves... push & pop this
280 croak sprintf("%s takes 2 arguments\n", (caller 0)[3])
282 my ($name, $filehandle) = @_;
284 my $tmpfh = do { local *F; *F; };
285 my $savefh = do { local *F; *F; };
287 (undef, $tmpfh) = test::tmpnam();
288 select((select($tmpfh), $| = 1)[0]);
290 open $savefh, '>&' . fileno $filehandle
291 or die "can't dup $name: $!";
292 open $filehandle, '>&' . fileno $tmpfh
293 or die "can't open $name to tempfile: $!";
295 push @{$grabs{$name}}, $savefh, $tmpfh, $filehandle;
298 # -------------------------------------
300 =head2 restore_output
302 Restore a saved filehandle to its original state, return the saved output.
312 Name of the filehandle to restore (as passed to L<save_output>).
322 A single string being the output saved.
331 croak "$name has not been saved\n"
332 unless exists $grabs{$name};
333 croak "All saved instances of $name have been restored\n"
334 unless @{$grabs{$name}};
335 my ($savefh, $tmpfh, $origfh) = splice @{$grabs{$name}}, -3;
338 or die "cannot close $name opened to tempfile: $!";
339 open $origfh, '>&' . fileno $savefh
340 or die "cannot dup $name back again: $!";
341 select((select($origfh), $| = 1)[0]);
345 my $string = <$tmpfh>;
351 sub _test_save_restore_output {
352 warn "to stderr 1\n";
353 save_output("stderr", *STDERR{IO});
355 print 'SAVED:->:', restore_output("stderr"), ":<-\n";
356 warn "to stderr 2\n";
359 # -------------------------------------
363 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
364 if TEST_DEBUG has SAVE in the value.
374 I<Optional>. If defined, a name by which to refer to the tmpfile in user
385 Name of temporary file.
389 Open filehandle to temp file, in r/w mode. Only created & returned in list
401 my $savewarn = $SIG{__WARN__};
402 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
403 local $SIG{__WARN__} =
406 if defined $savewarn and
407 UNIVERSAL::isa($savewarn,'CODE') and
408 $_[0] !~ /^Subroutine tmpnam redefined/;
412 my $tmpnam = POSIX::tmpnam;
415 push @tmpfns, [ $tmpnam, $_[0] ];
417 push @tmpfns, $tmpnam;
421 sysopen my $tmpfh, $tmpnam, O_RDWR | O_CREAT | O_EXCL;
422 return $tmpnam, $tmpfh;
430 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
433 printf "Used temp file: %s (%s)\n", @$_;
435 print "Used temp file: $_\n";
439 unlink map((ref $_ ? $_->[0] : $_), @tmpfns)
444 # -------------------------------------
448 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
449 if TEST_DEBUG has SAVE in the value (does get deleted otherwise).
463 Name of temporary dir.
473 my $tempdir = POSIX::tmpnam;
475 or die "Failed to create temporary directory $tempdir: $!\n";
478 push @tmpdirs, [ $tempdir, $_[0] ];
480 push @tmpdirs, $tempdir;
489 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
490 printf "Used temp dir: %s (%s)\n", @$_;
492 # Solaris gets narky about removing the pwd.
493 chdir File::Spec->rootdir;
497 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
498 print "Used temp dir: $_\n";
500 # Solaris gets narky about removing the pwd.
501 chdir File::Spec->rootdir;
508 # -------------------------------------
512 compare(+{ fn1 => $fn1, fn2 => $fn2, gzip => 1 });
514 This performs one test.
520 A single argument is taken, considered as a hash ref, with the following keys:
522 In TEST_DEBUG mode, if the files do not compare equal, outputs file info on
529 B<Mandatory> File to compare
533 B<Mandatory> File to compare
537 B<Mandatory> Test name
541 B<Optional> sort files prior to comparison. Requires the C<sort> command to
542 be on C<$PATH> (else skips).
546 B<Optional> gunzip files prior to comparison. Requires the C<gzip> command to
547 be on C<$PATH> (else skips). gzip occurs prior to any sort.
551 B<Optional> untar files prior to comparison. Requires the C<tar> command to
552 be on C<$PATH> (else skips). any gzip occurs prior to any tar. Tar files are
553 considered equal if they each contain the same filenames & each file contained
554 is equal. If the sort flag is present, each file is sorted prior to comparison.
562 # return codes and old-style call semantics left for backwards compatibility
564 my $savewarn = $SIG{__WARN__};
565 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
566 local $SIG{__WARN__} =
569 if defined $savewarn and
570 UNIVERSAL::isa($savewarn,'CODE') and
571 $_[0] !~ /^Subroutine compare redefined/;
575 my ($fn1, $fn2, $sort) = @_;
576 my ($gzip, $tar, $name);
579 if ( @_ == 1 and UNIVERSAL::isa($_[0], 'HASH') ) {
580 ($fn1, $fn2, $name, $sort, $gzip, $tar, $notest) =
581 @{$_[0]}{qw( fn1 fn2 name sort gunzip untar notest )};
582 my @missing = grep ! defined $_[0]->{$_}, qw( fn1 fn2 name );
583 carp "Missing mandatory key(s): " . join(', ', @missing) . "\n"
587 my ($name1, $name2) = ($fn1, $fn2);
589 for ( grep ! defined, $fn1, $fn2 ) {
590 carp 'Usage: compare({fn1 => $fn1, fn2 => $fn2, name => "some name"})' ."\n"
601 my $fn = ($name1, $name2)[$_];
603 carp "Does not exist: $fn\n"
606 } elsif ( ! -r $fn ) {
607 carp "Cannot read: $fn\n"
621 unless ( find_exec('gzip') ) {
622 print "ok # Skip gzip not found in path\n";
628 system "gzip $fn1 -cd > $tmp1"
629 and croak "gzip $fn1 failed: $?\n";
630 system "gzip $fn2 -cd > $tmp2"
631 and croak "gzip $fn2 failed: $?\n";
632 ($fn1, $fn2) = ($tmp1, $tmp2);
636 unless ( find_exec('tar') ) {
637 print "ok # Skip tar not found in path\n";
642 chomp (my @list1 = sort qx( tar tf $fn1 ));
643 croak "tar tf $fn1 failed with wait status: $?\n"
645 chomp(my @list2 = sort qx( tar tf $fn2 ));
646 croak "tar tf $fn2 failed with wait status: $?\n"
649 if ( @list2 > @list1 ) {
651 sprintf("More files (%d) in $name2 than $name1 (%d)\n",
652 scalar @list2, scalar @list1)
654 ok @list1, @list2, $name
657 } elsif ( @list1 > @list2 ) {
659 sprintf("More files (%d) in $name1 than $name2 (%d)\n",
660 scalar @list1, scalar @list2)
662 ok @list1, @list2, $name
667 for (my $i = 0; $i < @list1; $i++) {
668 if ( $list1[$i] lt $list2[$i] ) {
669 carp "File $list1[$i] is present in $name1 but not $name2\n"
671 ok $list1[$i], $list2[$i], $name
674 } elsif ( $list1[$i] gt $list2[$i] ) {
675 carp "File $list2[$i] is present in $name2 but not $name1\n"
677 ok $list2[$i], $list1[$i], $name
683 for my $fn (@list1) {
686 system "tar -xf $fn1 -O $fn > $tmp1"
687 and croak "tar -xf $fn1 -O $fn failed: $?\n";
688 system "tar -xf $fn2 -O $fn > $tmp2"
689 and croak "tar -xf $fn2 -O $fn failed: $?\n";
690 my $ok = compare({ fn1 => $tmp1,
695 qq'Subcheck file "$fn" for compare $name1, $name2',
697 unless ( $ok >= 1 ) {
698 carp qq'Difference found testing file "$fn" in tars $name1 ($tmp1), $name2 ($tmp2)\n'
712 unless ( find_exec('sort') ) {
713 print "ok # Skip sort not found in path\n";
719 system sort => $fn1, -o => $tmp1
720 and croak "Sort $fn1 failed: $?\n";
721 system sort => $fn2, -o => $tmp2
722 and croak "Sort $fn2 failed: $?\n";
723 ($fn1, $fn2) = ($tmp1, $tmp2);
726 unless ( File::Compare::compare($fn1, $fn2) ) {
732 if ( $ENV{TEST_DEBUG} ) {
734 die "Fork failed: $!\n"
737 if ( $pid ) { # Parent
738 my $waitpid = waitpid($pid, 0);
739 die "Waitpid got: $waitpid (expected $pid)\n"
740 unless $waitpid == $pid;
742 open *STDOUT{IO}, ">&" . fileno STDERR;
743 # Uniquify file names
744 my @args = keys %{+{ map {;$_=>1} $name1, $name2, $fn1, $fn2 }};
745 exec qw(ls -l), @args;
748 my $fh1 = IO::File->new($fn1, O_RDONLY)
749 or die "Couldn't open $fn1: $!\n";
750 my $fh2 = IO::File->new($fn2, O_RDONLY)
751 or die "Couldn't open $fn2: $!\n";
756 while ( ! $found and my $line1 = <$fh1> ) {
758 if ( ! defined $line2 ) {
759 print STDERR "$fn2 ended at line: $.\n";
761 } elsif ( $line2 ne $line1 ) {
762 my $maxlength = max(map length($_), $line1, $line2);
763 my $minlength = min(map length($_), $line1, $line2);
765 my @diffchars = grep(substr($line1, $_, 1) ne substr($line2, $_, 1),
767 my $diff = ' ' x $minlength;
768 substr($diff, $_, 1) = '|'
771 my @extrachars, map((length($line1) > length($line2) ? '^' : 'v'),
772 $minlength..$maxlength-1);
774 $diff = join '', $diff, @extrachars;
776 my $diff_count = @diffchars;
777 my $extra_count = @extrachars;
779 print STDERR <<"END";
780 Difference at line $. ($diff_count characters differ) (top line is $extra_count chars longer):
786 Differing characters at positions @{[join ',',@diffchars]} (zero-based)
794 if ( defined $line2 ) {
795 print STDERR "$name1 ended before line: $.\n";
797 print STDERR "Difference between $name1, $name2 not found!\n";
811 # -------------------------------------
823 The name of the program
833 The path to the first executable file with the given name on C<$PATH>. Or
834 nothing, if no such file exists.
842 # defined further up to use in constants
844 # ----------------------------------------------------------------------------
854 =head1 REPORTING BUGS
860 Martyn J. Pearce C<fluffy@cpan.org>
864 Copyright (c) 2001, 2002, 2004 Martyn J. Pearce. This program is free
865 software; you can redistribute it and/or modify it under the same terms as
874 1; # keep require happy.