Merge branch 'master' into attribute_helpers
[gitmo/Moose.git] / t / 070_attribute_helpers / 100_collection_with_roles.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 29;
7
8 BEGIN {
9     use_ok('Moose::AttributeHelpers');
10 }
11
12 package Subject;
13
14 use Moose::Role;
15 use Moose::AttributeHelpers;
16
17 has observers => (
18     traits     => [ 'Collection::Array' ],
19     is         => 'ro',
20     isa        => 'ArrayRef[Observer]',
21     auto_deref => 1,
22     default    => sub { [] },
23     handles    => {
24         'add_observer'    => 'push',
25         'count_observers' => 'count',
26     },
27 );
28
29 sub notify {
30     my ($self) = @_;
31     foreach my $observer ( $self->observers() ) {
32         $observer->update($self);
33     }
34 }
35
36 ###############################################################################
37
38 package Observer;
39
40 use Moose::Role;
41
42 requires 'update';
43
44 ###############################################################################
45
46 package Counter;
47
48 use Moose;
49 use Moose::AttributeHelpers;
50
51 with 'Subject';
52
53 has count => (
54     traits    => [ 'Counter' ],
55     is        => 'ro',
56     isa       => 'Int',
57     default   => 0,
58     handles  => {
59         inc_counter => 'inc',
60         dec_counter => 'dec',
61     },
62 );
63
64 after qw(inc_counter dec_counter) => sub {
65     my ($self) = @_;
66     $self->notify();
67 };
68
69 ###############################################################################
70
71 package Display;
72
73 use Test::More;
74
75 use Moose;
76
77 with 'Observer';
78
79 sub update {
80     my ( $self, $subject ) = @_;
81     like $subject->count, qr{^-?\d+$}, 'Observed number ' . $subject->count;
82 }
83
84 ###############################################################################
85
86 package main;
87
88 my $count = Counter->new();
89
90 ok($count->can('add_observer'), 'add_observer method added');
91
92 ok($count->can('count_observers'), 'count_observers method added');
93
94 ok($count->can('inc_counter'), 'inc_counter method added');
95
96 ok($count->can('dec_counter'), 'dec_counter method added');
97
98 $count->add_observer( Display->new() );
99
100 is($count->count_observers, 1, 'Only one observer');
101
102 is($count->count, 0, 'Default to zero');
103
104 $count->inc_counter;
105
106 is($count->count, 1, 'Increment to one ');
107
108 $count->inc_counter for (1 .. 6);
109
110 is($count->count, 7, 'Increment up to seven');
111
112 $count->dec_counter;
113
114 is($count->count, 6, 'Decrement to 6');
115
116 $count->dec_counter for (1 .. 5);
117
118 is($count->count, 1, 'Decrement to 1');
119
120 $count->dec_counter for (1 .. 2);
121
122 is($count->count, -1, 'Negative numbers');
123
124 $count->inc_counter;
125
126 is($count->count, 0, 'Back to zero');