3 use Test::More tests => 18;
8 use Mouse::Util::TypeConstraints;
9 type Baz => where { defined($_) && $_ eq 'Baz' };
11 coerce Baz => from 'ArrayRef', via { 'Baz' };
13 has 'bar' => ( is => 'rw', isa => 'Str | Baz | Undef', coerce => 1 );
17 Foo->new( bar => +{} );
19 like($@, qr/^Attribute \(bar\) does not pass the type constraint because: Validation failed for 'Baz\|Str\|Undef' failed with value HASH\(\w+\)/, 'type constraint and coercion failed')
23 isa_ok(Foo->new( bar => undef ), 'Foo');
25 ok !$@, 'got an object 1';
28 isa_ok(Foo->new( bar => 'foo' ), 'Foo');
31 ok !$@, 'got an object 2';
39 is $f->bar, 'Baz', 'bar is baz (coerce from ArrayRef)';
45 is $f->bar, 'hoge', 'bar is hoge';
51 is $f->bar, undef, 'bar is undef';
57 use Mouse::Util::TypeConstraints;
59 type 'Type1' => where { defined($_) && $_ eq 'Name' };
60 coerce 'Type1', from 'Str', via { 'Names' };
62 type 'Type2' => where { defined($_) && $_ eq 'Group' };
63 coerce 'Type2', from 'Str', via { 'Name' };
65 has 'foo' => ( is => 'rw', isa => 'Type1|Type2', coerce => 1 );
68 my $foo = Bar->new( foo => 'aaa' );
69 ok $foo, 'got an object 3';
70 is $foo->foo, 'Name', 'foo is Name';
80 use Mouse::Util::TypeConstraints;
82 type 'Type3' => where { defined($_) && $_ eq 'Name' };
83 coerce 'Type3', from 'CodeRef', via { 'Name' };
85 has 'foo' => ( is => 'rw', isa => 'Type3|KLASS|Undef', coerce => 1 );
88 eval { Funk->new( foo => 'aaa' ) };
89 like $@, qr/Attribute \(foo\) does not pass the type constraint because: Validation failed for 'KLASS\|Type3\|Undef' failed with value aaa/;
92 ok $k, 'got an object 4';
94 is $k->foo, 'Name', 'foo is Name';
96 isa_ok $k->foo, 'KLASS';
98 is $k->foo, undef, 'foo is undef';