refactor curries usage
[gitmo/MooseX-AttributeHelpers.git] / t / 005_basic_list.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 24;
7 use Test::Exception;
8
9 BEGIN {
10     use_ok('MooseX::AttributeHelpers');   
11 }
12
13 {
14     package Stuff;
15     use Moose;
16
17     has '_options' => (
18         metaclass => 'Collection::List',
19         is        => 'ro',
20         isa       => 'ArrayRef[Int]',
21         init_arg  => 'options',
22         default   => sub { [] },
23         provides  => {
24             'count'    => 'num_options',
25             'empty'    => 'has_options',        
26             'map'      => 'map_options',
27             'grep'     => 'filter_options',
28             'find'     => 'find_option',
29             'elements' => 'options',
30             'join'     => 'join_options',
31         },
32         curries   => {
33             'grep'     => {less_than_five => [ sub { $_ < 5 } ]},
34             'map'      => {up_by_one      => [ sub { $_ + 1 } ]},
35             'join'     => {dashify        => [ '-' ]}
36         }
37     );
38 }
39
40 my $stuff = Stuff->new(options => [ 1 .. 10 ]);
41 isa_ok($stuff, 'Stuff');
42
43 can_ok($stuff, $_) for qw[
44     _options
45     num_options
46     has_options
47     map_options
48     filter_options
49     find_option
50     options
51     join_options
52 ];
53
54 is_deeply($stuff->_options, [1 .. 10], '... got options');
55
56 ok($stuff->has_options, '... we have options');
57 is($stuff->num_options, 10, '... got 2 options');
58
59 is_deeply(
60 [ $stuff->filter_options(sub { $_[0] % 2 == 0 }) ],
61 [ 2, 4, 6, 8, 10 ],
62 '... got the right filtered values'
63 );
64
65 is_deeply(
66 [ $stuff->map_options(sub { $_[0] * 2 }) ],
67 [ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ],
68 '... got the right mapped values'
69 );
70
71 is($stuff->find_option(sub { $_[0] % 2 == 0 }), 2, '.. found the right option');
72
73 is_deeply([ $stuff->options ], [1 .. 10], '... got the list of options');
74
75 is($stuff->join_options(':'), '1:2:3:4:5:6:7:8:9:10', '... joined the list of options by :');
76
77 # test the currying
78 is_deeply([ $stuff->less_than_five() ], [1 .. 4]);
79
80 is_deeply([ $stuff->up_by_one() ], [2 .. 11]);
81
82 is($stuff->dashify, '1-2-3-4-5-6-7-8-9-10');
83
84 ## test the meta
85
86 my $options = $stuff->meta->get_attribute('_options');
87 isa_ok($options, 'MooseX::AttributeHelpers::Collection::List');
88
89 is_deeply($options->provides, {
90     'map'      => 'map_options',
91     'grep'     => 'filter_options',
92     'find'     => 'find_option',
93     'count'    => 'num_options',
94     'empty'    => 'has_options',
95     'elements' => 'options',
96     'join'     => 'join_options',
97 }, '... got the right provies mapping');
98
99 is($options->type_constraint->type_parameter, 'Int', '... got the right container type');