Add HEAD requests support to T::Rest
[catagits/Catalyst-Action-REST.git] / t / lib / Test / Rest.pm
1 package Test::Rest;
2
3 use Moose;
4 use namespace::autoclean;
5
6 use LWP::UserAgent;
7 use Params::Validate qw(:all);
8
9 sub new {
10     my $self = shift;
11     my %p    = validate( @_, { 
12             content_type => { type => SCALAR }, 
13         }, 
14     );
15     my $ref  = {
16         'ua'           => LWP::UserAgent->new,
17         'content_type' => $p{'content_type'},
18     };
19     bless $ref, $self;
20 }
21
22 {
23     my @non_data_methods = qw(HEAD GET DELETE OPTIONS);
24     foreach my $method (@non_data_methods) {
25         no strict 'refs';
26         my $sub = lc($method);
27         *$sub = sub {
28             my $self = shift;
29             my %p = validate(
30                 @_,
31                 {
32                     url     => { type => SCALAR },
33                     headers => { type => HASHREF, default => {} },
34                 },
35             );
36             my $req  = HTTP::Request->new( "$method" => $p{'url'} );
37             $req->header( $_ => $p{headers}{$_} ) for keys %{ $p{headers} };
38             $req->content_type( $self->{'content_type'} );
39             return $req;
40         };
41     }
42
43     my @data_methods = qw(PUT POST);
44     foreach my $method (@data_methods) {
45         no strict 'refs';
46         my $sub = lc($method);
47         *{$sub} = sub {
48             my $self = shift;
49             my %p    = validate(
50                 @_,
51                 {
52                     url  => { type => SCALAR },
53                     data => 1,
54                     headers => { type => HASHREF, default => {} },
55                 },
56             );
57             my $req = HTTP::Request->new( "$method" => $p{'url'} );
58             $req->header( $_ => $p{headers}{$_} ) for keys %{ $p{headers} };
59             $req->content_type( $self->{'content_type'} );
60             $req->content_length(
61                 do { use bytes; length( $p{'data'} ) }
62             );
63             $req->content( $p{'data'} );
64             return $req;
65         };
66     }
67 }
68
69 1;
70