summaryrefslogtreecommitdiff
path: root/t/type_constraints/duck_types.t
blob: d13d862609a7e30f9d29cc99c0cc665c68b98d20 (plain)
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
use strict;
use warnings;

use Test::More;
use Test::Fatal;

{

    package Duck;
    use Moose;

    sub quack { }

}

{

    package Swan;
    use Moose;

    sub honk { }

}

{

    package RubberDuck;
    use Moose;

    sub quack { }

}

{

    package DucktypeTest;
    use Moose;
    use Moose::Util::TypeConstraints;

    duck_type 'DuckType' => [qw(quack)];
    duck_type 'SwanType' => [qw(honk)];

    has duck => (
        isa        => 'DuckType',
        is => 'ro',
        lazy_build => 1,
    );

    sub _build_duck { Duck->new }

    has swan => (
        isa => duck_type( [qw(honk)] ),
        is => 'ro',
    );

    has other_swan => (
        isa => 'SwanType',
        is => 'ro',
    );

}

# try giving it a duck
is( exception { DucktypeTest->new( duck => Duck->new ) }, undef, 'the Duck lives okay' );

# try giving it a swan which is like a duck, but not close enough
like( exception { DucktypeTest->new( duck => Swan->new ) }, qr/Swan is missing methods 'quack'/, "the Swan doesn't quack" );

# try giving it a rubber RubberDuckey
is( exception { DucktypeTest->new( swan => Swan->new ) }, undef, 'but a Swan can honk' );

# try giving it a rubber RubberDuckey
is( exception { DucktypeTest->new( duck => RubberDuck->new ) }, undef, 'the RubberDuck lives okay' );

# try with the other constraint form
is( exception { DucktypeTest->new( other_swan => Swan->new ) }, undef, 'but a Swan can honk' );

my $re = qr/Validation failed for 'DuckType' with value/;

like( exception { DucktypeTest->new( duck => undef ) }, $re, 'Exception for undef' );
like( exception { DucktypeTest->new( duck => [] ) }, $re, 'Exception for arrayref' );
like( exception { DucktypeTest->new( duck => {} ) }, $re, 'Exception for hashref' );
like( exception { DucktypeTest->new( duck => \'foo' ) }, $re, 'Exception for scalar ref' );

done_testing;