Test for narrowing "Str | Int | ArrayRef" down to "Int | ArrayRef" too
[gitmo/Moose.git] / t / 030_roles / 017_extending_role_attrs.t
CommitLineData
8d62bf6d 1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
68e9fbfc 6use Test::More tests => 17;
8d62bf6d 7use Test::Exception;
8
9BEGIN {
10 use_ok('Moose');
11}
12
13=pod
14
15This basically just makes sure that using +name
dd14f8e8 16on role attributes works right.
8d62bf6d 17
18=cut
19
20{
21 package Foo::Role;
22 use Moose::Role;
23
24 has 'bar' => (
25 is => 'rw',
26 isa => 'Int',
27 default => sub { 10 },
28 );
29
30 package Foo;
31 use Moose;
32
33 with 'Foo::Role';
34
35 ::lives_ok {
36 has '+bar' => (default => sub { 100 });
37 } '... extended the attribute successfully';
38}
39
40my $foo = Foo->new;
41isa_ok($foo, 'Foo');
42
43is($foo->bar, 100, '... got the extended attribute');
44
dd14f8e8 45{
46 package Bar::Role;
47 use Moose::Role;
48
49 has 'foo' => (
50 is => 'rw',
51 isa => 'Str | Int',
52 );
53
54 package Bar;
55 use Moose;
56
57 with 'Bar::Role';
58
59 ::lives_ok {
60 has '+foo' => (
61 isa => 'Int',
62 )
63 } "... narrowed the role's type constraint successfully";
64}
65
66
67my $bar = Bar->new(foo => 42);
68isa_ok($bar, 'Bar');
69is($bar->foo, 42, '... got the extended attribute');
70$bar->foo(100);
71is($bar->foo, 100, "... can change the attribute's value to an Int");
72
73throws_ok { $bar->foo("baz") } qr/^Attribute \(foo\) does not pass the type constraint because: Validation failed for 'Int' failed with value baz at /;
74is($bar->foo, 100, "... still has the old Int value");
75
68e9fbfc 76{
77 package Baz::Role;
78 use Moose::Role;
79
80 has 'baz' => (
81 is => 'rw',
82 isa => 'Str | Int | ArrayRef',
83 );
84
85 package Baz;
86 use Moose;
87
88 with 'Baz::Role';
89
90 ::lives_ok {
91 has '+baz' => (
92 isa => 'Int | ArrayRef',
93 )
94 } "... narrowed the role's type constraint successfully";
95}
96
97
98my $baz = Baz->new(baz => 99);
99isa_ok($baz, 'Baz');
100is($baz->baz, 99, '... got the extended attribute');
101$baz->baz(100);
102is($baz->baz, 100, "... can change the attribute's value to an Int");
103$baz->baz(["hi"]);
104is_deeply($baz->baz, ["hi"], "... can change the attribute's value to an ArrayRef");
105
106throws_ok { $baz->baz("quux") } qr/^Attribute \(baz\) does not pass the type constraint because: Validation failed for 'Int \| ArrayRef' failed with value quux at /;
107is_deeply($baz->baz, ["hi"], "... still has the old ArrayRef value");
108