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