fix list_all_package_symbols
[gitmo/Package-Stash-PP.git] / t / 02-extension.t
CommitLineData
f10f6217 1use strict;
2use warnings;
3
4use Test::More;
13f4d7c3 5use Test::Fatal;
f10f6217 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 35my $foo_stash = My::Package::Stash->new('Foo');
f10f6217 36
e94260da 37isa_ok($foo_stash, 'My::Package::Stash');
38isa_ok($foo_stash, 'Package::Stash');
f10f6217 39
40ok(!defined($Foo::{foo}), '... the %foo slot has not been created yet');
41ok(!$foo_stash->has_package_symbol('%foo'), '... the foo_stash agrees');
42
13f4d7c3 43ok(!exception {
f10f6217 44 $foo_stash->add_package_symbol('%foo' => { one => 1 });
13f4d7c3 45}, '... the %foo symbol is created succcessfully');
f10f6217 46
47ok(!defined($Foo::{foo}), '... the %foo slot has not been created in the actual Foo package');
48ok($foo_stash->has_package_symbol('%foo'), '... the foo_stash agrees');
49
50my $foo = $foo_stash->get_package_symbol('%foo');
51is_deeply({ one => 1 }, $foo, '... got the right package variable back');
52
53$foo->{two} = 2;
54
55is($foo, $foo_stash->get_package_symbol('%foo'), '... our %foo is the same as the foo_stashs');
56
57ok(!defined($Foo::{bar}), '... the @bar slot has not been created yet');
58
13f4d7c3 59ok(!exception {
f10f6217 60 $foo_stash->add_package_symbol('@bar' => [ 1, 2, 3 ]);
13f4d7c3 61}, '... created @Foo::bar successfully');
f10f6217 62
63ok(!defined($Foo::{bar}), '... the @bar slot has still not been created');
64
65ok(!defined($Foo::{baz}), '... the %baz slot has not been created yet');
66
13f4d7c3 67ok(!exception {
f10f6217 68 $foo_stash->add_package_symbol('%baz');
13f4d7c3 69}, '... created %Foo::baz successfully');
f10f6217 70
71ok(!defined($Foo::{baz}), '... the %baz slot has still not been created');
72
73done_testing;