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( evcheck save_output restore_output );
105 # Utility -----------------------------
107 use Carp qw( carp croak );
108 use Cwd 2.01 qw( cwd );
110 use Fatal 1.02 qw( close open seek sysopen unlink );
111 use Fcntl 1.03 qw( :DEFAULT );
112 use File::Basename qw( basename );
113 use File::Compare 1.1002 qw( );
114 use File::Path 1.0401 qw( mkpath rmtree );
115 use File::Spec 0.6 qw( );
116 use FindBin 1.42 qw( $Bin );
117 use POSIX 1.02 qw( );
118 use Test 1.122 qw( ok skip );
120 # ----------------------------------------------------------------------------
123 if ( File::Spec->file_name_is_absolute($_[0]) ) {
126 return File::Spec->catdir(cwd, $_[0]);
131 croak "Can't min over 0 args!\n"
142 # -------------------------------------
144 # -------------------------------------
146 use constant BUILD_SCRIPT_DIR => => File::Spec->catdir( $Bin, File::Spec->updir, qw( blib script ) );
151 for (split /:/, $PATH) {
152 my $try = File::Spec->catfile($_, $exec);
159 # -------------------------------------
161 # -------------------------------------
163 $PATH = join ':', BUILD_SCRIPT_DIR, split /:/, $PATH;
168 my $tmpdn = tempdir();
172 die "Couldn't create temp dir: $tmpdn: $!\n"
173 unless -r $tmpdn and -w $tmpdn and -x $tmpdn and -o $tmpdn and -d $tmpdn;
175 #@INC = map rel2abs($_), @INC;
178 # -------------------------------------
180 # -------------------------------------
184 Eval code, return status
198 Name to use in error messages
208 1 if eval was okay, 0 if not.
217 my ($code, $name) = @_;
225 carp "Code $name failed: $@\n"
233 # -------------------------------------
237 Redirect a filehandle to temporary storage for later examination.
247 Name to store as (used in L<restore_output>)
251 The filehandle to save
257 # Map from names to saved filehandles.
259 # Values are arrayrefs, being filehandle that was saved (to restore), the
260 # filehandle being printed to in the meantime, and the original filehandle.
261 # This may be treated as a stack; to allow multiple saves... push & pop this
267 croak sprintf("%s takes 2 arguments\n", (caller 0)[3])
269 my ($name, $filehandle) = @_;
271 my $tmpfh = do { local *F; *F; };
272 my $savefh = do { local *F; *F; };
274 (undef, $tmpfh) = test::tmpnam();
275 select((select($tmpfh), $| = 1)[0]);
277 open $savefh, '>&' . fileno $filehandle
278 or die "can't dup $name: $!";
279 open $filehandle, '>&' . fileno $tmpfh
280 or die "can't open $name to tempfile: $!";
282 push @{$grabs{$name}}, $savefh, $tmpfh, $filehandle;
285 # -------------------------------------
287 =head2 restore_output
289 Restore a saved filehandle to its original state, return the saved output.
299 Name of the filehandle to restore (as passed to L<save_output>).
309 A single string being the output saved.
318 croak "$name has not been saved\n"
319 unless exists $grabs{$name};
320 croak "All saved instances of $name have been restored\n"
321 unless @{$grabs{$name}};
322 my ($savefh, $tmpfh, $origfh) = splice @{$grabs{$name}}, -3;
325 or die "cannot close $name opened to tempfile: $!";
326 open $origfh, '>&' . fileno $savefh
327 or die "cannot dup $name back again: $!";
328 select((select($origfh), $| = 1)[0]);
332 my $string = <$tmpfh>;
338 sub _test_save_restore_output {
339 warn "to stderr 1\n";
340 save_output("stderr", *STDERR{IO});
342 print 'SAVED:->:', restore_output("stderr"), ":<-\n";
343 warn "to stderr 2\n";
346 # -------------------------------------
350 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
351 if TEST_DEBUG has SAVE in the value.
361 I<Optional>. If defined, a name by which to refer to the tmpfile in user
372 Name of temporary file.
376 Open filehandle to temp file, in r/w mode. Only created & returned in list
388 my $savewarn = $SIG{__WARN__};
389 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
390 local $SIG{__WARN__} =
393 if defined $savewarn and
394 UNIVERSAL::isa($savewarn,'CODE') and
395 $_[0] !~ /^Subroutine tmpnam redefined/;
399 my $tmpnam = POSIX::tmpnam;
402 push @tmpfns, [ $tmpnam, $_[0] ];
404 push @tmpfns, $tmpnam;
408 sysopen my $tmpfh, $tmpnam, O_RDWR | O_CREAT | O_EXCL;
409 return $tmpnam, $tmpfh;
417 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
420 printf "Used temp file: %s (%s)\n", @$_;
422 print "Used temp file: $_\n";
426 unlink map((ref $_ ? $_->[0] : $_), @tmpfns)
431 # -------------------------------------
435 Very much like the one in L<POSIX> or L<File::Temp>, but does not get deleted
436 if TEST_DEBUG has SAVE in the value (does get deleted otherwise).
450 Name of temporary dir.
460 my $tempdir = POSIX::tmpnam;
462 or die "Failed to create temporary directory $tempdir: $!\n";
465 push @tmpdirs, [ $tempdir, $_[0] ];
467 push @tmpdirs, $tempdir;
476 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
477 printf "Used temp dir: %s (%s)\n", @$_;
479 # Solaris gets narky about removing the pwd.
480 chdir File::Spec->rootdir;
484 if ( defined $ENV{TEST_DEBUG} and $ENV{TEST_DEBUG} =~ /\bSAVE\b/ ) {
485 print "Used temp dir: $_\n";
487 # Solaris gets narky about removing the pwd.
488 chdir File::Spec->rootdir;
495 # -------------------------------------
499 compare(+{ fn1 => $fn1, fn2 => $fn2, gzip => 1 });
501 This performs one test.
507 A single argument is taken, considered as a hash ref, with the following keys:
509 In TEST_DEBUG mode, if the files do not compare equal, outputs file info on
516 B<Mandatory> File to compare
520 B<Mandatory> File to compare
524 B<Mandatory> Test name
528 B<Optional> sort files prior to comparison. Requires the C<sort> command to
529 be on C<$PATH> (else skips).
533 B<Optional> gunzip files prior to comparison. Requires the C<gzip> command to
534 be on C<$PATH> (else skips). gzip occurs prior to any sort.
538 B<Optional> untar files prior to comparison. Requires the C<tar> command to
539 be on C<$PATH> (else skips). any gzip occurs prior to any tar. Tar files are
540 considered equal if they each contain the same filenames & each file contained
541 is equal. If the sort flag is present, each file is sorted prior to comparison.
549 # return codes and old-style call semantics left for backwards compatibility
551 my $savewarn = $SIG{__WARN__};
552 # Subvert bizarre (& incorrect) subroutine redefined errors in 5.005_03
553 local $SIG{__WARN__} =
556 if defined $savewarn and
557 UNIVERSAL::isa($savewarn,'CODE') and
558 $_[0] !~ /^Subroutine compare redefined/;
562 my ($fn1, $fn2, $sort) = @_;
563 my ($gzip, $tar, $name);
566 if ( @_ == 1 and UNIVERSAL::isa($_[0], 'HASH') ) {
567 ($fn1, $fn2, $name, $sort, $gzip, $tar, $notest) =
568 @{$_[0]}{qw( fn1 fn2 name sort gunzip untar notest )};
569 my @missing = grep ! defined $_[0]->{$_}, qw( fn1 fn2 name );
570 carp "Missing mandatory key(s): " . join(', ', @missing) . "\n"
574 my ($name1, $name2) = ($fn1, $fn2);
576 for ( grep ! defined, $fn1, $fn2 ) {
577 carp 'Usage: compare({fn1 => $fn1, fn2 => $fn2, name => "some name"})' ."\n"
588 my $fn = ($name1, $name2)[$_];
590 carp "Does not exist: $fn\n"
593 } elsif ( ! -r $fn ) {
594 carp "Cannot read: $fn\n"
608 unless ( find_exec('gzip') ) {
609 print "ok # Skip gzip not found in path\n";
615 system "gzip $fn1 -cd > $tmp1"
616 and croak "gzip $fn1 failed: $?\n";
617 system "gzip $fn2 -cd > $tmp2"
618 and croak "gzip $fn2 failed: $?\n";
619 ($fn1, $fn2) = ($tmp1, $tmp2);
623 unless ( find_exec('tar') ) {
624 print "ok # Skip tar not found in path\n";
629 chomp (my @list1 = sort qx( tar tf $fn1 ));
630 croak "tar tf $fn1 failed with wait status: $?\n"
632 chomp(my @list2 = sort qx( tar tf $fn2 ));
633 croak "tar tf $fn2 failed with wait status: $?\n"
636 if ( @list2 > @list1 ) {
638 sprintf("More files (%d) in $name2 than $name1 (%d)\n",
639 scalar @list2, scalar @list1)
641 ok @list1, @list2, $name
644 } elsif ( @list1 > @list2 ) {
646 sprintf("More files (%d) in $name1 than $name2 (%d)\n",
647 scalar @list1, scalar @list2)
649 ok @list1, @list2, $name
654 for (my $i = 0; $i < @list1; $i++) {
655 if ( $list1[$i] lt $list2[$i] ) {
656 carp "File $list1[$i] is present in $name1 but not $name2\n"
658 ok $list1[$i], $list2[$i], $name
661 } elsif ( $list1[$i] gt $list2[$i] ) {
662 carp "File $list2[$i] is present in $name2 but not $name1\n"
664 ok $list2[$i], $list1[$i], $name
670 for my $fn (@list1) {
673 system "tar -xf $fn1 -O $fn > $tmp1"
674 and croak "tar -xf $fn1 -O $fn failed: $?\n";
675 system "tar -xf $fn2 -O $fn > $tmp2"
676 and croak "tar -xf $fn2 -O $fn failed: $?\n";
677 my $ok = compare({ fn1 => $tmp1,
682 qq'Subcheck file "$fn" for compare $name1, $name2',
684 unless ( $ok >= 1 ) {
685 carp qq'Difference found testing file "$fn" in tars $name1 ($tmp1), $name2 ($tmp2)\n'
699 unless ( find_exec('sort') ) {
700 print "ok # Skip sort not found in path\n";
706 system sort => $fn1, -o => $tmp1
707 and croak "Sort $fn1 failed: $?\n";
708 system sort => $fn2, -o => $tmp2
709 and croak "Sort $fn2 failed: $?\n";
710 ($fn1, $fn2) = ($tmp1, $tmp2);
713 unless ( File::Compare::compare($fn1, $fn2) ) {
719 if ( $ENV{TEST_DEBUG} ) {
721 die "Fork failed: $!\n"
724 if ( $pid ) { # Parent
725 my $waitpid = waitpid($pid, 0);
726 die "Waitpid got: $waitpid (expected $pid)\n"
727 unless $waitpid == $pid;
729 open *STDOUT{IO}, ">&" . fileno STDERR;
730 # Uniquify file names
731 my @args = keys %{+{ map {;$_=>1} $name1, $name2, $fn1, $fn2 }};
732 exec qw(ls -l), @args;
735 my $fh1 = IO::File->new($fn1, O_RDONLY)
736 or die "Couldn't open $fn1: $!\n";
737 my $fh2 = IO::File->new($fn2, O_RDONLY)
738 or die "Couldn't open $fn2: $!\n";
743 while ( ! $found and my $line1 = <$fh1> ) {
745 if ( ! defined $line2 ) {
746 print STDERR "$fn2 ended at line: $.\n";
748 } elsif ( $line2 ne $line1 ) {
749 my $maxlength = max(map length($_), $line1, $line2);
750 my $minlength = min(map length($_), $line1, $line2);
752 my @diffchars = grep(substr($line1, $_, 1) ne substr($line2, $_, 1),
754 my $diff = ' ' x $minlength;
755 substr($diff, $_, 1) = '|'
758 my @extrachars, map((length($line1) > length($line2) ? '^' : 'v'),
759 $minlength..$maxlength-1);
761 $diff = join '', $diff, @extrachars;
763 my $diff_count = @diffchars;
764 my $extra_count = @extrachars;
766 print STDERR <<"END";
767 Difference at line $. ($diff_count characters differ) (top line is $extra_count chars longer):
773 Differing characters at positions @{[join ',',@diffchars]} (zero-based)
781 if ( defined $line2 ) {
782 print STDERR "$name1 ended before line: $.\n";
784 print STDERR "Difference between $name1, $name2 not found!\n";
798 # -------------------------------------
810 The name of the program
820 The path to the first executable file with the given name on C<$PATH>. Or
821 nothing, if no such file exists.
829 # defined further up to use in constants
831 # ----------------------------------------------------------------------------
841 =head1 REPORTING BUGS
847 Martyn J. Pearce C<fluffy@cpan.org>
851 Copyright (c) 2001, 2002, 2004 Martyn J. Pearce. This program is free
852 software; you can redistribute it and/or modify it under the same terms as
861 1; # keep require happy.