7 use Moose::Util::TypeConstraints;
15 inc_counter_2 => [ inc => 2 ],
17 dec_counter_2 => [ dec => 2 ],
18 reset_counter => 'reset',
20 set_counter_42 => [ set => 42 ],
28 my $class = Moose::Meta::Class->create(
30 superclasses => ['Moose::Object'],
33 $class->add_attribute(
35 traits => ['Counter'],
40 clearer => '_clear_counter',
45 return ( $class->name, \%handles );
50 run_tests(build_class);
51 run_tests( build_class( lazy => 1 ) );
52 run_tests( build_class( trigger => sub { } ) );
54 # Will force the inlining code to check the entire hashref when it is modified.
55 subtype 'MyInt', as 'Int', where { 1 };
57 run_tests( build_class( isa => 'MyInt' ) );
59 coerce 'MyInt', from 'Int', via { $_ };
61 run_tests( build_class( isa => 'MyInt', coerce => 1 ) );
65 my ( $class, $handles ) = @_;
67 can_ok( $class, $_ ) for sort keys %{$handles};
70 my $obj = $class->new();
72 is( $obj->counter, 0, '... got the default value' );
75 is( $obj->counter, 1, '... got the incremented value' );
78 is( $obj->counter, 2, '... got the incremented value (again)' );
80 throws_ok { $obj->inc_counter( 1, 2 ) }
81 qr/Cannot call inc with more than 1 argument/,
82 'inc throws an error when two arguments are passed';
85 is( $obj->counter, 1, '... got the decremented value' );
87 throws_ok { $obj->dec_counter( 1, 2 ) }
88 qr/Cannot call dec with more than 1 argument/,
89 'dec throws an error when two arguments are passed';
92 is( $obj->counter, 0, '... got the original value' );
94 throws_ok { $obj->reset_counter(2) }
95 qr/Cannot call reset with any arguments/,
96 'reset throws an error when an argument is passed';
99 is( $obj->counter, 5, '... set the value' );
101 throws_ok { $obj->set_counter( 1, 2 ) }
102 qr/Cannot call set with more than 1 argument/,
103 'set throws an error when two arguments are passed';
105 $obj->inc_counter(2);
106 is( $obj->counter, 7, '... increment by arg' );
108 $obj->dec_counter(5);
109 is( $obj->counter, 2, '... decrement by arg' );
112 is( $obj->counter, 4, '... curried increment' );
115 is( $obj->counter, 2, '... curried deccrement' );
117 $obj->set_counter_42;
118 is( $obj->counter, 42, '... curried set' );
120 if ( $class->meta->get_attribute('counter')->is_lazy ) {
121 my $obj = $class->new;
124 is( $obj->counter, 1, 'inc increments - with lazy default' );
126 $obj->_clear_counter;
129 is( $obj->counter, -1, 'dec decrements - with lazy default' );