3 use Test::More tests => 18;
8 use Mouse::Util::TypeConstraints;
9 type Baz => where { defined($_) && $_ eq 'Baz' };
10 coerce Baz => from 'ArrayRef', via { 'Baz' };
11 has 'bar' => ( is => 'rw', isa => 'Str | Baz | Undef', coerce => 1 );
15 Foo->new( bar => +{} );
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');
20 isa_ok(Foo->new( bar => undef ), 'Foo');
22 ok !$@, 'got an object 1';
25 isa_ok(Foo->new( bar => 'foo' ), 'Foo');
28 ok !$@, 'got an object 2';
36 is $f->bar, 'Baz', 'bar is baz (coerce from ArrayRef)';
42 is $f->bar, 'hoge', 'bar is hoge';
48 is $f->bar, undef, 'bar is undef';
54 use Mouse::Util::TypeConstraints;
56 type 'Type1' => where { defined($_) && $_ eq 'Name' };
57 coerce 'Type1', from 'Str', via { 'Names' };
59 type 'Type2' => where { defined($_) && $_ eq 'Group' };
60 coerce 'Type2', from 'Str', via { 'Name' };
62 has 'foo' => ( is => 'rw', isa => 'Type1|Type2', coerce => 1 );
65 my $foo = Bar->new( foo => 'aaa' );
66 ok $foo, 'got an object 3';
67 is $foo->foo, 'Name', 'foo is Name';
72 sub new { bless {}, shift };
77 use Mouse::Util::TypeConstraints;
79 type 'Type3' => where { defined($_) && $_ eq 'Name' };
80 coerce 'Type3', from 'CodeRef', via { 'Name' };
82 has 'foo' => ( is => 'rw', isa => 'Type3|KLASS|Undef', coerce => 1 );
85 eval { Funk->new( foo => 'aaa' ) };
86 like $@, qr/Attribute \(foo\) does not pass the type constraint because: Validation failed for 'Type3\|KLASS\|Undef' failed with value aaa/;
89 ok $k, 'got an object 4';
91 is $k->foo, 'Name', 'foo is Name';
93 isa_ok $k->foo, 'KLASS';
95 is $k->foo, undef, 'foo is undef';