make defaults.t a bit more modular
[gitmo/MooseX-UndefTolerant.git] / t / defaults.t
1 use Test::More;
2 use Test::Fatal;
3
4 use MooseX::UndefTolerant::Attribute ();
5
6 {
7     package Foo;
8     use Moose;
9
10     has 'attr1' => (
11         traits => [ qw(MooseX::UndefTolerant::Attribute)],
12         is => 'ro',
13         isa => 'Num',
14         predicate => 'has_attr1',
15         default => 1,
16     );
17     has 'attr2' => (
18         is => 'ro',
19         isa => 'Num',
20         predicate => 'has_attr2',
21         default => 2,
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         default => 1,
35     );
36     has 'attr2' => (
37         is => 'ro',
38         isa => 'Num',
39         predicate => 'has_attr2',
40         default => 2,
41     );
42 }
43
44
45 package main;
46
47 sub do_tests
48 {
49     note 'Testing class with a single UndefTolerant attribute';
50     do_tests_with_class('Foo');
51
52     note '';
53     note 'Testing class with the entire class being UndefTolerant';
54     do_tests_with_class('Bar');
55 }
56
57 sub do_tests_with_class
58 {
59     my $class = shift;
60
61     {
62         my $obj = $class->new;
63         ok($obj->has_attr1, 'attr1 has a value');
64         ok($obj->has_attr2, 'attr2 has a value');
65         is($obj->attr1, 1, 'attr1\'s value is its default');
66         is($obj->attr2, 2, 'attr2\'s value is its default');
67     }
68
69     {
70         my $obj = $class->new(attr1 => undef);
71         ok($obj->has_attr1, 'UT attr1 has a value when assigned undef in constructor');
72         is($obj->attr1, 1, 'attr1\'s value is its default');
73         is($obj->attr2, 2, 'attr2\'s value is its default');
74     }
75
76     {
77         my $obj = $class->new(attr1 => 1234, attr2 => 5678);
78         is($obj->attr1, 1234, 'assigning a defined value during construction works as normal');
79         ok($obj->has_attr1, '...and the predicate returns true as normal');
80         is($obj->attr2, 5678, 'assigning a defined value during construction works as normal');
81         ok($obj->has_attr2, '...and the predicate returns true as normal');
82     }
83 }
84
85 note 'Default behaviour: mutable classes';
86 note '';
87 do_tests;
88
89 note '';
90 note 'Default behaviour: immutable classes';
91 note '';
92 Foo->meta->make_immutable;
93 Bar->meta->make_immutable;
94
95 TODO: {
96     local $TODO = 'some immutable cases are not handled yet';
97     # for now, catch errors
98     ok(! exception { do_tests }, 'tests do not die');
99
100     is(Test::More->builder->current_test, 44, 'if we got here, we can declare victory!');
101 }
102
103 done_testing;
104