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