Add each_value to scalar. Also add tests for the behaviour of setting both $_ and...
[gitmo/Moose-Autobox.git] / t / 010_each.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 17;
7
8 require_ok('Moose::Autobox');
9
10 use Moose::Autobox;
11
12 {
13   my %hash = (
14     a => 1,
15     b => 2,
16     c => 3,
17   );
18
19   my $href = { %hash };
20
21   is_deeply($href, \%hash, "sanity check to start");
22
23   my (@keys, @keys2);
24   $href->each_key(sub { push @keys, $_ });
25   is_deeply([ sort @keys ], [ sort keys %hash ], 'keys found via each_key in $_');
26   $href->each_key(sub { push @keys2, $_[0] });
27   is_deeply([ sort @keys2 ], [ sort keys %hash ], 'keys found via each_key in $_[0]');
28
29   my (@values, @values2);
30   $href->each_value(sub { push @values, $_ });
31   is_deeply([ sort @values ], [ sort values %hash ], 'values via each_values in $_');
32   $href->each_value(sub { push @values2, $_[0] });
33   is_deeply([ sort @values2 ], [ sort values %hash ], 'values via each_values in $_[0]');
34
35   $href->each_value(sub { $_++ });
36   is($href->{a}, 2, "we can ++ values directly");
37
38   $href->each_key(sub { $_ = "$_$_" });
39   ok(! exists $href->{aa}, "we cannot alter keys directly");
40 }
41
42 {
43   my @array = qw(foo bar baz);
44
45   my $aref = [ @array ];
46
47   is_deeply($aref, \@array, "sanity check to start");
48
49   my (@keys, @keys2);
50   $aref->each_key(sub { push @keys, $_ });
51   is_deeply([ @keys ], [ 0, 1, 2 ], 'keys found via each_key in $_');
52   $aref->each_key(sub { push @keys2, $_[0] });
53   is_deeply([ @keys2 ], [ 0, 1, 2 ], 'keys found via each_key in $_[0]');
54
55   my (@values, @values2);
56   $aref->each_value(sub { push @values, $_ });
57   is_deeply([ @values ], [ @array ], 'values via each_values in $_');
58   $aref->each_value(sub { push @values2, $_[0] });
59   is_deeply([ @values2 ], [ @array ], 'values via each_values in $_[0]');
60
61   $aref->each_value(sub { $_ = uc });
62   is($aref->[0], 'FOO', "we can alter values directly");
63
64   $aref->each_key(sub { $_ = $_ + 1 });
65   ok(! $aref->[3], "we cannot alter keys directly");
66 }
67
68 {
69     my $string = 'foo';
70     my @values;
71     $string->each_value(sub { push @values, $_ });
72     is_deeply( [@values], [$string], 'each_values for scalar using $_' );
73 }
74 {
75     my $string = 'foo';
76     my @values;
77     $string->each_value(sub { push @values, $_[0] });
78     is_deeply( [@values], [$string], 'each_values for scalar using $_[0]' );
79 }