more type system hacking and tests
[gitmo/Moose.git] / t / 040_type_constraints / 012_container_type_coercion.t
CommitLineData
b17a3035 1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
6use Test::More tests => 10;
7use Test::Exception;
8
9BEGIN {
10 use_ok('Moose::Util::TypeConstraints');
11 use_ok('Moose::Meta::TypeConstraint::Container');
12}
13
14my $r = Moose::Util::TypeConstraints->_get_type_constraint_registry;
15
16# Array of Ints
17
18my $array_of_ints = Moose::Meta::TypeConstraint::Container->new(
19 name => 'ArrayRef[Int]',
20 parent => find_type_constraint('ArrayRef'),
21 container_type => find_type_constraint('Int'),
22);
23isa_ok($array_of_ints, 'Moose::Meta::TypeConstraint::Container');
24isa_ok($array_of_ints, 'Moose::Meta::TypeConstraint');
25
26$r->add_type_constraint($array_of_ints);
27
28is(find_type_constraint('ArrayRef[Int]'), $array_of_ints, '... found the type we just added');
29
30# Hash of Ints
31
32my $hash_of_ints = Moose::Meta::TypeConstraint::Container->new(
33 name => 'HashRef[Int]',
34 parent => find_type_constraint('HashRef'),
35 container_type => find_type_constraint('Int'),
36);
37isa_ok($hash_of_ints, 'Moose::Meta::TypeConstraint::Container');
38isa_ok($hash_of_ints, 'Moose::Meta::TypeConstraint');
39
40$r->add_type_constraint($hash_of_ints);
41
42is(find_type_constraint('HashRef[Int]'), $hash_of_ints, '... found the type we just added');
43
44## now attempt a coercion
45
46{
47 package Foo;
48 use Moose;
49 use Moose::Util::TypeConstraints;
50
51 coerce 'ArrayRef[Int]'
52 => from 'HashRef[Int]'
53 => via { [ values %$_ ] };
54
55 has 'bar' => (
56 is => 'ro',
57 isa => 'ArrayRef[Int]',
58 coerce => 1,
59 );
60
61}
62
63my $foo = Foo->new(bar => { one => 1, two => 2, three => 3 });
64isa_ok($foo, 'Foo');
65
66is_deeply([ sort @{$foo->bar} ], [ 1, 2, 3 ], '... our coercion worked!');
67
68