8a58aa3e986b6a656d5723b70bbc08ea2aa6937d
[gitmo/Eval-Closure.git] / t / close-over.t
1 #!/usr/bin/env perl
2 use strict;
3 use warnings;
4 use Test::More;
5 use Test::Fatal;
6
7 use Eval::Closure;
8
9 use Test::Requires 'PadWalker';
10
11 {
12     my $foo = [];
13     my $env = { '$foo' => \$foo };
14
15     my $code = eval_closure(
16         source      => 'sub { push @$foo, @_ }',
17         environment => $env,
18     );
19     is_deeply(scalar(PadWalker::closed_over($code)), $env,
20               "closed over the right things");
21 }
22
23 {
24     my $foo = {};
25     my $bar = [];
26     my $env = { '$foo' => \$bar, '$bar' => \$foo };
27
28     my $code = eval_closure(
29         source      => 'sub { push @$foo, @_; $bar->{foo} = \@_ }',
30         environment => $env,
31     );
32     is_deeply(scalar(PadWalker::closed_over($code)), $env,
33               "closed over the right things");
34 }
35
36 {
37     my $foo = [];
38     my $env = { '$foo' => \$foo };
39
40     like(
41         exception {
42             eval_closure(
43                 source      => 'sub { push @$foo, @_; return $__captures }',
44                 environment => $env,
45             );
46         },
47         qr/Global symbol "\$__captures/,
48         "we don't close over \$__captures"
49     );
50 }
51
52 # it'd be nice if we could test that closing over other things wasn't possible,
53 # but perl's optimizer gets in the way of that
54
55 done_testing;