RE: MM in maint@21251 breaks mp2
[p5sagit/p5-mst-13.2.git] / lib / Test / Builder.pm
index 2d8eddd..6f3edd8 100644 (file)
@@ -8,17 +8,32 @@ $^C ||= 0;
 
 use strict;
 use vars qw($VERSION $CLASS);
-$VERSION = '0.11';
+$VERSION = '0.17';
 $CLASS = __PACKAGE__;
 
 my $IsVMS = $^O eq 'VMS';
 
+# Make Test::Builder thread-safe for ithreads.
+BEGIN {
+    use Config;
+    if( $] >= 5.008 && $Config{useithreads} ) {
+        require threads;
+        require threads::shared;
+        threads::shared->import;
+    }
+    else {
+        *share = sub { 0 };
+        *lock  = sub { 0 };
+    }
+}
+
 use vars qw($Level);
-my @Test_Results = ();
-my @Test_Details = ();
 my($Test_Died) = 0;
 my($Have_Plan) = 0;
-my $Curr_Test = 0;
+my $Original_Pid = $$;
+my $Curr_Test = 0;      share($Curr_Test);
+my @Test_Results = ();  share(@Test_Results);
+my @Test_Details = ();  share(@Test_Details);
 
 
 =head1 NAME
@@ -55,9 +70,6 @@ Test::Builder - Backend for building test libraries
 
 =head1 DESCRIPTION
 
-I<THIS IS ALPHA GRADE SOFTWARE>  Meaning the underlying code is well
-tested, yet the interface is subject to change.
-
 Test::Simple and Test::More have proven to be popular testing modules,
 but they're not always flexible enough.  Test::Builder provides the a
 building block upon which to write your own test libraries I<which can
@@ -134,6 +146,11 @@ sub plan {
 
     return unless $cmd;
 
+    if( $Have_Plan ) {
+        die sprintf "You tried to plan twice!  Second plan at %s line %d\n",
+          ($self->caller)[1,2];
+    }
+
     if( $cmd eq 'no_plan' ) {
         $self->no_plan;
     }
@@ -152,6 +169,13 @@ sub plan {
             die "You said to run 0 tests!  You've got to run something.\n";
         }
     }
+    else {
+        require Carp;
+        my @args = grep { defined } ($cmd, $arg);
+        Carp::croak("plan() doesn't understand @args");
+    }
+
+    return 1;
 }
 
 =item B<expected_tests>
@@ -192,6 +216,21 @@ sub no_plan {
     $Have_Plan  = 1;
 }
 
+=item B<has_plan>
+
+  $plan = $Test->has_plan
+  
+Find out whether a plan has been defined. $plan is either C<undef> (no plan has been set), C<no_plan> (indeterminate # of tests) or an integer (the number of expected tests).
+
+=cut
+
+sub has_plan {
+       return($Expected_Tests) if $Expected_Tests;
+       return('no_plan') if $No_Plan;
+       return(undef);
+};
+
+
 =item B<skip_all>
 
   $Test->skip_all;
@@ -238,12 +277,18 @@ like Test::Simple's ok().
 sub ok {
     my($self, $test, $name) = @_;
 
+    # $test might contain an object which we don't want to accidentally
+    # store, so we turn it into a boolean.
+    $test = $test ? 1 : 0;
+
     unless( $Have_Plan ) {
-        die "You tried to run a test without a plan!  Gotta have a plan.\n";
+        require Carp;
+        Carp::croak("You tried to run a test without a plan!  Gotta have a plan.");
     }
 
+    lock $Curr_Test;
     $Curr_Test++;
-    
+
     $self->diag(<<ERR) if defined $name and $name =~ /^[\d\s]+$/;
     You named your test '$name'.  You shouldn't use numbers for your test names.
     Very confusing.
@@ -254,12 +299,15 @@ ERR
     my $todo = $self->todo($pack);
 
     my $out;
+    my $result = {};
+    share($result);
+
     unless( $test ) {
         $out .= "not ";
-        $Test_Results[$Curr_Test-1] = $todo ? 1 : 0;
+        @$result{ 'ok', 'actual_ok' } = ( ( $todo ? 1 : 0 ), 0 );
     }
     else {
-        $Test_Results[$Curr_Test-1] = 1;
+        @$result{ 'ok', 'actual_ok' } = ( 1, $test );
     }
 
     $out .= "ok";
@@ -268,13 +316,24 @@ ERR
     if( defined $name ) {
         $name =~ s|#|\\#|g;     # # in a name can confuse Test::Harness.
         $out   .= " - $name";
+        $result->{name} = $name;
+    }
+    else {
+        $result->{name} = '';
     }
 
     if( $todo ) {
         my $what_todo = $todo;
         $out   .= " # TODO $what_todo";
+        $result->{reason} = $what_todo;
+        $result->{type}   = 'todo';
+    }
+    else {
+        $result->{reason} = '';
+        $result->{type}   = '';
     }
 
+    $Test_Results[$Curr_Test-1] = $result;
     $out .= "\n";
 
     $self->_print($out);
@@ -354,7 +413,7 @@ sub _is_diag {
         }
     }
 
-    $self->diag(sprintf <<DIAGNOSTIC, $got, $expect);
+    return $self->diag(sprintf <<DIAGNOSTIC, $got, $expect);
          got: %s
     expected: %s
 DIAGNOSTIC
@@ -443,25 +502,57 @@ sub unlike {
     $self->_regex_ok($this, $regex, '!~', $name);
 }
 
-sub _regex_ok {
-    my($self, $this, $regex, $cmp, $name) = @_;
+=item B<maybe_regex>
 
-    local $Level = $Level + 1;
+  $Test->maybe_regex(qr/$regex/);
+  $Test->maybe_regex('/$regex/');
 
-    my $ok = 0;
-    my $usable_regex;
+Convenience method for building testing functions that take regular
+expressions as arguments, but need to work before perl 5.005.
+
+Takes a quoted regular expression produced by qr//, or a string
+representing a regular expression.
+
+Returns a Perl value which may be used instead of the corresponding
+regular expression, or undef if it's argument is not recognised.
+
+For example, a version of like(), sans the useful diagnostic messages,
+could be written as:
+
+  sub laconic_like {
+      my ($self, $this, $regex, $name) = @_;
+      my $usable_regex = $self->maybe_regex($regex);
+      die "expecting regex, found '$regex'\n"
+          unless $usable_regex;
+      $self->ok($this =~ m/$usable_regex/, $name);
+  }
+
+=cut
+
+
+sub maybe_regex {
+       my ($self, $regex) = @_;
+    my $usable_regex = undef;
     if( ref $regex eq 'Regexp' ) {
         $usable_regex = $regex;
     }
     # Check if it looks like '/foo/'
     elsif( my($re, $opts) = $regex =~ m{^ /(.*)/ (\w*) $ }sx ) {
-        $usable_regex = "(?$opts)$re";
-    }
-    else {
-        $ok = $self->ok( 0, $name );
+        $usable_regex = length $opts ? "(?$opts)$re" : $re;
+    };
+    return($usable_regex)
+};
 
-        $self->diag("    '$regex' doesn't look much like a regex to me.");
+sub _regex_ok {
+    my($self, $this, $regex, $cmp, $name) = @_;
+
+    local $Level = $Level + 1;
 
+    my $ok = 0;
+    my $usable_regex = $self->maybe_regex($regex);
+    unless (defined $usable_regex) {
+        $ok = $self->ok( 0, $name );
+        $self->diag("    '$regex' doesn't look much like a regex to me.");
         return $ok;
     }
 
@@ -524,7 +615,7 @@ sub _cmp_diag {
     
     $got    = defined $got    ? "'$got'"    : 'undef';
     $expect = defined $expect ? "'$expect'" : 'undef';
-    $self->diag(sprintf <<DIAGNOSTIC, $got, $type, $expect);
+    return $self->diag(sprintf <<DIAGNOSTIC, $got, $type, $expect);
     %s
         %s
     %s
@@ -564,12 +655,23 @@ sub skip {
     $why ||= '';
 
     unless( $Have_Plan ) {
-        die "You tried to run tests without a plan!  Gotta have a plan.\n";
+        require Carp;
+        Carp::croak("You tried to run tests without a plan!  Gotta have a plan.");
     }
 
+    lock($Curr_Test);
     $Curr_Test++;
 
-    $Test_Results[$Curr_Test-1] = 1;
+    my %result;
+    share(%result);
+    %result = (
+        'ok'      => 1,
+        actual_ok => 1,
+        name      => '',
+        type      => 'skip',
+        reason    => $why,
+    );
+    $Test_Results[$Curr_Test-1] = \%result;
 
     my $out = "ok";
     $out   .= " $Curr_Test" if $self->use_numbers;
@@ -598,16 +700,28 @@ sub todo_skip {
     $why ||= '';
 
     unless( $Have_Plan ) {
-        die "You tried to run tests without a plan!  Gotta have a plan.\n";
+        require Carp;
+        Carp::croak("You tried to run tests without a plan!  Gotta have a plan.");
     }
 
+    lock($Curr_Test);
     $Curr_Test++;
 
-    $Test_Results[$Curr_Test-1] = 1;
+    my %result;
+    share(%result);
+    %result = (
+        'ok'      => 1,
+        actual_ok => 0,
+        name      => '',
+        type      => 'todo_skip',
+        reason    => $why,
+    );
+
+    $Test_Results[$Curr_Test-1] = \%result;
 
     my $out = "not ok";
     $out   .= " $Curr_Test" if $self->use_numbers;
-    $out   .= " # TODO $why\n";
+    $out   .= " # TODO & SKIP $why\n";
 
     $Test->_print($out);
 
@@ -765,6 +879,14 @@ already.
 
 We encourage using this rather than calling print directly.
 
+Returns false.  Why?  Because diag() is often used in conjunction with
+a failing test (C<ok() || diag()>) it "passes through" the failure.
+
+    return ok(...) || diag(...);
+
+=for blame transfer
+Mark Fowler <mark@twoshortplanks.com>
+
 =cut
 
 sub diag {
@@ -776,6 +898,7 @@ sub diag {
 
     # Escape each line with a #.
     foreach (@msgs) {
+        $_ = 'undef' unless defined;
         s/^/# /gms;
     }
 
@@ -785,6 +908,8 @@ sub diag {
     my $fh = $self->todo ? $self->todo_output : $self->failure_output;
     local($\, $", $,) = (undef, ' ', '');
     print $fh @msgs;
+
+    return 0;
 }
 
 =begin _private
@@ -808,6 +933,15 @@ sub _print {
 
     local($\, $", $,) = (undef, ' ', '');
     my $fh = $self->output;
+
+    # Escape each line after the first with a # so we don't
+    # confuse Test::Harness.
+    foreach (@msgs) {
+        s/\n(.)/\n# $1/sg;
+    }
+
+    push @msgs, "\n" unless $msgs[-1] =~ /\n\Z/;
+
     print $fh @msgs;
 }
 
@@ -932,8 +1066,28 @@ You usually shouldn't have to set this.
 sub current_test {
     my($self, $num) = @_;
 
+    lock($Curr_Test);
     if( defined $num ) {
+        unless( $Have_Plan ) {
+            require Carp;
+            Carp::croak("Can't change the current test number without a plan!");
+        }
+
         $Curr_Test = $num;
+        if( $num > @Test_Results ) {
+            my $start = @Test_Results ? $#Test_Results + 1 : 0;
+            for ($start..$num-1) {
+                my %result;
+                share(%result);
+                %result = ( ok        => 1, 
+                            actual_ok => undef, 
+                            reason    => 'incrementing test number', 
+                            type      => 'unknown', 
+                            name      => undef 
+                          );
+                $Test_Results[$_] = \%result;
+            }
+        }
     }
     return $Curr_Test;
 }
@@ -953,23 +1107,62 @@ Of course, test #1 is $tests[0], etc...
 sub summary {
     my($self) = shift;
 
-    return @Test_Results;
+    return map { $_->{'ok'} } @Test_Results;
 }
 
-=item B<details>  I<UNIMPLEMENTED>
+=item B<details>
 
     my @tests = $Test->details;
 
 Like summary(), but with a lot more detail.
 
     $tests[$test_num - 1] = 
-            { ok         => is the test considered ok?
+            { 'ok'       => is the test considered a pass?
               actual_ok  => did it literally say 'ok'?
               name       => name of the test (if any)
-              type       => 'skip' or 'todo' (if any)
+              type       => type of test (if any, see below).
               reason     => reason for the above (if any)
             };
 
+'ok' is true if Test::Harness will consider the test to be a pass.
+
+'actual_ok' is a reflection of whether or not the test literally
+printed 'ok' or 'not ok'.  This is for examining the result of 'todo'
+tests.  
+
+'name' is the name of the test.
+
+'type' indicates if it was a special test.  Normal tests have a type
+of ''.  Type can be one of the following:
+
+    skip        see skip()
+    todo        see todo()
+    todo_skip   see todo_skip()
+    unknown     see below
+
+Sometimes the Test::Builder test counter is incremented without it
+printing any test output, for example, when current_test() is changed.
+In these cases, Test::Builder doesn't know the result of the test, so
+it's type is 'unkown'.  These details for these tests are filled in.
+They are considered ok, but the name and actual_ok is left undef.
+
+For example "not ok 23 - hole count # TODO insufficient donuts" would
+result in this structure:
+
+    $tests[22] =    # 23 - 1, since arrays start from 0.
+      { ok        => 1,   # logically, the test passed since it's todo
+        actual_ok => 0,   # in absolute terms, it failed
+        name      => 'hole count',
+        type      => 'todo',
+        reason    => 'insufficient donuts'
+      };
+
+=cut
+
+sub details {
+    return @Test_Results;
+}
+
 =item B<todo>
 
     my $todo_reason = $Test->todo;
@@ -1013,7 +1206,7 @@ Like the normal caller(), except it reports according to your level().
 sub caller {
     my($self, $height) = @_;
     $height ||= 0;
-    
+
     my @caller = CORE::caller($self->level + $height + 1);
     return wantarray ? @caller : $caller[0];
 }
@@ -1106,9 +1299,13 @@ sub _ending {
 
     _sanity_check();
 
+    # Don't bother with an ending if this is a forked copy.  Only the parent
+    # should do the ending.
+    do{ _my_exit($?) && return } if $Original_Pid != $$;
+
     # Bailout if plan() was never called.  This is so
     # "require Test::Simple" doesn't puke.
-    do{ _my_exit(0) && return } if !$Have_Plan;
+    do{ _my_exit(0) && return } if !$Have_Plan && !$Test_Died;
 
     # Figure out if we passed or failed and print helpful messages.
     if( @Test_Results ) {
@@ -1118,7 +1315,17 @@ sub _ending {
             $Expected_Tests = $Curr_Test;
         }
 
-        my $num_failed = grep !$_, @Test_Results[0..$Expected_Tests-1];
+        # 5.8.0 threads bug.  Shared arrays will not be auto-extended 
+        # by a slice.  Worse, we have to fill in every entry else
+        # we'll get an "Invalid value for shared scalar" error
+        for my $idx ($#Test_Results..$Expected_Tests-1) {
+            my %empty_result = ();
+            share(%empty_result);
+            $Test_Results[$idx] = \%empty_result
+              unless defined $Test_Results[$idx];
+        }
+
+        my $num_failed = grep !$_->{'ok'}, @Test_Results[0..$Expected_Tests-1];
         $num_failed += abs($Expected_Tests - @Test_Results);
 
         if( $Curr_Test < $Expected_Tests ) {
@@ -1151,6 +1358,11 @@ FAIL
     elsif ( $Skip_All ) {
         _my_exit( 0 ) && return;
     }
+    elsif ( $Test_Died ) {
+        $self->diag(<<'FAIL');
+Looks like your test died before it could output anything.
+FAIL
+    }
     else {
         $self->diag("No tests run!\n");
         _my_exit( 255 ) && return;
@@ -1161,9 +1373,16 @@ END {
     $Test->_ending if defined $Test and !$Test->no_ending;
 }
 
+=head1 THREADS
+
+In perl 5.8.0 and later, Test::Builder is thread-safe.  The test
+number is shared amongst all threads.  This means if one thread sets
+the test number using current_test() they will all be effected.
+
 =head1 EXAMPLES
 
-At this point, Test::Simple and Test::More are your best examples.
+CPAN can provide the best examples.  Test::Simple, Test::More,
+Test::Exception and Test::Differences all use Test::Builder.
 
 =head1 SEE ALSO
 
@@ -1176,7 +1395,7 @@ E<lt>schwern@pobox.comE<gt>
 
 =head1 COPYRIGHT
 
-Copyright 2001 by chromatic E<lt>chromatic@wgz.orgE<gt>,
+Copyright 2002 by chromatic E<lt>chromatic@wgz.orgE<gt>,
                   Michael G Schwern E<lt>schwern@pobox.comE<gt>.
 
 This program is free software; you can redistribute it and/or