summaryrefslogtreecommitdiffstats
path: root/t/10-lazy-require.t
blob: fbe2c81f369b9eecec4d16b75abae69ae6c41aec (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Test::Exception;

{
    package My::MooseX::LazyRequire;
    use MooseX::Attribute::Shorthand ();

    sub import {
        my $class = caller;
        MooseX::Attribute::Shorthand->import(
            -for_class => $class,
            lazy_required => {
                lazy     => 1,
                required => 1,
                default  => sub {
                    my $name = shift;
                    sub {
                        Carp::confess "Attribute $name must be provided before calling reader";
                    }
                },
            },
        );
    }
}

{
    package Foo;
    use Moose;
    BEGIN { My::MooseX::LazyRequire->import }

    has bar => (
        is            => 'ro',
        lazy_required => 1,
    );

    has baz => (
        is      => 'ro',
        builder => '_build_baz',
    );

    sub _build_baz { shift->bar + 1 }
}

{
    my $foo;
    lives_ok(sub {
        $foo = Foo->new(bar => 42);
    });
    is($foo->baz, 43);
}

{
    my $foo;
    lives_ok(sub {
        $foo = Foo->new(baz => 23);
    });
    is($foo->baz, 23);
}

throws_ok(sub {
    Foo->new;
}, qr/must be provided/);

{
    package Bar;
    use Moose;
    BEGIN { My::MooseX::LazyRequire->import }

    has foo => (
        is            => 'rw',
        lazy_required => 1,
    );

    has baz => (
        is      => 'ro',
        lazy    => 1,
        builder => '_build_baz',
    );

    sub _build_baz { shift->foo + 1 }
}

{
    my $bar = Bar->new;

    throws_ok(sub {
        $bar->baz;
    }, qr/must be provided/);

    $bar->foo(42);

    my $baz;
    lives_ok(sub {
        $baz = $bar->baz;
    });

    is($baz, 43);
}

done_testing;