bump version
[gitmo/Moo.git] / t / accessor-roles.t
1 use strictures 1;
2 use Test::More;
3 use Test::Fatal;
4 use Sub::Quote;
5
6 {
7   package One; use Moo;
8   has one => (is => 'ro', default => sub { 'one' });
9
10   package One::P1; use Moo::Role;
11   has two => (is => 'ro', default => sub { 'two' });
12
13   package One::P2; use Moo::Role;
14   has three => (is => 'ro', default => sub { 'three' });
15   has four => (is => 'ro', lazy => 1, default => sub { 'four' }, predicate => 1);
16
17   package One::P3; use Moo::Role;
18   has '+three' => (is => 'ro', default => sub { 'three' });
19 }
20
21 my $combined = Moo::Role->create_class_with_roles('One', qw(One::P1 One::P2));
22 isa_ok $combined, "One";
23 ok $combined->does($_), "Does $_" for qw(One::P1 One::P2);
24
25 my $c = $combined->new;
26 is $c->one, "one",     "attr default set from class";
27 is $c->two, "two",     "attr default set from role";
28 is $c->three, "three", "attr default set from role";
29
30 {
31   package Deux; use Moo; with 'One::P1';
32   ::like(
33     ::exception { has two => (is => 'ro', default => sub { 'II' }); },
34     qr{^You cannot overwrite a locally defined method \(two\) with a reader},
35     'overwriting accesssors with roles fails'
36   );
37 }
38
39 {
40   package Two; use Moo; with 'One::P1';
41   has '+two' => (is => 'ro', default => sub { 'II' });
42 }
43
44 is(Two->new->two, 'II', "overwriting accessors using +attr works");
45
46 my $o = One->new;
47 Moo::Role->apply_roles_to_object($o, 'One::P2');
48 is($o->three, 'three', 'attr default set from role applied to object');
49 ok(!$o->has_four, 'lazy attr default not set on apply');
50
51 $o = $combined->new(three => '3');
52 Moo::Role->apply_roles_to_object($o, 'One::P3');
53 is($o->three, '3', 'attr default not used when already set when role applied to object');
54
55 done_testing;