6834fb95be472909b70901dd3c6dc0963da5b516
[p5sagit/Class-Accessor-Grouped.git] / t / accessors_ro.t
1 use Test::More tests => 48;
2 use Test::Exception;
3 use strict;
4 use warnings;
5 use Config;
6 use lib 't/lib';
7
8 # we test the pure-perl versions only, but allow overrides
9 # from the accessor_xs test-umbrella
10 # Also make sure a rogue envvar will not interfere with
11 # things
12 my $use_xs;
13 BEGIN {
14   $Class::Accessor::Grouped::USE_XS = 0
15     unless defined $Class::Accessor::Grouped::USE_XS;
16   $ENV{CAG_USE_XS} = 1;
17   $use_xs = $Class::Accessor::Grouped::USE_XS;
18 };
19
20 use AccessorGroupsRO;
21
22 my $obj = AccessorGroupsRO->new;
23
24 {
25   my $warned = 0;
26
27   local $SIG{__WARN__} = sub {
28     if  (shift =~ /DESTROY/i) {
29       $warned++;
30     };
31   };
32
33   no warnings qw/once/;
34   local *AccessorGroupsRO::DESTROY = sub {};
35
36   $obj->mk_group_ro_accessors('warnings', 'DESTROY');
37
38   ok($warned);
39 };
40
41 my $test_accessors = {
42   singlefield => {
43     is_xs => $use_xs,
44   },
45   multiple1 => {
46   },
47   multiple2 => {
48   },
49   lr1name => {
50     custom_field => 'lr1;field',
51   },
52   lr2name => {
53     custom_field => "lr2'field",
54   },
55 };
56
57 for my $name (sort keys %$test_accessors) {
58
59   my $alias = "_${name}_accessor";
60   my $field = $test_accessors->{$name}{custom_field} || $name;
61
62   can_ok($obj, $name, $alias);
63
64   ok(!$obj->can($field))
65     if $field ne $name;
66
67   is($obj->$name, undef);
68   is($obj->$alias, undef);
69
70   # get via name
71   $obj->{$field} = 'a';
72   is($obj->$name, 'a');
73
74   # alias gets same as name
75   is($obj->$alias, 'a');
76
77   my $ro_regex = $test_accessors->{$name}{is_xs}
78     ? qr/Usage\:.+$name.*\(self\)/
79     : qr/cannot alter the value of '\Q$field\E'/
80   ;
81
82   {
83     local $TODO = "Class::XSAccessor emits broken error messages on 5.10 or -DDEBUGGING 5.8"
84       if (
85         $test_accessors->{$name}{is_xs}
86           and
87         $] < '5.011'
88           and
89         ( $] > '5.009' or $Config{config_args} =~ /DEBUGGING/ )
90       );
91
92     # die on set via name/alias
93     throws_ok {
94       $obj->$name('b');
95     } $ro_regex;
96
97     throws_ok {
98       $obj->$alias('b');
99     } $ro_regex;
100   }
101
102   # value should be unchanged
103   is($obj->$name, 'a');
104   is($obj->$alias, 'a');
105 };
106
107 #important
108 1;