ce4f9b8b94464832d6ae6c37b0e85211a73f9455
[gitmo/MooseX-Getopt.git] / t / 002_custom_option_type.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 31;
7
8 BEGIN {
9     use_ok('MooseX::Getopt');
10 }
11
12 {
13     package App;
14     use Moose;
15     use Moose::Util::TypeConstraints;
16
17     use Scalar::Util 'looks_like_number';
18
19     with 'MooseX::Getopt';
20
21     subtype 'ArrayOfInts'
22         => as 'ArrayRef'
23         => where { scalar (grep { looks_like_number($_) } @$_)  };
24
25     MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
26         'ArrayOfInts' => '=i@'
27     );
28
29     has 'nums' => (
30         is      => 'ro',
31         isa     => 'ArrayOfInts',
32         default => sub { [0] }
33     );
34
35 }
36
37 foreach my $parser_name (qw(MooseX::Getopt::Parser::Long MooseX::Getopt::Parser::Descriptive MooseX::Getopt::Parser::Default)) {
38     SKIP: {
39         if ($parser_name eq 'MooseX::Getopt::Parser::Descriptive') {
40             eval { require Getopt::Long::Descriptive };
41             skip "Getopt::Long::Descriptive not installed", 10 if $@;
42         }
43
44         {
45             local @ARGV = ();
46
47             my $parser = $parser_name->new;
48             ok(ref($parser) =~ /^MooseX::Getopt::Parser::/, '... parser object is created');
49
50             my $getopt = MooseX::Getopt::Session->new( parser => $parser );
51             isa_ok($getopt, 'MooseX::Getopt::Session');
52
53             my $app = App->new_with_options( getopt => $getopt );
54             isa_ok($app, 'App');
55
56             is_deeply($app->nums, [0], '... nums is [0] as expected');
57         }
58
59         {
60             local @ARGV = ('--nums', 3, '--nums', 5);
61
62             my $parser = $parser_name->new;
63             ok(ref($parser) =~ /^MooseX::Getopt::Parser::/, '... parser object is created');
64
65             my $getopt = MooseX::Getopt::Session->new( parser => $parser );
66             isa_ok($getopt, 'MooseX::Getopt::Session');
67
68             my $app = App->new_with_options( getopt => $getopt );
69             isa_ok($app, 'App');
70
71             is_deeply($app->nums, [3, 5], '... nums is [3, 5] as expected');
72         }
73
74         # Make sure it really used our =i@, instead of falling back
75         #  to =s@ via the type system, and test that exceptions work
76         #  while we're at it.
77         eval {
78             local @ARGV = ('--nums', 3, '--nums', 'foo');
79
80             my $parser = $parser_name->new;
81             ok(ref($parser) =~ /^MooseX::Getopt::Parser::/, '... parser object is created');
82
83             my $getopt = MooseX::Getopt::Session->new( parser => $parser );
84             isa_ok($getopt, 'MooseX::Getopt::Session');
85
86             my $app = App->new_with_options( getopt => $getopt );
87         };
88         like($@, qr/Value "foo" invalid/, 'Numeric constraint enforced');
89
90     }
91 }