TypeConstraint::Utils,.. now with find_or_create_type_constraint goodness
[gitmo/Moose.git] / t / 040_type_constraints / 005_util_type_coercion.t
CommitLineData
182134e8 1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
e90c03d0 6use Test::More tests => 14;
182134e8 7use Test::Exception;
8
9BEGIN {
10 use_ok('Moose::Util::TypeConstraints');
11}
12
13{
14 package HTTPHeader;
182134e8 15 use Moose;
16
17 has 'array' => (is => 'ro');
18 has 'hash' => (is => 'ro');
19}
20
21subtype Header =>
22 => as Object
23 => where { $_->isa('HTTPHeader') };
24
25coerce Header
d6e2d9a1 26 => from ArrayRef
27 => via { HTTPHeader->new(array => $_[0]) }
28 => from HashRef
29 => via { HTTPHeader->new(hash => $_[0]) };
81dc201f 30
31
32{
33 package Math::BigFloat;
34 sub new { bless { }, shift }; # not a moose class ;-)
35}
36
37subtype "Math::BigFloat"
38 => as "Math::BigFloat"
39 => where { 1 };
40
41coerce "Math::BigFloat"
42 => from Num
43 => via { Math::BigFloat->new( $_ ) };
44
182134e8 45
d9b40005 46Moose::Util::TypeConstraints->export_type_constraints_as_functions();
182134e8 47
48my $header = HTTPHeader->new();
49isa_ok($header, 'HTTPHeader');
50
51ok(Header($header), '... this passed the type test');
52ok(!Header([]), '... this did not pass the type test');
53ok(!Header({}), '... this did not pass the type test');
54
7c13858b 55my $coercion = find_type_constraint('Header')->coercion;
a27aa600 56isa_ok($coercion, 'Moose::Meta::TypeCoercion');
182134e8 57
e90c03d0 58{
a27aa600 59 my $coerced = $coercion->coerce([ 1, 2, 3 ]);
e90c03d0 60 isa_ok($coerced, 'HTTPHeader');
61
62 is_deeply(
63 $coerced->array(),
64 [ 1, 2, 3 ],
65 '... got the right array');
66 is($coerced->hash(), undef, '... nothing assigned to the hash');
67}
68
69{
a27aa600 70 my $coerced = $coercion->coerce({ one => 1, two => 2, three => 3 });
e90c03d0 71 isa_ok($coerced, 'HTTPHeader');
72
73 is_deeply(
74 $coerced->hash(),
75 { one => 1, two => 2, three => 3 },
76 '... got the right hash');
77 is($coerced->array(), undef, '... nothing assigned to the array');
78}
79
80{
81 my $scalar_ref = \(my $var);
a27aa600 82 my $coerced = $coercion->coerce($scalar_ref);
e90c03d0 83 is($coerced, $scalar_ref, '... got back what we put in');
84}
85
86{
a27aa600 87 my $coerced = $coercion->coerce("Foo");
e90c03d0 88 is($coerced, "Foo", '... got back what we put in');
89}
90