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