Commit | Line | Data |
c3398f5b |
1 | #!/usr/bin/env perl |
2 | use strict; |
3 | use warnings; |
8ab2c6ab |
4 | use Test::More; |
c3398f5b |
5 | |
6 | my $lazy_run = 0; |
7 | |
8 | do { |
9 | package Class; |
10 | use Mouse; |
11 | |
12 | has lazy => ( |
13 | is => 'rw', |
14 | lazy => 1, |
15 | default => sub { ++$lazy_run }, |
16 | ); |
17 | |
18 | has lazy_value => ( |
19 | is => 'rw', |
20 | lazy => 1, |
21 | default => "welp", |
22 | ); |
23 | |
2c689df4 |
24 | eval { |
c3398f5b |
25 | has lazy_no_default => ( |
26 | is => 'rw', |
27 | lazy => 1, |
28 | ); |
2c689df4 |
29 | }; |
30 | ::like $@, qr/You cannot have a lazy attribute \(lazy_no_default\) without specifying a default value for it/; |
c3398f5b |
31 | }; |
32 | |
33 | my $object = Class->new; |
34 | is($lazy_run, 0, "lazy attribute not yet initialized"); |
35 | |
36 | is($object->lazy, 1, "lazy coderef"); |
37 | is($lazy_run, 1, "lazy coderef invoked once"); |
38 | |
39 | is($object->lazy, 1, "lazy coderef is cached"); |
40 | is($lazy_run, 1, "lazy coderef invoked once"); |
41 | |
42 | is($object->lazy_value, 'welp', "lazy value"); |
43 | is($lazy_run, 1, "lazy coderef invoked once"); |
44 | |
45 | is($object->lazy_value("newp"), "newp", "set new value"); |
46 | is($lazy_run, 1, "lazy coderef invoked once"); |
47 | |
48 | is($object->lazy_value, "newp", "got new value"); |
49 | is($lazy_run, 1, "lazy coderef invoked once"); |
50 | |
8ab2c6ab |
51 | is($object->lazy(42), 42); |
52 | is($object->lazy_value(3.14), 3.14); |
53 | |
c3398f5b |
54 | my $object2 = Class->new(lazy => 'very', lazy_value => "heh"); |
55 | is($lazy_run, 1, "lazy attribute not initialized when an argument is passed to the constructor"); |
56 | |
57 | is($object2->lazy, 'very', 'value from the constructor'); |
58 | is($object2->lazy_value, 'heh', 'value from the constructor'); |
59 | is($lazy_run, 1, "lazy coderef not invoked, we already have a value"); |
60 | |
8ab2c6ab |
61 | done_testing; |