Commit | Line | Data |
f10f6217 |
1 | use strict; |
2 | use warnings; |
3 | |
4 | use Test::More; |
5 | use Test::Exception; |
6 | |
7 | { |
e94260da |
8 | package My::Package::Stash; |
f10f6217 |
9 | use strict; |
10 | use warnings; |
11 | |
e94260da |
12 | use base 'Package::Stash'; |
f10f6217 |
13 | |
14 | use Symbol 'gensym'; |
15 | |
e55970bc |
16 | sub new { |
17 | my $class = shift; |
18 | my $self = $class->SUPER::new(@_); |
19 | $self->{namespace} = {}; |
20 | return $self; |
f10f6217 |
21 | } |
22 | |
23 | sub add_package_symbol { |
24 | my ($self, $variable, $initial_value) = @_; |
25 | |
26 | my ($name, $sigil, $type) = $self->_deconstruct_variable_name($variable); |
27 | |
28 | my $glob = gensym(); |
29 | *{$glob} = $initial_value if defined $initial_value; |
30 | $self->namespace->{$name} = *{$glob}; |
31 | } |
32 | } |
33 | |
34 | # No actually package Foo exists :) |
e94260da |
35 | my $foo_stash = My::Package::Stash->new('Foo'); |
f10f6217 |
36 | |
e94260da |
37 | isa_ok($foo_stash, 'My::Package::Stash'); |
38 | isa_ok($foo_stash, 'Package::Stash'); |
f10f6217 |
39 | |
40 | ok(!defined($Foo::{foo}), '... the %foo slot has not been created yet'); |
41 | ok(!$foo_stash->has_package_symbol('%foo'), '... the foo_stash agrees'); |
42 | |
43 | lives_ok { |
44 | $foo_stash->add_package_symbol('%foo' => { one => 1 }); |
45 | } '... the %foo symbol is created succcessfully'; |
46 | |
47 | ok(!defined($Foo::{foo}), '... the %foo slot has not been created in the actual Foo package'); |
48 | ok($foo_stash->has_package_symbol('%foo'), '... the foo_stash agrees'); |
49 | |
50 | my $foo = $foo_stash->get_package_symbol('%foo'); |
51 | is_deeply({ one => 1 }, $foo, '... got the right package variable back'); |
52 | |
53 | $foo->{two} = 2; |
54 | |
55 | is($foo, $foo_stash->get_package_symbol('%foo'), '... our %foo is the same as the foo_stashs'); |
56 | |
57 | ok(!defined($Foo::{bar}), '... the @bar slot has not been created yet'); |
58 | |
59 | lives_ok { |
60 | $foo_stash->add_package_symbol('@bar' => [ 1, 2, 3 ]); |
61 | } '... created @Foo::bar successfully'; |
62 | |
63 | ok(!defined($Foo::{bar}), '... the @bar slot has still not been created'); |
64 | |
65 | ok(!defined($Foo::{baz}), '... the %baz slot has not been created yet'); |
66 | |
67 | lives_ok { |
68 | $foo_stash->add_package_symbol('%baz'); |
69 | } '... created %Foo::baz successfully'; |
70 | |
71 | ok(!defined($Foo::{baz}), '... the %baz slot has still not been created'); |
72 | |
73 | done_testing; |