Remove useless whitespace
[gitmo/MooseX-Singleton.git] / t / 003-immutable.t
CommitLineData
2b4ce4bd 1use strict;
2use warnings;
3
a82b9823 4use Scalar::Util qw( refaddr );
2b4ce4bd 5use Test::More;
6
7BEGIN {
e01c7277 8 eval 'use Test::Warn';
9 plan skip_all => 'These tests require Test::Warn' if $@;
2b4ce4bd 10}
11
42915f8a 12{
2b4ce4bd 13 package MooseX::Singleton::Test;
14 use MooseX::Singleton;
15
16 has bag => (
17 is => 'rw',
18 isa => 'HashRef[Int]',
19 default => sub { { default => 42 } },
20 );
21
22 sub distinct_keys {
23 my $self = shift;
24 scalar keys %{ $self->bag };
25 }
26
27 sub clear {
28 my $self = shift;
4c256923 29 $self->bag( {} );
2b4ce4bd 30 }
31
32 sub add {
4c256923 33 my $self = shift;
34 my $key = shift;
2b4ce4bd 35 my $value = @_ ? shift : 1;
36
37 $self->bag->{$key} += $value;
38 }
b6591604 39
0ab35c13 40 ::warning_is sub { __PACKAGE__->meta->make_immutable }, '',
2b4ce4bd 41 'no warnings when calling make_immutable';
42}
43
44my $mst = MooseX::Singleton::Test->instance;
4c256923 45isa_ok( $mst, 'MooseX::Singleton::Test',
46 'Singleton->instance returns a real instance' );
2b4ce4bd 47
4c256923 48is( $mst->distinct_keys, 1, "default keys" );
2b4ce4bd 49
4c256923 50$mst->add( foo => 10 );
51is( $mst->distinct_keys, 2, "added key" );
2b4ce4bd 52
4c256923 53$mst->add( bar => 5 );
54is( $mst->distinct_keys, 3, "added another key" );
2b4ce4bd 55
56my $mst2 = MooseX::Singleton::Test->instance;
4c256923 57is( $mst, $mst2, 'instances are the same object' );
58isa_ok( $mst2, 'MooseX::Singleton::Test',
59 'Singleton->instance returns a real instance' );
2b4ce4bd 60
4c256923 61is( $mst2->distinct_keys, 3, "keys from before" );
2b4ce4bd 62
4c256923 63$mst->add( baz => 2 );
2b4ce4bd 64
4c256923 65is( $mst->distinct_keys, 4, "attributes are shared even after ->instance" );
66is( $mst2->distinct_keys, 4, "attributes are shared even after ->instance" );
2b4ce4bd 67
4c256923 68is( MooseX::Singleton::Test->distinct_keys, 4, "Package->reader works" );
2b4ce4bd 69
4c256923 70MooseX::Singleton::Test->add( quux => 9000 );
2b4ce4bd 71
4c256923 72is( $mst->distinct_keys, 5, "Package->add works" );
73is( $mst2->distinct_keys, 5, "Package->add works" );
74is( MooseX::Singleton::Test->distinct_keys, 5, "Package->add works" );
2b4ce4bd 75
76MooseX::Singleton::Test->clear;
77
4c256923 78is( $mst->distinct_keys, 0, "Package->clear works" );
79is( $mst2->distinct_keys, 0, "Package->clear works" );
80is( MooseX::Singleton::Test->distinct_keys, 0, "Package->clear works" );
2b4ce4bd 81
a82b9823 82{
83 my $addr;
84
85 {
86 $addr = refaddr( MooseX::Singleton::Test->instance );
87 }
88
4c256923 89 is(
90 $addr, refaddr( MooseX::Singleton::Test->instance ),
91 'singleton is not randomly destroyed'
92 );
a82b9823 93}
e01c7277 94
95done_testing;