More tweaking of t0m's doc changes
[gitmo/Moose.git] / t / 040_type_constraints / 005_util_type_coercion.t
CommitLineData
182134e8 1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
470b518a 6use Test::More tests => 24;
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
182134e8 31
d9b40005 32Moose::Util::TypeConstraints->export_type_constraints_as_functions();
182134e8 33
34my $header = HTTPHeader->new();
35isa_ok($header, 'HTTPHeader');
36
37ok(Header($header), '... this passed the type test');
38ok(!Header([]), '... this did not pass the type test');
39ok(!Header({}), '... this did not pass the type test');
40
470b518a 41my $anon_type = subtype Object => where { $_->isa('HTTPHeader') };
182134e8 42
470b518a 43lives_ok {
44 coerce $anon_type
45 => from ArrayRef
46 => via { HTTPHeader->new(array => $_[0]) }
47 => from HashRef
48 => via { HTTPHeader->new(hash => $_[0]) };
49} 'coercion of anonymous subtype succeeds';
e90c03d0 50
470b518a 51foreach my $coercion (
52 find_type_constraint('Header')->coercion,
53 $anon_type->coercion
54 ) {
e90c03d0 55
470b518a 56 my $coercion = find_type_constraint('Header')->coercion;
57 isa_ok($coercion, 'Moose::Meta::TypeCoercion');
e90c03d0 58
470b518a 59 {
60 my $coerced = $coercion->coerce([ 1, 2, 3 ]);
61 isa_ok($coerced, 'HTTPHeader');
62
63 is_deeply(
64 $coerced->array(),
65 [ 1, 2, 3 ],
66 '... got the right array');
67 is($coerced->hash(), undef, '... nothing assigned to the hash');
68 }
69
70 {
71 my $coerced = $coercion->coerce({ one => 1, two => 2, three => 3 });
72 isa_ok($coerced, 'HTTPHeader');
73
74 is_deeply(
75 $coerced->hash(),
76 { one => 1, two => 2, three => 3 },
77 '... got the right hash');
78 is($coerced->array(), undef, '... nothing assigned to the array');
79 }
80
81 {
82 my $scalar_ref = \(my $var);
83 my $coerced = $coercion->coerce($scalar_ref);
84 is($coerced, $scalar_ref, '... got back what we put in');
85 }
86
87 {
88 my $coerced = $coercion->coerce("Foo");
89 is($coerced, "Foo", '... got back what we put in');
90 }
e90c03d0 91}