Add HEAD requests support to T::Rest
[catagits/Catalyst-Action-REST.git] / t / lib / Test / Rest.pm
CommitLineData
7ad87df9 1package Test::Rest;
2
930013e6 3use Moose;
4use namespace::autoclean;
7ad87df9 5
6use LWP::UserAgent;
7use Params::Validate qw(:all);
8
9sub new {
10 my $self = shift;
e601adda 11 my %p = validate( @_, {
12 content_type => { type => SCALAR },
13 },
14 );
d34c067a 15 my $ref = {
16 'ua' => LWP::UserAgent->new,
7ad87df9 17 'content_type' => $p{'content_type'},
18 };
19 bless $ref, $self;
20}
21
d34c067a 22{
637afb35 23 my @non_data_methods = qw(HEAD GET DELETE OPTIONS);
d34c067a 24 foreach my $method (@non_data_methods) {
25 no strict 'refs';
26 my $sub = lc($method);
27 *$sub = sub {
28 my $self = shift;
bc06b9a3 29 my %p = validate(
30 @_,
31 {
32 url => { type => SCALAR },
33 headers => { type => HASHREF, default => {} },
34 },
35 );
d34c067a 36 my $req = HTTP::Request->new( "$method" => $p{'url'} );
bc06b9a3 37 $req->header( $_ => $p{headers}{$_} ) for keys %{ $p{headers} };
d34c067a 38 $req->content_type( $self->{'content_type'} );
39 return $req;
40 };
41 }
7ad87df9 42
d34c067a 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,
bc06b9a3 54 headers => { type => HASHREF, default => {} },
d34c067a 55 },
56 );
57 my $req = HTTP::Request->new( "$method" => $p{'url'} );
bc06b9a3 58 $req->header( $_ => $p{headers}{$_} ) for keys %{ $p{headers} };
d34c067a 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 }
7ad87df9 67}
68
7ad87df9 691;
70