Change and create new constraints with some failing tests
[gitmo/Moose.git] / t / 050_util_type_constraints.t
CommitLineData
a15dff8d 1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
76d37e5a 6use Test::More tests => 25;
a15dff8d 7use Test::Exception;
8
9use Scalar::Util ();
10
11BEGIN {
12 use_ok('Moose::Util::TypeConstraints');
13}
14
15type Num => where { Scalar::Util::looks_like_number($_) };
16type String => where { !ref($_) && !Num($_) };
17
18subtype Natural
19 => as Num
20 => where { $_ > 0 };
21
22subtype NaturalLessThanTen
23 => as Natural
76d37e5a 24 => where { $_ < 10 }
25 => message { "The number '$_' is not less than 10" };
182134e8 26
7c13858b 27Moose::Util::TypeConstraints->export_type_contstraints_as_functions();
a15dff8d 28
29is(Num(5), 5, '... this is a Num');
30ok(!defined(Num('Foo')), '... this is not a Num');
31
a15dff8d 32is(String('Foo'), 'Foo', '... this is a Str');
33ok(!defined(String(5)), '... this is not a Str');
34
a15dff8d 35is(Natural(5), 5, '... this is a Natural');
36is(Natural(-5), undef, '... this is not a Natural');
37is(Natural('Foo'), undef, '... this is not a Natural');
38
a15dff8d 39is(NaturalLessThanTen(5), 5, '... this is a NaturalLessThanTen');
40is(NaturalLessThanTen(12), undef, '... this is not a NaturalLessThanTen');
41is(NaturalLessThanTen(-5), undef, '... this is not a NaturalLessThanTen');
42is(NaturalLessThanTen('Foo'), undef, '... this is not a NaturalLessThanTen');
a15dff8d 43
44# anon sub-typing
45
46my $negative = subtype Num => where { $_ < 0 };
47ok(defined $negative, '... got a value back from negative');
66811d63 48isa_ok($negative, 'Moose::Meta::TypeConstraint');
a15dff8d 49
a27aa600 50is($negative->check(-5), -5, '... this is a negative number');
51ok(!defined($negative->check(5)), '... this is not a negative number');
52is($negative->check('Foo'), undef, '... this is not a negative number');
53
76d37e5a 54# check some meta-details
55
56my $natural_less_than_ten = find_type_constraint('NaturalLessThanTen');
57isa_ok($natural_less_than_ten, 'Moose::Meta::TypeConstraint');
58
59ok($natural_less_than_ten->has_message, '... it has a message');
60
61ok(!defined($natural_less_than_ten->validate(5)), '... validated successfully (no error)');
62
63is($natural_less_than_ten->validate(15),
64 "The number '15' is not less than 10",
65 '... validated unsuccessfully (got error)');
66
67my $natural = find_type_constraint('Natural');
68isa_ok($natural, 'Moose::Meta::TypeConstraint');
69
70ok(!$natural->has_message, '... it does not have a message');
71
72ok(!defined($natural->validate(5)), '... validated successfully (no error)');
73
74is($natural->validate(-5),
75 "Validation failed for 'Natural' failed.",
76 '... validated unsuccessfully (got error)');
a27aa600 77
78