Commit | Line | Data |
eec1bb49 |
1 | use strict; |
2 | use warnings; |
3 | use Test::More tests => 18; |
4 | |
5 | { |
6 | package Foo; |
7 | use Mouse; |
3b46bd49 |
8 | use Mouse::Util::TypeConstraints; |
3fa6f35d |
9 | type Baz => where { defined($_) && $_ eq 'Baz' }; |
eec1bb49 |
10 | coerce Baz => from 'ArrayRef', via { 'Baz' }; |
11 | has 'bar' => ( is => 'rw', isa => 'Str | Baz | Undef', coerce => 1 ); |
12 | } |
13 | |
14 | eval { |
15 | Foo->new( bar => +{} ); |
16 | }; |
108a7c18 |
17 | like($@, qr/^Attribute \(bar\) does not pass the type constraint because: Validation failed for 'Str\|Baz\|Undef' failed with value HASH\(\w+\)/, 'type constraint and coercion failed'); |
eec1bb49 |
18 | |
19 | eval { |
20 | isa_ok(Foo->new( bar => undef ), 'Foo'); |
21 | }; |
22 | ok !$@, 'got an object 1'; |
23 | |
24 | eval { |
25 | isa_ok(Foo->new( bar => 'foo' ), 'Foo'); |
26 | |
27 | }; |
28 | ok !$@, 'got an object 2'; |
29 | |
30 | |
31 | my $f = Foo->new; |
32 | eval { |
33 | $f->bar([]); |
34 | }; |
684db121 |
35 | ok !$@, $@; |
eec1bb49 |
36 | is $f->bar, 'Baz', 'bar is baz (coerce from ArrayRef)'; |
37 | |
38 | eval { |
39 | $f->bar('hoge'); |
40 | }; |
41 | ok !$@; |
42 | is $f->bar, 'hoge', 'bar is hoge'; |
43 | |
44 | eval { |
45 | $f->bar(undef); |
46 | }; |
47 | ok !$@; |
48 | is $f->bar, undef, 'bar is undef'; |
49 | |
50 | |
51 | { |
52 | package Bar; |
53 | use Mouse; |
3b46bd49 |
54 | use Mouse::Util::TypeConstraints; |
eec1bb49 |
55 | |
3fa6f35d |
56 | type 'Type1' => where { defined($_) && $_ eq 'Name' }; |
eec1bb49 |
57 | coerce 'Type1', from 'Str', via { 'Names' }; |
58 | |
3fa6f35d |
59 | type 'Type2' => where { defined($_) && $_ eq 'Group' }; |
eec1bb49 |
60 | coerce 'Type2', from 'Str', via { 'Name' }; |
61 | |
62 | has 'foo' => ( is => 'rw', isa => 'Type1|Type2', coerce => 1 ); |
63 | } |
64 | |
65 | my $foo = Bar->new( foo => 'aaa' ); |
66 | ok $foo, 'got an object 3'; |
67 | is $foo->foo, 'Name', 'foo is Name'; |
68 | |
69 | |
70 | { |
71 | package KLASS; |
72 | sub new { bless {}, shift }; |
73 | } |
74 | { |
bcc5080b |
75 | package Funk; |
eec1bb49 |
76 | use Mouse; |
3b46bd49 |
77 | use Mouse::Util::TypeConstraints; |
eec1bb49 |
78 | |
3fa6f35d |
79 | type 'Type3' => where { defined($_) && $_ eq 'Name' }; |
eec1bb49 |
80 | coerce 'Type3', from 'CodeRef', via { 'Name' }; |
81 | |
82 | has 'foo' => ( is => 'rw', isa => 'Type3|KLASS|Undef', coerce => 1 ); |
83 | } |
84 | |
bcc5080b |
85 | eval { Funk->new( foo => 'aaa' ) }; |
eec1bb49 |
86 | like $@, qr/Attribute \(foo\) does not pass the type constraint because: Validation failed for 'Type3\|KLASS\|Undef' failed with value aaa/; |
87 | |
bcc5080b |
88 | my $k = Funk->new; |
eec1bb49 |
89 | ok $k, 'got an object 4'; |
90 | $k->foo(sub {}); |
91 | is $k->foo, 'Name', 'foo is Name'; |
92 | $k->foo(KLASS->new); |
93 | isa_ok $k->foo, 'KLASS'; |
94 | $k->foo(undef); |
95 | is $k->foo, undef, 'foo is undef'; |
96 | |