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