rename Stash::Manip -> Package::Stash
[gitmo/Package-Stash-PP.git] / t / 002-extension.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Exception;
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 namespace {
17         $_[0]->{namespace} ||= {}
18     }
19
20     sub add_package_symbol {
21         my ($self, $variable, $initial_value) = @_;
22
23         my ($name, $sigil, $type) = $self->_deconstruct_variable_name($variable);
24
25         my $glob = gensym();
26         *{$glob} = $initial_value if defined $initial_value;
27         $self->namespace->{$name} = *{$glob};
28     }
29 }
30
31 # No actually package Foo exists :)
32 my $foo_stash = My::Package::Stash->new('Foo');
33
34 isa_ok($foo_stash, 'My::Package::Stash');
35 isa_ok($foo_stash, 'Package::Stash');
36
37 ok(!defined($Foo::{foo}), '... the %foo slot has not been created yet');
38 ok(!$foo_stash->has_package_symbol('%foo'), '... the foo_stash agrees');
39
40 lives_ok {
41     $foo_stash->add_package_symbol('%foo' => { one => 1 });
42 } '... the %foo symbol is created succcessfully';
43
44 ok(!defined($Foo::{foo}), '... the %foo slot has not been created in the actual Foo package');
45 ok($foo_stash->has_package_symbol('%foo'), '... the foo_stash agrees');
46
47 my $foo = $foo_stash->get_package_symbol('%foo');
48 is_deeply({ one => 1 }, $foo, '... got the right package variable back');
49
50 $foo->{two} = 2;
51
52 is($foo, $foo_stash->get_package_symbol('%foo'), '... our %foo is the same as the foo_stashs');
53
54 ok(!defined($Foo::{bar}), '... the @bar slot has not been created yet');
55
56 lives_ok {
57     $foo_stash->add_package_symbol('@bar' => [ 1, 2, 3 ]);
58 } '... created @Foo::bar successfully';
59
60 ok(!defined($Foo::{bar}), '... the @bar slot has still not been created');
61
62 ok(!defined($Foo::{baz}), '... the %baz slot has not been created yet');
63
64 lives_ok {
65     $foo_stash->add_package_symbol('%baz');
66 } '... created %Foo::baz successfully';
67
68 ok(!defined($Foo::{baz}), '... the %baz slot has still not been created');
69
70 done_testing;