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