Require Dist::Zilla 4.200016+
[gitmo/Moose.git] / t / attributes / attribute_type_unions.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7 use Test::Fatal;
8
9
10 {
11     package Foo;
12     use Moose;
13
14     has 'bar' => (is => 'rw', isa => 'ArrayRef | HashRef');
15 }
16
17 my $foo = Foo->new;
18 isa_ok($foo, 'Foo');
19
20 is( exception {
21     $foo->bar([])
22 }, undef, '... set bar successfully with an ARRAY ref' );
23
24 is( exception {
25     $foo->bar({})
26 }, undef, '... set bar successfully with a HASH ref' );
27
28 isnt( exception {
29     $foo->bar(100)
30 }, undef, '... couldnt set bar successfully with a number' );
31
32 isnt( exception {
33     $foo->bar(sub {})
34 }, undef, '... couldnt set bar successfully with a CODE ref' );
35
36 # check the constructor
37
38 is( exception {
39     Foo->new(bar => [])
40 }, undef, '... created new Foo with bar successfully set with an ARRAY ref' );
41
42 is( exception {
43     Foo->new(bar => {})
44 }, undef, '... created new Foo with bar successfully set with a HASH ref' );
45
46 isnt( exception {
47     Foo->new(bar => 50)
48 }, undef, '... didnt create a new Foo with bar as a number' );
49
50 isnt( exception {
51     Foo->new(bar => sub {})
52 }, undef, '... didnt create a new Foo with bar as a CODE ref' );
53
54 {
55     package Bar;
56     use Moose;
57
58     has 'baz' => (is => 'rw', isa => 'Str | CodeRef');
59 }
60
61 my $bar = Bar->new;
62 isa_ok($bar, 'Bar');
63
64 is( exception {
65     $bar->baz('a string')
66 }, undef, '... set baz successfully with a string' );
67
68 is( exception {
69     $bar->baz(sub { 'a sub' })
70 }, undef, '... set baz successfully with a CODE ref' );
71
72 isnt( exception {
73     $bar->baz(\(my $var1))
74 }, undef, '... couldnt set baz successfully with a SCALAR ref' );
75
76 isnt( exception {
77     $bar->baz({})
78 }, undef, '... couldnt set bar successfully with a HASH ref' );
79
80 # check the constructor
81
82 is( exception {
83     Bar->new(baz => 'a string')
84 }, undef, '... created new Bar with baz successfully set with a string' );
85
86 is( exception {
87     Bar->new(baz => sub { 'a sub' })
88 }, undef, '... created new Bar with baz successfully set with a CODE ref' );
89
90 isnt( exception {
91     Bar->new(baz => \(my $var2))
92 }, undef, '... didnt create a new Bar with baz as a number' );
93
94 isnt( exception {
95     Bar->new(baz => {})
96 }, undef, '... didnt create a new Bar with baz as a HASH ref' );
97
98 done_testing;