closer to the sketch actually working
[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 use Moose;
8
9 ## Sketch for how this could work
10 ok my $Optional = Moose::Meta::TypeConstraint::Parameterizable->new(
11         name => 'Optional',
12         package_defined_in => __PACKAGE__,
13         parent => find_type_constraint('Item'),
14         constraint => sub { 1 },
15         constraint_generator => sub {
16                 my $type_parameter = shift;
17                 my $check = $type_parameter->_compiled_type_constraint;
18                 return sub {
19                         my (@args) = @_;
20                         if(exists($args[0])) {
21                                 ## If it exists, we need to validate it
22                                 $check->($args[0]);
23                         } else {
24                                 ## But it's is okay if the value doesn't exists
25                                 return 1;
26                         }
27                 }
28         }
29 );
30
31 Moose::Util::TypeConstraints::register_type_constraint($Optional);
32 Moose::Util::TypeConstraints::add_parameterizable_type($Optional);
33 ## END SKETCH
34
35 isa_ok $Optional, 'Moose::Meta::TypeConstraint::Parameterizable';
36
37 ok my $int = Moose::Util::TypeConstraints::find_or_parse_type_constraint('Int')
38  => 'Got Int';
39
40 ok my $arrayref = Moose::Util::TypeConstraints::find_or_parse_type_constraint('ArrayRef[Int]')
41  => 'Got ArrayRef[Int]';
42
43 ok my $Optional_Int = $Optional->parameterize($int), 'Parameterized Int';
44 ok my $Optional_ArrayRef = $Optional->parameterize($arrayref), 'Parameterized ArrayRef';
45
46 ok $Optional_Int->check() => 'Optional is allowed to not exist';
47 ok !$Optional_Int->check(undef) => 'Optional is NOT allowed to be undef';
48 ok $Optional_Int->check(199) => 'Correctly validates 199';
49 ok !$Optional_Int->check("a") => 'Correctly fails "a"';
50
51 ok $Optional_ArrayRef->check() => 'Optional is allowed to not exist';
52 ok !$Optional_ArrayRef->check(undef) => 'Optional is NOT allowed to be undef';
53 ok $Optional_ArrayRef->check([1,2,3]) => 'Correctly validates [1,2,3]';
54 ok !$Optional_ArrayRef->check("a") => 'Correctly fails "a"';
55 ok !$Optional_ArrayRef->check(["a","b"]) => 'Correctly fails ["a","b"]';