die wrap with prefix for attribute isa
[gitmo/Moo.git] / t / accessor-isa.t
CommitLineData
6d377074 1use strictures 1;
2use Test::More;
3use Test::Fatal;
4
5sub run_for {
6 my $class = shift;
7
8 my $obj = $class->new(less_than_three => 1);
9
e57f338d 10 is($obj->less_than_three, 1, "initial value set (${class})");
6d377074 11
12 like(
13 exception { $obj->less_than_three(4) },
bc65d744 14 qr/isa check for "less_than_three" failed: 4 is not less than three/,
15 "exception thrown on bad set (${class})"
6d377074 16 );
17
e57f338d 18 is($obj->less_than_three, 1, "initial value remains after bad set (${class})");
6d377074 19
20 my $ret;
21
22 is(
23 exception { $ret = $obj->less_than_three(2) },
e57f338d 24 undef, "no exception on correct set (${class})"
6d377074 25 );
26
e57f338d 27 is($ret, 2, "correct setter return (${class})");
28 is($obj->less_than_three, 2, "correct getter return (${class})");
6d377074 29
e57f338d 30 is(exception { $class->new }, undef, "no exception with no value (${class})");
6d377074 31 like(
32 exception { $class->new(less_than_three => 12) },
bc65d744 33 qr/isa check for "less_than_three" failed: 12 is not less than three/,
e57f338d 34 "exception thrown on bad constructor arg (${class})"
6d377074 35 );
36}
37
38{
39 package Foo;
40
b1eebd55 41 use Moo;
6d377074 42
43 has less_than_three => (
44 is => 'rw',
45 isa => sub { die "$_[0] is not less than three" unless $_[0] < 3 }
46 );
47}
48
49run_for 'Foo';
50
51{
52 package Bar;
53
54 use Sub::Quote;
b1eebd55 55 use Moo;
6d377074 56
57 has less_than_three => (
58 is => 'rw',
e57f338d 59 isa => quote_sub q{
60 my ($x) = @_;
61 die "$x is not less than three" unless $x < 3
62 }
6d377074 63 );
64}
65
66run_for 'Bar';
67
68{
69 package Baz;
70
71 use Sub::Quote;
b1eebd55 72 use Moo;
6d377074 73
74 has less_than_three => (
75 is => 'rw',
76 isa => quote_sub(
e57f338d 77 q{
78 my ($value) = @_;
79 die "$value is not less than ${word}" unless $value < $limit
80 },
6d377074 81 { '$limit' => \3, '$word' => \'three' }
82 )
83 );
84}
85
86run_for 'Baz';
87
ef21bc32 88{
89 package LazyFoo;
90
91 use Moo;
92
93 has less_than_three => (
94 is => 'lazy',
95 isa => sub { die "$_[0] is not less than three" unless $_[0] < 3 }
96 );
97
98 sub _build_less_than_three { 4 }
99}
100
101like(
102 exception { LazyFoo->new->less_than_three },
bc65d744 103 qr/isa check for "less_than_three" failed: 4 is not less than three/,
ef21bc32 104 "exception thrown on bad builder return value (LazyFoo)"
105);
106
6d377074 107done_testing;