refactoring the parameterized type constraints
[gitmo/Moose.git] / t / 040_type_constraints / 018_custom_parameterized_types.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 21;
7 use Test::Exception;
8
9 BEGIN {
10     use_ok("Moose::Util::TypeConstraints");
11     use_ok('Moose::Meta::TypeConstraint::Parameterized');
12 }
13
14 lives_ok {
15     subtype 'AlphaKeyHash' => as 'HashRef'
16         => where {
17             # no keys match non-alpha
18             (grep { /[^a-zA-Z]/ } keys %$_) == 0
19         };
20 } '... created the subtype special okay';
21
22 lives_ok {
23     subtype 'Trihash' => as 'AlphaKeyHash'
24         => where {
25             keys(%$_) == 3
26         };
27 } '... created the subtype special okay';
28
29 lives_ok {
30     subtype 'Noncon' => as 'Item';
31 } '... created the subtype special okay';
32
33 {
34     my $t = find_type_constraint('AlphaKeyHash');
35     isa_ok($t, 'Moose::Meta::TypeConstraint');
36
37     is($t->name, 'AlphaKeyHash', '... name is correct');
38
39     my $p = $t->parent;
40     isa_ok($p, 'Moose::Meta::TypeConstraint');
41
42     is($p->name, 'HashRef', '... parent name is correct');
43
44     ok($t->check({ one => 1, two => 2 }), '... validated it correctly');
45     ok(!$t->check({ one1 => 1, two2 => 2 }), '... validated it correctly');
46 }
47
48 my $hoi = Moose::Util::TypeConstraints::find_or_create_type_constraint('AlphaKeyHash[Int]');
49
50 ok($hoi->check({ one => 1, two => 2 }), '... validated it correctly');
51 ok(!$hoi->check({ one1 => 1, two2 => 2 }), '... validated it correctly');
52 ok(!$hoi->check({ one => 'uno', two => 'dos' }), '... validated it correctly');
53 ok(!$hoi->check({ one1 => 'un', two2 => 'deux' }), '... validated it correctly');
54
55 my $th = Moose::Util::TypeConstraints::find_or_create_type_constraint('Trihash[Bool]');
56
57 ok(!$th->check({ one => 1, two => 1 }), '... validated it correctly');
58 ok($th->check({ one => 1, two => 0, three => 1 }), '... validated it correctly');
59 ok(!$th->check({ one => 1, two => 2, three => 1 }), '... validated it correctly');
60 ok(!$th->check({foo1 => 1, bar2 => 0, baz3 => 1}), '... validated it correctly');
61
62 dies_ok {
63     Moose::Meta::TypeConstraint::Parameterized->new(
64         name           => 'Str[Int]',
65         parent         => find_type_constraint('Str'),
66         type_parameter => find_type_constraint('Int'),
67     );
68 } 'non-containers cannot be parameterized';
69
70 dies_ok {
71     Moose::Meta::TypeConstraint::Parameterized->new(
72         name           => 'Noncon[Int]',
73         parent         => find_type_constraint('Noncon'),
74         type_parameter => find_type_constraint('Int'),
75     );
76 } 'non-containers cannot be parameterized';
77