c9d65294c7b78ca5023e8014b8c5baef722d3c8d
[gitmo/Moose.git] / t / 050_util_type_constraints.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 22;
7 use Test::Exception;
8
9 use Scalar::Util ();
10
11 BEGIN {
12     use_ok('Moose::Util::TypeConstraints');           
13 }
14
15 type Num => where { Scalar::Util::looks_like_number($_) };
16 type String => where { !ref($_) && !Num($_) };
17
18 subtype Natural 
19         => as Num 
20         => where { $_ > 0 };
21
22 subtype NaturalLessThanTen 
23         => as Natural
24         => where { $_ < 10 };
25
26 is(Num(5), 5, '... this is a Num');
27 ok(!defined(Num('Foo')), '... this is not a Num');
28
29 is(&Num, &Num, '... the type w/out arguments just returns itself');
30 is(Num(), Num(), '... the type w/out arguments just returns itself');
31
32 is(String('Foo'), 'Foo', '... this is a Str');
33 ok(!defined(String(5)), '... this is not a Str');
34
35 is(&String, &String, '... the type w/out arguments just returns itself');
36
37 is(Natural(5), 5, '... this is a Natural');
38 is(Natural(-5), undef, '... this is not a Natural');
39 is(Natural('Foo'), undef, '... this is not a Natural');
40
41 is(&Natural, &Natural, '... the type w/out arguments just returns itself');
42
43 is(NaturalLessThanTen(5), 5, '... this is a NaturalLessThanTen');
44 is(NaturalLessThanTen(12), undef, '... this is not a NaturalLessThanTen');
45 is(NaturalLessThanTen(-5), undef, '... this is not a NaturalLessThanTen');
46 is(NaturalLessThanTen('Foo'), undef, '... this is not a NaturalLessThanTen');
47
48 is(&NaturalLessThanTen, &NaturalLessThanTen, 
49         '... the type w/out arguments just returns itself');
50         
51 # anon sub-typing       
52         
53 my $negative = subtype Num => where     { $_ < 0 };
54 ok(defined $negative, '... got a value back from negative');
55 is(ref($negative), 'CODE', '... got a type constraint back from negative');
56
57 is($negative->(-5), -5, '... this is a negative number');
58 ok(!defined($negative->(5)), '... this is not a negative number');
59 is($negative->('Foo'), undef, '... this is not a negative number');