fix list_all_package_symbols
[gitmo/Package-Stash-PP.git] / t / 02-extension.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Fatal;
6
7 {
8     package My::Package::Stash;
9     use strict;
10     use warnings;
11
12     use base 'Package::Stash';
13
14     use Symbol 'gensym';
15
16     sub new {
17         my $class = shift;
18         my $self = $class->SUPER::new(@_);
19         $self->{namespace} = {};
20         return $self;
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 :)
35 my $foo_stash = My::Package::Stash->new('Foo');
36
37 isa_ok($foo_stash, 'My::Package::Stash');
38 isa_ok($foo_stash, 'Package::Stash');
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 ok(!exception {
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 ok(!exception {
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 ok(!exception {
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;