Test-Unit

 view release on metacpan or  search on metacpan

lib/Test/Unit/Assertion/CodeRef.pm  view on Meta::CPAN

package Test::Unit::Assertion::CodeRef;

use strict;
use base qw/Test::Unit::Assertion/;

use Carp;
use Test::Unit::Debug qw(debug);

my $deparser;

sub new {
    my $class = shift;
    my $code = shift;
    croak "$class\::new needs a CODEREF" unless ref($code) eq 'CODE';
    bless \$code => $class;
}

sub do_assertion {
    my $self = shift;
    my $possible_object = $_[0];
    debug("Called do_assertion(" . ($possible_object || 'undef') . ")\n");
    if (ref($possible_object) and
        ref($possible_object) ne 'Regexp' and
        eval { $possible_object->isa('UNIVERSAL') })
    {
        debug("  [$possible_object] isa [" . ref($possible_object) . "]\n");
        $possible_object->$$self(@_[1..$#_]);
    }
    else {
        debug("  asserting [$self]"
              . (@_ ? " on args " . join(', ', map { $_ || '<undef>' } @_) : '')
              . "\n");
        $$self->(@_);
    }
}

sub to_string {
    my $self = shift;
    if (eval "require B::Deparse") {
        $deparser ||= B::Deparse->new("-p");
        return join '', "sub ", $deparser->coderef2text($$self);
    }
    else {
        return "sub {
    # If you had a working B::Deparse, you'd know what was in
    # this subroutine.
}";
    }
}

1;
__END__

=head1 NAME

Test::Unit::Assertion::CodeRef - A delayed evaluation assertion using a Coderef

=head1 SYNOPSIS

    require Test::Unit::Assertion::CodeRef;

    my $assert_eq =
      Test::Unit::Assertion::CodeRef->new(sub {
        $_[0] eq $_[1]
          or Test::Unit::Failure->throw(-text =>
                                          "Expected '$_[0]', got '$_[1]'\n");
      });

    $assert_eq->do_assertion('foo', 'bar');

Although this is how you'd use Test::Unit::Assertion::CodeRef
directly, it is more usually used indirectly via
Test::Unit::Test::assert, which instantiates a
Test::Unit::Assertion::CodeRef when passed a Coderef as its first
argument.

 view all matches for this distribution
 view release on metacpan -  search on metacpan

( run in 1.704 second using v1.00-cache-2.02-grep-82fe00e-cpan-d29e8ade9f55 )