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;
59 is => 'rw', isa => 'Str',
61 my ($self, $val, $attr) = @_;
62 $trigger_calls{new_attr}++;
65 my ($self, $value, $set, $attr) = @_;
66 $initializer_calls{new_attr}++;
71 my @classes = qw(Parent Child);
75 my $foo = Parent->new;
76 my $bar = Parent->new;
78 is(blessed($foo), 'Parent', 'Parent->new gives a Parent object');
79 is($foo->name, undef, 'No name yet');
80 is($foo->lazy_classname, 'Parent', "lazy attribute initialized");
81 is( exception { $foo->type_constrained(10.5) }, undef, "Num type constraint for now.." );
83 # try to rebless, except it will fail due to Child's stricter type constraint
84 like( exception { Child->meta->rebless_instance($foo) }, qr/^Attribute \(type_constrained\) does not pass the type constraint because\: Validation failed for 'Int' with value 10\.5/, '... this failed because of type check' );
85 like( exception { Child->meta->rebless_instance($bar) }, qr/^Attribute \(type_constrained\) does not pass the type constraint because\: Validation failed for 'Int' with value 5\.5/, '... this failed because of type check' );
87 $foo->type_constrained(10);
88 $bar->type_constrained(5);
90 Child->meta->rebless_instance($foo);
91 Child->meta->rebless_instance($bar, new_attr => 'blah');
93 is(blessed($foo), 'Child', 'successfully reblessed into Child');
94 is($foo->name, 'Junior', "Child->name's default came through");
96 is($foo->lazy_classname, 'Parent', "lazy attribute was already initialized");
97 is($bar->lazy_classname, 'Child', "lazy attribute just now initialized");
99 like( exception { $foo->type_constrained(10.5) }, qr/^Attribute \(type_constrained\) does not pass the type constraint because\: Validation failed for 'Int' with value 10\.5/, '... this failed because of type check' );
103 local $TODO = 'Moose::Meta::Class does not yet call triggers for rebless_instance!';
104 is_deeply(\%Child::trigger_calls, { new_attr => 1 }, 'Trigger fired on rebless_instance');
106 is_deeply(\%Child::initializer_calls, { new_attr => 1 }, 'Initializer fired on rebless_instance');
108 undef %Child::trigger_calls;
109 undef %Child::initializer_calls;