8 use Test::Moose qw(with_immutable);
9 use Scalar::Util 'blessed';
11 use Moose::Util::TypeConstraints;
26 has lazy_classname => (
29 default => sub { "Parent" },
32 has type_constrained => (
46 has '+lazy_classname' => (
47 default => sub {"Child"},
50 has '+type_constrained' => (
56 our %initializer_calls;
62 my ( $self, $val, $attr ) = @_;
63 $trigger_calls{new_attr}++;
66 my ( $self, $value, $set, $attr ) = @_;
67 $initializer_calls{new_attr}++;
73 my @classes = qw(Parent Child);
76 my $foo = Parent->new;
77 my $bar = Parent->new;
79 is( blessed($foo), 'Parent', 'Parent->new gives a Parent object' );
80 is( $foo->name, undef, 'No name yet' );
81 is( $foo->lazy_classname, 'Parent', "lazy attribute initialized" );
83 exception { $foo->type_constrained(10.5) }, undef,
84 "Num type constraint for now.."
87 # try to rebless, except it will fail due to Child's stricter type constraint
89 exception { Child->meta->rebless_instance($foo) },
90 qr/^Attribute \(type_constrained\) does not pass the type constraint because\: Validation failed for 'Int' with value 10\.5/,
91 '... this failed because of type check'
94 exception { Child->meta->rebless_instance($bar) },
95 qr/^Attribute \(type_constrained\) does not pass the type constraint because\: Validation failed for 'Int' with value 5\.5/,
96 '... this failed because of type check'
99 $foo->type_constrained(10);
100 $bar->type_constrained(5);
102 Child->meta->rebless_instance($foo);
103 Child->meta->rebless_instance( $bar, new_attr => 'blah' );
105 is( blessed($foo), 'Child', 'successfully reblessed into Child' );
106 is( $foo->name, 'Junior', "Child->name's default came through" );
109 $foo->lazy_classname, 'Parent',
110 "lazy attribute was already initialized"
113 $bar->lazy_classname, 'Child',
114 "lazy attribute just now initialized"
118 exception { $foo->type_constrained(10.5) },
119 qr/^Attribute \(type_constrained\) does not pass the type constraint because\: Validation failed for 'Int' with value 10\.5/,
120 '... this failed because of type check'
124 \%Child::trigger_calls, { new_attr => 1 },
125 'Trigger fired on rebless_instance'
128 \%Child::initializer_calls, { new_attr => 1 },
129 'Initializer fired on rebless_instance'
132 undef %Child::trigger_calls;
133 undef %Child::initializer_calls;