Bump version
[gitmo/Moo.git] / t / accessor-weaken.t
CommitLineData
32381de9 1use strictures 1;
2use Test::More;
3
4{
5 package Foo;
6
7 use Moo;
8
f3dc0ac6 9 has one => (is => 'rw', weak_ref => 1);
6998abed 10
11 package Foo2;
12
13 use Moo;
14
f3dc0ac6 15 has one => (is => 'rw', lazy => 1, weak_ref => 1, default => sub { {} });
32381de9 16}
17
2215d4b9 18my $ref = {};
32381de9 19my $foo = Foo->new(one => $ref);
2215d4b9 20is($foo->one, $ref, 'value present');
32381de9 21ok(Scalar::Util::isweak($foo->{one}), 'value weakened');
f3dc0ac6 22is($foo->one($ref), $ref, 'value returned from setter');
2215d4b9 23undef $ref;
6998abed 24ok(!defined $foo->{one}, 'weak value gone');
25
26my $foo2 = Foo2->new;
27ok(my $ref2 = $foo2->one, 'value returned');
28ok(Scalar::Util::isweak($foo2->{one}), 'value weakened');
f3dc0ac6 29is($foo2->one($ref2), $ref2, 'value returned from setter');
6998abed 30undef $ref2;
31ok(!defined $foo->{one}, 'weak value gone');
2215d4b9 32
f3dc0ac6 33
2215d4b9 34# test readonly SVs
35sub mk_ref { \ 'yay' };
36my $foo_ro = eval { Foo->new(one => mk_ref()) };
37if ($] < 5.008003) {
38 like(
39 $@,
40 qr/\QReference to readonly value in "one" can not be weakened on Perl < 5.8.3/,
41 'Expected exception thrown on old perls'
42 );
43}
5f578bd3 44elsif ($^O eq 'cygwin' and $] < 5.012000) {
45 SKIP: { skip 'Static coderef reaping seems nonfunctional on cygwin < 5.12', 1 }
46}
2215d4b9 47else {
48 is(${$foo_ro->one},'yay', 'value present');
49 ok(Scalar::Util::isweak($foo_ro->{one}), 'value weakened');
50
51 { no warnings 'redefine'; *mk_ref = sub {} }
52 ok (!defined $foo_ro->{one}, 'optree reaped, ro static value gone');
53}
32381de9 54
55done_testing;