Finish renaming Mouse::TypeRegistry to Mouse::Util::TypeConstraints
[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;
eec1bb49 9 subtype Baz => where { defined($_) && $_ eq 'Baz' };
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};
17ok $@, 'not got an object';
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};
35ok !$@;
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
56 subtype 'Type1' => where { defined($_) && $_ eq 'Name' };
57 coerce 'Type1', from 'Str', via { 'Names' };
58
59 subtype 'Type2' => where { defined($_) && $_ eq 'Group' };
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{
75 package Baz;
76 use Mouse;
3b46bd49 77 use Mouse::Util::TypeConstraints;
eec1bb49 78
79 subtype 'Type3' => where { defined($_) && $_ eq 'Name' };
80 coerce 'Type3', from 'CodeRef', via { 'Name' };
81
82 has 'foo' => ( is => 'rw', isa => 'Type3|KLASS|Undef', coerce => 1 );
83}
84
85eval { Baz->new( foo => 'aaa' ) };
86like $@, qr/Attribute \(foo\) does not pass the type constraint because: Validation failed for 'Type3\|KLASS\|Undef' failed with value aaa/;
87
88my $k = Baz->new;
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