comment update
[gitmo/MooseX-UndefTolerant.git] / t / constructor.t
CommitLineData
36bf5c4d 1use Test::More tests => 14;
5cc8d5b3 2use Test::Fatal;
5447ee45 3
5cc8d5b3 4{
5 package Foo;
6 use Moose;
7
8 has 'attr1' => (
9 traits => [ qw(MooseX::UndefTolerant::Attribute)],
10 is => 'ro',
11 isa => 'Num',
36bf5c4d 12 predicate => 'has_attr1',
5cc8d5b3 13 );
5447ee45 14
5cc8d5b3 15 has 'attr2' => (
16 is => 'ro',
17 isa => 'Num',
36bf5c4d 18 predicate => 'has_attr2',
5cc8d5b3 19 );
20}
5447ee45 21
5cc8d5b3 22{
23 package Bar;
24 use Moose;
25 use MooseX::UndefTolerant;
26
27 has 'attr1' => (
28 is => 'ro',
29 isa => 'Num',
36bf5c4d 30 predicate => 'has_attr1',
5cc8d5b3 31 );
32 has 'attr2' => (
33 is => 'ro',
34 isa => 'Num',
36bf5c4d 35 predicate => 'has_attr2',
5cc8d5b3 36 );
37}
5447ee45 38
39package main;
40
36bf5c4d 41note 'Constructor behaviour';
42note '';
43
5cc8d5b3 44note '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
5447ee45 51{
5cc8d5b3 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');
5447ee45 56}
57
58{
36bf5c4d 59 my $obj = Foo->new(attr1 => 1234, attr2 => 5678);
5cc8d5b3 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');
36bf5c4d 62 is($obj->attr2, 5678, 'assigning a defined value during construction works as normal');
63 ok($obj->has_attr2, '...and the predicate returns true as normal');
5447ee45 64}
65
5cc8d5b3 66
67note '';
68note 'Testing class with the entire class being UndefTolerant';
5447ee45 69{
5cc8d5b3 70 my $obj = Bar->new;
71 ok(!$obj->has_attr1, 'attr1 has no value before it is assigned');
5447ee45 72}
73
efcfddbd 74{
5cc8d5b3 75 my $obj = Bar->new(attr1 => undef);
76 ok(!$obj->has_attr1, 'attr1 has no value when assigned undef in constructor');
77 ok (!exception { $obj = Bar->new(attr2 => undef) },
78 'assigning undef to attr2 does not produce an error');
79 ok(!$obj->has_attr2, 'attr2 has no value when assigned undef in constructor');
efcfddbd 80}
5447ee45 81
5cc8d5b3 82{
83 my $obj = Bar->new(attr1 => 1234);
84 is($obj->attr1, 1234, 'assigning a defined value during construction works as normal');
85 ok($obj->has_attr1, '...and the predicate returns true as normal');
86}
87
88