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