convert the XS implementation to its own dist
[gitmo/Package-Stash-XS.git] / t / 02-extension.t
1 #!/usr/bin/env perl
2 use strict;
3 use warnings;
4 use lib 't/lib';
5 use Test::More;
6 use Test::Fatal;
7
8 {
9     package My::Package::Stash;
10     use strict;
11     use warnings;
12
13     use base 'Package::Stash';
14
15     use Symbol 'gensym';
16
17     sub new {
18         my $class = shift;
19         my $self = $class->SUPER::new(@_);
20         $self->{namespace} = {};
21         return $self;
22     }
23
24     sub add_symbol {
25         my ($self, $variable, $initial_value) = @_;
26
27         (my $name = $variable) =~ s/^[\$\@\%\&]//;
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 :)
36 my $foo_stash = My::Package::Stash->new('Foo');
37
38 isa_ok($foo_stash, 'My::Package::Stash');
39 isa_ok($foo_stash, 'Package::Stash');
40
41 ok(!defined($Foo::{foo}), '... the %foo slot has not been created yet');
42 ok(!$foo_stash->has_symbol('%foo'), '... the foo_stash agrees');
43
44 is(exception {
45     $foo_stash->add_symbol('%foo' => { one => 1 });
46 }, undef, '... the %foo symbol is created succcessfully');
47
48 ok(!defined($Foo::{foo}), '... the %foo slot has not been created in the actual Foo package');
49 ok($foo_stash->has_symbol('%foo'), '... the foo_stash agrees');
50
51 my $foo = $foo_stash->get_symbol('%foo');
52 is_deeply({ one => 1 }, $foo, '... got the right package variable back');
53
54 $foo->{two} = 2;
55
56 is($foo, $foo_stash->get_symbol('%foo'), '... our %foo is the same as the foo_stashs');
57
58 ok(!defined($Foo::{bar}), '... the @bar slot has not been created yet');
59
60 is(exception {
61     $foo_stash->add_symbol('@bar' => [ 1, 2, 3 ]);
62 }, undef, '... created @Foo::bar successfully');
63
64 ok(!defined($Foo::{bar}), '... the @bar slot has still not been created');
65
66 ok(!defined($Foo::{baz}), '... the %baz slot has not been created yet');
67
68 is(exception {
69     $foo_stash->add_symbol('%baz');
70 }, undef, '... created %Foo::baz successfully');
71
72 ok(!defined($Foo::{baz}), '... the %baz slot has still not been created');
73
74 done_testing;