02e46fcbe940c7270ee4098cf504df54d7086344
[p5sagit/Function-Parameters.git] / t / types_custom.t
1 #!perl
2 use warnings FATAL => 'all';
3 use strict;
4
5 use Test::More tests => 8;
6 use Test::Fatal;
7
8 use Function::Parameters qw(:strict);
9 use Function::Parameters {
10         def => { check_argument_count => 1 },
11 };
12
13 {
14         package MyTC;
15
16         method new(
17                 $class:
18                 $name,
19                 $check,
20                 $get_message = fun ($value) {
21                         "Validation failed for constraint '$name' with value '$value'"
22                 },
23         ) {
24                 bless {
25                         name => $name,
26                         check => $check,
27                         get_message => $get_message,
28                 }, $class
29         }
30
31         method check($value) {
32                 $self->{check}($value)
33         }
34
35         method get_message($value) {
36                 $self->{get_message}($value)
37         }
38 }
39
40 use constant {
41         TEvenNum  => MyTC->new('even number'  => fun ($n) { $n =~ /^[0-9]+\z/ && $n % 2 == 0 }),
42         TShortStr => MyTC->new('short string' => fun ($s) { length($s) < 10 }),
43 };
44
45 fun foo((TEvenNum) $x, (TShortStr) $y) {
46         "$x/$y"
47 }
48
49 is foo(42, "hello"), "42/hello";
50 like exception { foo 41, "hello" },       qr{\bValidation failed for constraint 'even number' with value '41'};
51 like exception { foo 42, "1234567890~" }, qr{\bValidation failed for constraint 'short string' with value '1234567890~'};
52 like exception { foo 41, "1234567890~" }, qr{\bValidation failed for constraint 'even number' with value '41'};
53
54 def foo2((TEvenNum) $x, (TShortStr) $y) {
55         "$x/$y"
56 }
57
58 is foo2(42, "hello"), "42/hello";
59 like exception { foo2 41, "hello" },       qr{\bValidation failed for constraint 'even number' with value '41'};
60 like exception { foo2 42, "1234567890~" }, qr{\bValidation failed for constraint 'short string' with value '1234567890~'};
61 like exception { foo2 41, "1234567890~" }, qr{\bValidation failed for constraint 'even number' with value '41'};