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