got working prototype, but relies on uncommited changes to Moose::Meta::TypeConstraint
[gitmo/MooseX-Types-Structured.git] / t / 09-optional.t
1 use strict;
2 use warnings;
3
4 use Test::More tests=>15;
5 use Moose::Util::TypeConstraints;
6 use Moose::Meta::TypeConstraint::Parameterizable;
7
8 use Data::Dump qw/dump/;
9
10 ## Sketch for how this could work
11
12 ok my $Optional = Moose::Meta::TypeConstraint::Parameterizable->new(
13         name => 'Optional',
14         package_defined_in => __PACKAGE__,
15         parent => find_type_constraint('Item'),
16         constraint => sub { 1 },
17         constraint_generator => sub {
18                 my ($type_parameter, @args) = @_;
19                 my $check = $type_parameter->_compiled_type_constraint();
20                 return sub {
21                         my (@args) = @_;                        
22                         if(exists($args[0])) {
23                                 ## If it exists, we need to validate it
24                                 $check->($args[0]);
25                         } else {
26                                 ## But it's is okay if the value doesn't exists
27                                 return 1;
28                         }
29                 }
30         }
31 );
32
33 Moose::Util::TypeConstraints::register_type_constraint($Optional);
34 Moose::Util::TypeConstraints::add_parameterizable_type($Optional);
35 ## END SKETCH
36
37 isa_ok $Optional, 'Moose::Meta::TypeConstraint::Parameterizable';
38
39 ok my $int = Moose::Util::TypeConstraints::find_or_parse_type_constraint('Int')
40  => 'Got Int';
41
42 ok my $arrayref = Moose::Util::TypeConstraints::find_or_parse_type_constraint('ArrayRef[Int]')
43  => 'Got ArrayRef[Int]';
44
45 ok my $Optional_Int = $Optional->parameterize($int), 'Parameterized Int';
46 ok my $Optional_ArrayRef = $Optional->parameterize($arrayref), 'Parameterized ArrayRef';
47
48 ok $Optional_Int->check() => 'Optional is allowed to not exist';
49
50 ok !$Optional_Int->check(undef) => 'Optional is NOT allowed to be undef';
51 ok $Optional_Int->check(199) => 'Correctly validates 199';
52 ok !$Optional_Int->check("a") => 'Correctly fails "a"';
53
54 ok $Optional_ArrayRef->check() => 'Optional is allowed to not exist';
55 ok !$Optional_ArrayRef->check(undef) => 'Optional is NOT allowed to be undef';
56 ok $Optional_ArrayRef->check([1,2,3]) => 'Correctly validates [1,2,3]';
57 ok !$Optional_ArrayRef->check("a") => 'Correctly fails "a"';
58 ok !$Optional_ArrayRef->check(["a","b"]) => 'Correctly fails ["a","b"]';