added another example test to show more useful functionality
[gitmo/MooseX-Dependent.git] / t / 02-depending.t
1 use Test::More tests=>15; {
2     
3     use strict;
4     use warnings;
5     
6     use Test::Exception;
7     use MooseX::Types::Dependent qw(Depending);
8         use MooseX::Types::Moose qw(Int Str Object ArrayRef HashRef Maybe);
9         use MooseX::Types -declare => [qw(
10         IntGreaterThanInt
11         UniqueInt
12     )];
13     
14     ## The dependent value must exceed the constraining value
15     subtype IntGreaterThanInt,
16       as Depending[
17         Int,
18         sub {
19                         my ($dependent_val, $constraining_val) = @_;
20                         return ($dependent_val > $constraining_val) ? 1:undef;
21         },
22         Int,
23       ];
24
25         isa_ok IntGreaterThanInt, 'MooseX::Meta::TypeConstraint::Dependent';
26         ok !IntGreaterThanInt->check(['a',10]), "Fails, 'a' is not an Int.";
27         ok !IntGreaterThanInt->check([5,'b']), "Fails, 'b' is not an Int either.";
28         ok !IntGreaterThanInt->check({4,1}), "Fails, since this isn't an arrayref";
29         ok !IntGreaterThanInt->check([5,10]), "Fails, 5 is less than 10";
30         ok IntGreaterThanInt->check([11,6]), "Success, 11 is greater than 6.";
31         ok IntGreaterThanInt->check([12,1]), "Success, 12 is greater than1.";
32         ok IntGreaterThanInt->check([0,-10]), "Success, 0 is greater than -10.";
33     
34     ## The dependent value cannot exist in the constraining arrayref
35     subtype UniqueInt,
36       as Depending[
37         Int,
38         sub {
39             my ($dependent_int, $constraining_arrayref) = @_;
40             (grep { $_ == $dependent_int} @$constraining_arrayref) ? 0:1
41         },
42         ArrayRef[Int],
43       ];
44       
45     isa_ok UniqueInt, 'MooseX::Meta::TypeConstraint::Dependent';
46     ok !UniqueInt->check(['a',[1,2,3]]), '"a" not an Int';
47     ok !UniqueInt->check([1,['b','c']]), '"b","c" not an arrayref';    
48     ok !UniqueInt->check([1,[1,2,3]]), 'not unique in set';
49     ok !UniqueInt->check([10,[1,10,15]]), 'not unique in set';
50     ok UniqueInt->check([2,[3..6]]), 'PASS unique in set';
51     ok UniqueInt->check([3,[100..110]]), 'PASS unique in set';    
52 }