r49@latte: adam | 2006-12-03 12:30:40 -0800
[catagits/Catalyst-Action-REST.git] / t / lib / Test / Rest.pm
1 #
2 # Rest.pm
3 # Created by: Adam Jacob, Marchex, <adam@marchex.com>
4 # Created on: 10/16/2006 11:11:25 AM PDT
5 #
6 # $Id: $
7
8 package Test::Rest;
9
10 use strict;
11 use warnings;
12
13 use LWP::UserAgent;
14 use Params::Validate qw(:all);
15
16 sub new {
17     my $self = shift;
18     my %p    = validate( @_, { 
19             content_type => { type => SCALAR }, 
20         }, 
21     );
22     my $ref  = {
23         'ua'           => LWP::UserAgent->new,
24         'content_type' => $p{'content_type'},
25     };
26     bless $ref, $self;
27 }
28
29 {
30     my @non_data_methods = qw(GET DELETE OPTIONS);
31     foreach my $method (@non_data_methods) {
32         no strict 'refs';
33         my $sub = lc($method);
34         *$sub = sub {
35             my $self = shift;
36             my %p    = validate( @_, { url => { type => SCALAR }, }, );
37             my $req  = HTTP::Request->new( "$method" => $p{'url'} );
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                 },
55             );
56             my $req = HTTP::Request->new( "$method" => $p{'url'} );
57             $req->content_type( $self->{'content_type'} );
58             $req->content_length(
59                 do { use bytes; length( $p{'data'} ) }
60             );
61             $req->content( $p{'data'} );
62             return $req;
63         };
64     }
65 }
66
67 1;
68