Commit | Line | Data |
109b110b |
1 | use strict; |
2 | use warnings; |
e01c7277 |
3 | use Test::More; |
109b110b |
4 | |
5 | BEGIN { |
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; |
4c256923 |
22 | $self->bag( {} ); |
109b110b |
23 | } |
24 | |
25 | sub add { |
4c256923 |
26 | my $self = shift; |
27 | my $key = shift; |
109b110b |
28 | my $value = @_ ? shift : 1; |
29 | |
30 | $self->bag->{$key} += $value; |
31 | } |
32 | } |
33 | |
34 | my $mst = MooseX::Singleton::Test->instance; |
4c256923 |
35 | isa_ok( $mst, 'MooseX::Singleton::Test', |
36 | 'Singleton->instance returns a real instance' ); |
109b110b |
37 | |
4c256923 |
38 | is( $mst->distinct_keys, 1, "default keys" ); |
109b110b |
39 | |
4c256923 |
40 | $mst->add( foo => 10 ); |
41 | is( $mst->distinct_keys, 2, "added key" ); |
109b110b |
42 | |
4c256923 |
43 | $mst->add( bar => 5 ); |
44 | is( $mst->distinct_keys, 3, "added another key" ); |
109b110b |
45 | |
46 | my $mst2 = MooseX::Singleton::Test->instance; |
4c256923 |
47 | is( $mst, $mst2, 'instances are the same object' ); |
48 | isa_ok( $mst2, 'MooseX::Singleton::Test', |
49 | 'Singleton->instance returns a real instance' ); |
109b110b |
50 | |
4c256923 |
51 | is( $mst2->distinct_keys, 3, "keys from before" ); |
109b110b |
52 | |
4c256923 |
53 | $mst->add( baz => 2 ); |
109b110b |
54 | |
4c256923 |
55 | is( $mst->distinct_keys, 4, "attributes are shared even after ->instance" ); |
56 | is( $mst2->distinct_keys, 4, "attributes are shared even after ->instance" ); |
109b110b |
57 | |
4c256923 |
58 | is( MooseX::Singleton::Test->distinct_keys, 4, "Package->reader works" ); |
109b110b |
59 | |
4c256923 |
60 | MooseX::Singleton::Test->add( quux => 9000 ); |
109b110b |
61 | |
4c256923 |
62 | is( $mst->distinct_keys, 5, "Package->add works" ); |
63 | is( $mst2->distinct_keys, 5, "Package->add works" ); |
64 | is( MooseX::Singleton::Test->distinct_keys, 5, "Package->add works" ); |
109b110b |
65 | |
66 | MooseX::Singleton::Test->clear; |
67 | |
4c256923 |
68 | is( $mst->distinct_keys, 0, "Package->clear works" ); |
69 | is( $mst2->distinct_keys, 0, "Package->clear works" ); |
70 | is( MooseX::Singleton::Test->distinct_keys, 0, "Package->clear works" ); |
109b110b |
71 | |
03e1b8df |
72 | MooseX::Singleton::Test->_clear_instance; |
73 | $mst = $mst2 = undef; |
5a0f3fa6 |
74 | is( MooseX::Singleton::Test->instance->distinct_keys, 1, "back to the default" ); |
e01c7277 |
75 | |
76 | done_testing; |