drop package_ from method names
[gitmo/Package-Stash-XS.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
15c104e2 23 sub add_symbol {
f10f6217 24 my ($self, $variable, $initial_value) = @_;
25
e3ad44fd 26 (my $name = $variable) =~ s/^[\$\@\%\&]//;
f10f6217 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');
15c104e2 41ok(!$foo_stash->has_symbol('%foo'), '... the foo_stash agrees');
f10f6217 42
20336547 43is(exception {
15c104e2 44 $foo_stash->add_symbol('%foo' => { one => 1 });
20336547 45}, undef, '... the %foo symbol is created succcessfully');
f10f6217 46
47ok(!defined($Foo::{foo}), '... the %foo slot has not been created in the actual Foo package');
15c104e2 48ok($foo_stash->has_symbol('%foo'), '... the foo_stash agrees');
f10f6217 49
15c104e2 50my $foo = $foo_stash->get_symbol('%foo');
f10f6217 51is_deeply({ one => 1 }, $foo, '... got the right package variable back');
52
53$foo->{two} = 2;
54
15c104e2 55is($foo, $foo_stash->get_symbol('%foo'), '... our %foo is the same as the foo_stashs');
f10f6217 56
57ok(!defined($Foo::{bar}), '... the @bar slot has not been created yet');
58
20336547 59is(exception {
15c104e2 60 $foo_stash->add_symbol('@bar' => [ 1, 2, 3 ]);
20336547 61}, undef, '... 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
20336547 67is(exception {
15c104e2 68 $foo_stash->add_symbol('%baz');
20336547 69}, undef, '... created %Foo::baz successfully');
f10f6217 70
71ok(!defined($Foo::{baz}), '... the %baz slot has still not been created');
72
73done_testing;