added Mouse::Meta::TypeConstraint and use it. Mouse::Meta::Attribute->type_constraint...
[gitmo/Mouse.git] / t / 800_shikabased / 010-isa-or.t
CommitLineData
eec1bb49 1use strict;
2use warnings;
3use 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
14eval {
15 Foo->new( bar => +{} );
16};
108a7c18 17like($@, 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
19eval {
20 isa_ok(Foo->new( bar => undef ), 'Foo');
21};
22ok !$@, 'got an object 1';
23
24eval {
25 isa_ok(Foo->new( bar => 'foo' ), 'Foo');
26
27};
28ok !$@, 'got an object 2';
29
30
31my $f = Foo->new;
32eval {
33 $f->bar([]);
34};
684db121 35ok !$@, $@;
eec1bb49 36is $f->bar, 'Baz', 'bar is baz (coerce from ArrayRef)';
37
38eval {
39 $f->bar('hoge');
40};
41ok !$@;
42is $f->bar, 'hoge', 'bar is hoge';
43
44eval {
45 $f->bar(undef);
46};
47ok !$@;
48is $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
65my $foo = Bar->new( foo => 'aaa' );
66ok $foo, 'got an object 3';
67is $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 85eval { Funk->new( foo => 'aaa' ) };
eec1bb49 86like $@, qr/Attribute \(foo\) does not pass the type constraint because: Validation failed for 'Type3\|KLASS\|Undef' failed with value aaa/;
87
bcc5080b 88my $k = Funk->new;
eec1bb49 89ok $k, 'got an object 4';
90$k->foo(sub {});
91is $k->foo, 'Name', 'foo is Name';
92$k->foo(KLASS->new);
93isa_ok $k->foo, 'KLASS';
94$k->foo(undef);
95is $k->foo, undef, 'foo is undef';
96