_clear_instance and tests
[gitmo/MooseX-Singleton.git] / t / 001-basic.t
CommitLineData
109b110b 1use strict;
2use warnings;
03e1b8df 3use Test::More tests => 17;
109b110b 4
5BEGIN {
6 package MooseX::Singleton::Test;
7 use MooseX::Singleton;
8
9 has bag => (
10 is => 'rw',
11 isa => 'HashRef[Int]',
7afceec3 12 default => sub { { default => 42 } },
109b110b 13 );
14
15 sub distinct_keys {
16 my $self = shift;
17 scalar keys %{ $self->bag };
18 }
19
20 sub clear {
21 my $self = shift;
22 $self->bag({});
23 }
24
25 sub add {
26 my $self = shift;
27 my $key = shift;
28 my $value = @_ ? shift : 1;
29
30 $self->bag->{$key} += $value;
31 }
32}
33
34my $mst = MooseX::Singleton::Test->instance;
35isa_ok($mst, 'MooseX::Singleton::Test', 'Singleton->instance returns a real instance');
36
7afceec3 37is($mst->distinct_keys, 1, "default keys");
109b110b 38
39$mst->add(foo => 10);
7afceec3 40is($mst->distinct_keys, 2, "added key");
109b110b 41
42$mst->add(bar => 5);
7afceec3 43is($mst->distinct_keys, 3, "added another key");
109b110b 44
45my $mst2 = MooseX::Singleton::Test->instance;
2b4ce4bd 46is($mst, $mst2, 'instances are the same object');
109b110b 47isa_ok($mst2, 'MooseX::Singleton::Test', 'Singleton->instance returns a real instance');
48
7afceec3 49is($mst2->distinct_keys, 3, "keys from before");
109b110b 50
51$mst->add(baz => 2);
52
7afceec3 53is($mst->distinct_keys, 4, "attributes are shared even after ->instance");
54is($mst2->distinct_keys, 4, "attributes are shared even after ->instance");
109b110b 55
7afceec3 56is(MooseX::Singleton::Test->distinct_keys, 4, "Package->reader works");
109b110b 57
58MooseX::Singleton::Test->add(quux => 9000);
59
7afceec3 60is($mst->distinct_keys, 5, "Package->add works");
61is($mst2->distinct_keys, 5, "Package->add works");
62is(MooseX::Singleton::Test->distinct_keys, 5, "Package->add works");
109b110b 63
64MooseX::Singleton::Test->clear;
65
7afceec3 66is($mst->distinct_keys, 0, "Package->clear works");
67is($mst2->distinct_keys, 0, "Package->clear works");
68is(MooseX::Singleton::Test->distinct_keys, 0, "Package->clear works");
109b110b 69
03e1b8df 70MooseX::Singleton::Test->_clear_instance;
71$mst = $mst2 = undef;
72is(MooseX::Singleton::Test->new->distinct_keys, 1, "back to the default");