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