From: Ricardo SIGNES Date: Fri, 7 Aug 2009 18:28:42 +0000 (-0400) Subject: assert_valid to use constraints for assertion X-Git-Tag: 0.89~17 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=c24269b37a781e0358c3682e8717cfd539269550;p=gitmo%2FMoose.git assert_valid to use constraints for assertion --- diff --git a/lib/Moose/Meta/TypeConstraint.pm b/lib/Moose/Meta/TypeConstraint.pm index 3ab7a1e..298656f 100644 --- a/lib/Moose/Meta/TypeConstraint.pm +++ b/lib/Moose/Meta/TypeConstraint.pm @@ -104,6 +104,16 @@ sub validate { } } +sub assert_valid { + my ($self, $value) = @_; + + my $error = $self->validate($value); + return 1 if ! defined $error; + + require Moose; + Moose->throw_error($error); +} + sub get_message { my ($self, $value) = @_; if (my $msg = $self->message) { diff --git a/t/040_type_constraints/010_misc_type_tests.t b/t/040_type_constraints/010_misc_type_tests.t index 866c920..2cf0985 100644 --- a/t/040_type_constraints/010_misc_type_tests.t +++ b/t/040_type_constraints/010_misc_type_tests.t @@ -3,7 +3,7 @@ use strict; use warnings; -use Test::More tests => 8; +use Test::More tests => 11; use Test::Exception; BEGIN { @@ -47,3 +47,21 @@ ok $subtype1 => 'made a subtype from our type object'; my $subtype2 = subtype 'New2' => as $subtype1; ok $subtype2 => 'made a subtype of our subtype'; + +# assert_valid + +{ + my $type = find_type_constraint('Num'); + + my $ok_1 = eval { $type->assert_valid(1); }; + ok($ok_1, "we can assert_valid that 1 is of type $type"); + + my $ok_2 = eval { $type->assert_valid('foo'); }; + my $error = $@; + ok(! $ok_2, "'foo' is not of type $type"); + like( + $error, + qr{validation failed for .\Q$type\E.}i, + "correct error thrown" + ); +}