got working prototype, but relies on uncommited changes to Moose::Meta::TypeConstraint
[gitmo/MooseX-Types-Structured.git] / t / 09-optional.t
CommitLineData
fbb43338 1use strict;
2use warnings;
3
4use Test::More tests=>15;
5use Moose::Util::TypeConstraints;
6use Moose::Meta::TypeConstraint::Parameterizable;
968cdea9 7
b454ba9e 8use Data::Dump qw/dump/;
fbb43338 9
1e60caec 10## Sketch for how this could work
968cdea9 11
fbb43338 12ok 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 {
968cdea9 18 my ($type_parameter, @args) = @_;
19 my $check = $type_parameter->_compiled_type_constraint();
fbb43338 20 return sub {
968cdea9 21 my (@args) = @_;
fbb43338 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
1e60caec 33Moose::Util::TypeConstraints::register_type_constraint($Optional);
fbb43338 34Moose::Util::TypeConstraints::add_parameterizable_type($Optional);
1e60caec 35## END SKETCH
fbb43338 36
37isa_ok $Optional, 'Moose::Meta::TypeConstraint::Parameterizable';
38
1e60caec 39ok my $int = Moose::Util::TypeConstraints::find_or_parse_type_constraint('Int')
40 => 'Got Int';
fbb43338 41
1e60caec 42ok my $arrayref = Moose::Util::TypeConstraints::find_or_parse_type_constraint('ArrayRef[Int]')
43 => 'Got ArrayRef[Int]';
fbb43338 44
1e60caec 45ok my $Optional_Int = $Optional->parameterize($int), 'Parameterized Int';
46ok my $Optional_ArrayRef = $Optional->parameterize($arrayref), 'Parameterized ArrayRef';
fbb43338 47
48ok $Optional_Int->check() => 'Optional is allowed to not exist';
b454ba9e 49
fbb43338 50ok !$Optional_Int->check(undef) => 'Optional is NOT allowed to be undef';
51ok $Optional_Int->check(199) => 'Correctly validates 199';
52ok !$Optional_Int->check("a") => 'Correctly fails "a"';
53
54ok $Optional_ArrayRef->check() => 'Optional is allowed to not exist';
55ok !$Optional_ArrayRef->check(undef) => 'Optional is NOT allowed to be undef';
56ok $Optional_ArrayRef->check([1,2,3]) => 'Correctly validates [1,2,3]';
57ok !$Optional_ArrayRef->check("a") => 'Correctly fails "a"';
58ok !$Optional_ArrayRef->check(["a","b"]) => 'Correctly fails ["a","b"]';