s/"/'/g
[gitmo/MooseX-StrictConstructor.git] / t / basic.t
CommitLineData
32726d88 1use strict;
2use warnings;
3
40ab99f6 4use Test::Exception;
5use Test::Moose qw( with_immutable );
54cc4bad 6use Test::More;
32726d88 7
32726d88 8{
9 package Standard;
10
11 use Moose;
12
13 has 'thing' => ( is => 'rw' );
14}
15
16{
17 package Stricter;
18
3e532dbe 19 use Moose;
32726d88 20 use MooseX::StrictConstructor;
21
22 has 'thing' => ( is => 'rw' );
23}
24
25{
2ffa7b60 26 package Subclass;
27
3e532dbe 28 use Moose;
2ffa7b60 29 use MooseX::StrictConstructor;
30
31 extends 'Stricter';
32
33 has 'size' => ( is => 'rw' );
34}
35
36{
32726d88 37 package Tricky;
38
3e532dbe 39 use Moose;
32726d88 40 use MooseX::StrictConstructor;
41
42 has 'thing' => ( is => 'rw' );
43
5a0d4921 44 sub BUILD {
32726d88 45 my $self = shift;
46 my $params = shift;
47
48 delete $params->{spy};
49 }
50}
51
58812bf9 52{
a83dec43 53 package InitArg;
54
3e532dbe 55 use Moose;
a83dec43 56 use MooseX::StrictConstructor;
57
58 has 'thing' => ( is => 'rw', 'init_arg' => 'other' );
59 has 'size' => ( is => 'rw', 'init_arg' => undef );
60}
61
40ab99f6 62my @classes = qw( Standard Stricter Subclass Tricky InitArg );
5a0d4921 63
40ab99f6 64with_immutable {
65 lives_ok { Standard->new( thing => 1, bad => 99 ) }
66 'standard Moose class ignores unknown params';
0f795b43 67
40ab99f6 68 throws_ok { Stricter->new( thing => 1, bad => 99 ) }
69 qr/unknown attribute.+: bad/,
70 'strict constructor blows up on unknown params';
0f795b43 71
40ab99f6 72 lives_ok { Subclass->new( thing => 1, size => 'large' ) }
73 'subclass constructor handles known attributes correctly';
0f795b43 74
40ab99f6 75 throws_ok { Subclass->new( thing => 1, bad => 99 ) }
76 qr/unknown attribute.+: bad/,
77 'subclass correctly recognizes bad attribute';
5a0d4921 78
40ab99f6 79 lives_ok { Tricky->new( thing => 1, spy => 99 ) }
80 'can work around strict constructor by deleting params in BUILD()';
58812bf9 81
40ab99f6 82 throws_ok { Tricky->new( thing => 1, agent => 99 ) }
83 qr/unknown attribute.+: agent/,
84 'Tricky still blows up on unknown params other than spy';
58812bf9 85
40ab99f6 86 throws_ok { Subclass->new( thing => 1, bad => 99 ) }
87 qr/unknown attribute.+: bad/,
88 'subclass constructor blows up on unknown params';
58812bf9 89
40ab99f6 90 throws_ok { InitArg->new( thing => 1 ) }
91 qr/unknown attribute.+: thing/,
92 'InitArg blows up with attribute name';
58812bf9 93
40ab99f6 94 throws_ok { InitArg->new( size => 1 ) }
95 qr/unknown attribute.+: size/,
96 'InitArg blows up when given attribute with undef init_arg';
c001451a 97
40ab99f6 98 lives_ok { InitArg->new( other => 1 ) }
99 'InitArg works when given proper init_arg';
100} @classes;
54cc4bad 101
102done_testing();