Convert to Test::Fatal
[gitmo/MooseX-StrictConstructor.git] / t / basic.t
1 use strict;
2 use warnings;
3
4 use Test::Fatal;
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     is(
66         exception { Standard->new( thing => 1, bad => 99 ) }, undef,
67         'standard Moose class ignores unknown params'
68     );
69
70     like(
71         exception { Stricter->new( thing => 1, bad => 99 ) },
72         qr/unknown attribute.+: bad/,
73         'strict constructor blows up on unknown params'
74     );
75
76     is(
77         exception { Subclass->new( thing => 1, size => 'large' ) }, undef,
78         'subclass constructor handles known attributes correctly'
79     );
80
81     like(
82         exception { Subclass->new( thing => 1, bad => 99 ) },
83         qr/unknown attribute.+: bad/,
84         'subclass correctly recognizes bad attribute'
85     );
86
87     is(
88         exception { Tricky->new( thing => 1, spy => 99 ) }, undef,
89         'can work around strict constructor by deleting params in BUILD()'
90     );
91
92     like(
93         exception { Tricky->new( thing => 1, agent => 99 ) },
94         qr/unknown attribute.+: agent/,
95         'Tricky still blows up on unknown params other than spy'
96     );
97
98     like(
99         exception { Subclass->new( thing => 1, bad => 99 ) },
100         qr/unknown attribute.+: bad/,
101         'subclass constructor blows up on unknown params'
102     );
103
104     like(
105         exception { InitArg->new( thing => 1 ) },
106         qr/unknown attribute.+: thing/,
107         'InitArg blows up with attribute name'
108     );
109
110     like(
111         exception { InitArg->new( size => 1 ) },
112         qr/unknown attribute.+: size/,
113         'InitArg blows up when given attribute with undef init_arg'
114     );
115
116     is(
117         exception { InitArg->new( other => 1 ) }, undef,
118         'InitArg works when given proper init_arg'
119     );
120 }
121 @classes;
122
123 done_testing();