new .gitignore file, stolen from Moose repo
[gitmo/MooseX-UndefTolerant.git] / t / attribute.t
1 use Test::More tests => 12;
2 use Test::Fatal;
3
4 # TODO: this test should be renamed constructor.t, since all it tests is
5 # UT behaviour during construction.
6
7 {
8     package Foo;
9     use Moose;
10
11     has 'attr1' => (
12         traits => [ qw(MooseX::UndefTolerant::Attribute)],
13         is => 'ro',
14         isa => 'Num',
15         predicate => 'has_attr1'
16     );
17
18     has 'attr2' => (
19         is => 'ro',
20         isa => 'Num',
21         predicate => 'has_attr2'
22     );
23 }
24
25 {
26     package Bar;
27     use Moose;
28     use MooseX::UndefTolerant;
29
30     has 'attr1' => (
31         is => 'ro',
32         isa => 'Num',
33         predicate => 'has_attr1'
34     );
35     has 'attr2' => (
36         is => 'ro',
37         isa => 'Num',
38         predicate => 'has_attr2'
39     );
40 }
41
42 package main;
43
44 note 'Testing class with a single UndefTolerant attribute';
45 {
46     my $obj = Foo->new;
47     ok(!$obj->has_attr1, 'attr1 has no value before it is assigned');
48     ok(!$obj->has_attr2, 'attr2 has no value before it is assigned');
49 }
50
51 {
52     my $obj = Foo->new(attr1 => undef);
53     ok(!$obj->has_attr1, 'UT attr1 has no value when assigned undef in constructor');
54     ok (exception { $obj = Foo->new(attr2 => undef) },
55         'But assigning undef to attr2 generates a type constraint error');
56 }
57
58 {
59     my $obj = Foo->new(attr1 => 1234);
60     is($obj->attr1, 1234, 'assigning a defined value during construction works as normal');
61     ok($obj->has_attr1, '...and the predicate returns true as normal');
62 }
63
64
65 note '';
66 note 'Testing class with the entire class being UndefTolerant';
67 {
68     my $obj = Bar->new;
69     ok(!$obj->has_attr1, 'attr1 has no value before it is assigned');
70 }
71
72 {
73     my $obj = Bar->new(attr1 => undef);
74     ok(!$obj->has_attr1, 'attr1 has no value when assigned undef in constructor');
75     ok (!exception { $obj = Bar->new(attr2 => undef) },
76         'assigning undef to attr2 does not produce an error');
77     ok(!$obj->has_attr2, 'attr2 has no value when assigned undef in constructor');
78 }
79
80 {
81     my $obj = Bar->new(attr1 => 1234);
82     is($obj->attr1, 1234, 'assigning a defined value during construction works as normal');
83     ok($obj->has_attr1, '...and the predicate returns true as normal');
84 }
85
86