Introduce TypeConstraint::Role, and add find_or_create_{isa,does}_type_constraint...
[gitmo/Moose.git] / t / 040_type_constraints / 021_maybe_type_constraint.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 19;
7 use Test::Exception;
8
9 BEGIN {
10     use_ok('Moose');
11     use_ok('Moose::Util::TypeConstraints');
12 }
13
14 my $type = Moose::Util::TypeConstraints::find_or_parse_type_constraint('Maybe[Int]');
15 isa_ok($type, 'Moose::Meta::TypeConstraint');
16 isa_ok($type, 'Moose::Meta::TypeConstraint::Parameterized');
17
18 ok( $type->equals($type), "equals self" );
19 ok( !$type->equals($type->parent), "not equal to parent" );
20 ok( !$type->equals(find_type_constraint("Maybe")), "not equal to Maybe" );
21 ok( $type->parent->equals(find_type_constraint("Maybe")), "parent is Maybe" );
22 ok( $type->equals( Moose::Meta::TypeConstraint::Parameterized->new( name => "__ANON__", parent => find_type_constraint("Maybe"), type_parameter => find_type_constraint("Int") ) ), "equal to clone" );
23 ok( !$type->equals( Moose::Meta::TypeConstraint::Parameterized->new( name => "__ANON__", parent => find_type_constraint("Maybe"), type_parameter => find_type_constraint("Str") ) ), "not equal to clone with diff param" );
24 ok( !$type->equals( Moose::Util::TypeConstraints::find_or_parse_type_constraint('Maybe[Str]') ), "not equal to declarative version of diff param" );
25
26 ok($type->check(10), '... checked type correctly (pass)');
27 ok($type->check(undef), '... checked type correctly (pass)');
28 ok(!$type->check('Hello World'), '... checked type correctly (fail)');
29 ok(!$type->check([]), '... checked type correctly (fail)');
30
31 {
32     package Foo;
33     use Moose;
34     
35     has 'bar' => (is => 'rw', isa => 'Maybe[ArrayRef]', required => 1);    
36 }
37
38 lives_ok {
39     Foo->new(bar => []);
40 } '... it worked!';
41
42 lives_ok {
43     Foo->new(bar => undef);
44 } '... it worked!';
45
46 dies_ok {
47     Foo->new(bar => 100);
48 } '... failed the type check';
49
50 dies_ok {
51     Foo->new(bar => 'hello world');
52 } '... failed the type check';
53