POD update: METHODS is =head1 (not =head2)
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Test.pm
1 package Catalyst::Test;
2
3 use strict;
4 use warnings;
5 use Test::More ();
6
7 use Catalyst::Exception;
8 use Catalyst::Utils;
9 use Class::MOP;
10 use Sub::Exporter;
11
12 my $build_exports = sub {
13     my ($self, $meth, $args, $defaults) = @_;
14
15     my $request;
16     my $class = $args->{class};
17
18     if ( $ENV{CATALYST_SERVER} ) {
19         $request = sub { remote_request(@_) };
20     } elsif (! $class) {
21         $request = sub { Catalyst::Exception->throw("Must specify a test app: use Catalyst::Test 'TestApp'") };
22     } else {
23         unless (Class::MOP::is_class_loaded($class)) {
24             Class::MOP::load_class($class);
25         }
26         $class->import;
27
28         $request = sub { local_request( $class, @_ ) };
29     }
30
31     my $get = sub { $request->(@_)->content };
32
33     my $ctx_request = sub {
34         my $me      = ref $self || $self;
35
36         ### throw an exception if ctx_request is being used against a remote
37         ### server
38         Catalyst::Exception->throw("$me only works with local requests, not remote")
39             if $ENV{CATALYST_SERVER};
40
41         ### place holder for $c after the request finishes; reset every time
42         ### requests are done.
43         my $c;
44
45         ### hook into 'dispatch' -- the function gets called after all plugins
46         ### have done their work, and it's an easy place to capture $c.
47         no warnings 'redefine';
48         my $dispatch = Catalyst->can('dispatch');
49         local *Catalyst::dispatch = sub {
50             $c = shift;
51             $dispatch->( $c, @_ );
52         };
53
54         ### do the request; C::T::request will know about the class name, and
55         ### we've already stopped it from doing remote requests above.
56         my $res = $request->( @_ );
57
58         ### return both values
59         return ( $res, $c );
60     };
61
62     return {
63         request      => $request,
64         get          => $get,
65         ctx_request  => $ctx_request,
66         content_like => sub {
67             my $action = shift;
68             return Test::More->builder->like($get->($action),@_);
69         },
70         action_ok => sub {
71             my $action = shift;
72             return Test::More->builder->ok($request->($action)->is_success, @_);
73         },
74         action_redirect => sub {
75             my $action = shift;
76             return Test::More->builder->ok($request->($action)->is_redirect,@_);
77         },
78         action_notfound => sub {
79             my $action = shift;
80             return Test::More->builder->is_eq($request->($action)->code,404,@_);
81         },
82         contenttype_is => sub {
83             my $action = shift;
84             my $res = $request->($action);
85             return Test::More->builder->is_eq(scalar($res->content_type),@_);
86         },
87     };
88 };
89
90 our $default_host;
91
92 {
93     my $import = Sub::Exporter::build_exporter({
94         groups => [ all => $build_exports ],
95         into_level => 1,
96     });
97
98
99     sub import {
100         my ($self, $class, $opts) = @_;
101         $import->($self, '-all' => { class => $class });
102         $opts = {} unless ref $opts eq 'HASH';
103         $default_host = $opts->{default_host} if exists $opts->{default_host};
104         return 1;
105     }
106 }
107
108 =head1 NAME
109
110 Catalyst::Test - Test Catalyst Applications
111
112 =head1 SYNOPSIS
113
114     # Helper
115     script/test.pl
116
117     # Tests
118     use Catalyst::Test 'TestApp';
119     my $content  = get('index.html');           # Content as string
120     my $response = request('index.html');       # HTTP::Response object
121     my($res, $c) = ctx_request('index.html');      # HTTP::Response & context object
122
123     use HTTP::Request::Common;
124     my $response = request POST '/foo', [
125         bar => 'baz',
126         something => 'else'
127     ];
128
129     # Run tests against a remote server
130     CATALYST_SERVER='http://localhost:3000/' prove -r -l lib/ t/
131
132     # Tests with inline apps need to use Catalyst::Engine::Test
133     package TestApp;
134
135     use Catalyst;
136
137     sub foo : Global {
138             my ( $self, $c ) = @_;
139             $c->res->output('bar');
140     }
141
142     __PACKAGE__->setup();
143
144     package main;
145
146     use Catalyst::Test 'TestApp';
147     use Test::More tests => 1;
148
149     ok( get('/foo') =~ /bar/ );
150
151     # mock virtual hosts
152     use Catalyst::Test 'MyApp', { default_host => 'myapp.com' };
153     like( get('/whichhost'), qr/served by myapp.com/ );
154     like( get( '/whichhost', { host => 'yourapp.com' } ), qr/served by yourapp.com/ );
155     {
156         local $Catalyst::Test::default_host = 'otherapp.com';
157         like( get('/whichhost'), qr/served by otherapp.com/ );
158     }
159
160 =head1 DESCRIPTION
161
162 This module allows you to make requests to a Catalyst application either without
163 a server, by simulating the environment of an HTTP request using
164 L<HTTP::Request::AsCGI> or remotely if you define the CATALYST_SERVER
165 environment variable. This module also adds a few catalyst
166 specific testing methods as displayed in the method section.
167
168 The L<get> and L<request> functions take either a URI or an L<HTTP::Request>
169 object.
170
171 =head1 METHODS
172
173 =head2 $content = get( ... )
174
175 Returns the content.
176
177     my $content = get('foo/bar?test=1');
178
179 Note that this method doesn't follow redirects, so to test for a
180 correctly redirecting page you'll need to use a combination of this
181 method and the L<request> method below:
182
183     my $res = request('/'); # redirects to /y
184     warn $res->header('location');
185     use URI;
186     my $uri = URI->new($res->header('location'));
187     is ( $uri->path , '/y');
188     my $content = get($uri->path);
189
190 =head2 $res = request( ... );
191
192 Returns a L<HTTP::Response> object. Accepts an optional hashref for request
193 header configuration; currently only supports setting 'host' value.
194
195     my $res = request('foo/bar?test=1');
196     my $virtual_res = request('foo/bar?test=1', {host => 'virtualhost.com'});
197
198 =head1 FUNCTIONS
199
200 =head2 ($res, $c) = ctx_request( ... );
201
202 Works exactly like L<request>, except it also returns the Catalyst context object,
203 C<$c>. Note that this only works for local requests.
204
205 =head2 $res = Catalyst::Test::local_request( $AppClass, $url );
206
207 Simulate a request using L<HTTP::Request::AsCGI>.
208
209 =cut
210
211 sub local_request {
212     my $class = shift;
213
214     require HTTP::Request::AsCGI;
215
216     my $request = Catalyst::Utils::request( shift(@_) );
217     _customize_request($request, @_);
218     my $cgi     = HTTP::Request::AsCGI->new( $request, %ENV )->setup;
219
220     $class->handle_request;
221
222     return $cgi->restore->response;
223 }
224
225 my $agent;
226
227 =head2 $res = Catalyst::Test::remote_request( $url );
228
229 Do an actual remote request using LWP.
230
231 =cut
232
233 sub remote_request {
234
235     require LWP::UserAgent;
236
237     my $request = Catalyst::Utils::request( shift(@_) );
238     my $server  = URI->new( $ENV{CATALYST_SERVER} );
239
240     _customize_request($request, @_);
241
242     if ( $server->path =~ m|^(.+)?/$| ) {
243         my $path = $1;
244         $server->path("$path") if $path;    # need to be quoted
245     }
246
247     # the request path needs to be sanitised if $server is using a
248     # non-root path due to potential overlap between request path and
249     # response path.
250     if ($server->path) {
251         # If request path is '/', we have to add a trailing slash to the
252         # final request URI
253         my $add_trailing = $request->uri->path eq '/';
254         
255         my @sp = split '/', $server->path;
256         my @rp = split '/', $request->uri->path;
257         shift @sp;shift @rp; # leading /
258         if (@rp) {
259             foreach my $sp (@sp) {
260                 $sp eq $rp[0] ? shift @rp : last
261             }
262         }
263         $request->uri->path(join '/', @rp);
264         
265         if ( $add_trailing ) {
266             $request->uri->path( $request->uri->path . '/' );
267         }
268     }
269
270     $request->uri->scheme( $server->scheme );
271     $request->uri->host( $server->host );
272     $request->uri->port( $server->port );
273     $request->uri->path( $server->path . $request->uri->path );
274
275     unless ($agent) {
276
277         $agent = LWP::UserAgent->new(
278             keep_alive   => 1,
279             max_redirect => 0,
280             timeout      => 60,
281             
282             # work around newer LWP max_redirect 0 bug
283             # http://rt.cpan.org/Ticket/Display.html?id=40260
284             requests_redirectable => [],
285         );
286
287         $agent->env_proxy;
288     }
289
290     return $agent->request($request);
291 }
292
293 sub _customize_request {
294     my $request = shift;
295     my $opts = pop(@_) || {};
296     $opts = {} unless ref($opts) eq 'HASH';
297     if ( my $host = exists $opts->{host} ? $opts->{host} : $default_host  ) {
298         $request->header( 'Host' => $host );
299     }
300 }
301
302 =head2 action_ok
303
304 Fetches the given URL and check that the request was successful
305
306 =head2 action_redirect
307
308 Fetches the given URL and check that the request was a redirect
309
310 =head2 action_notfound
311
312 Fetches the given URL and check that the request was not found
313
314 =head2 content_like
315
316 Fetches the given URL and matches the content against it.
317
318 =head2 contenttype_is 
319     
320 Check for given MIME type
321
322 =head1 SEE ALSO
323
324 L<Catalyst>, L<Test::WWW::Mechanize::Catalyst>,
325 L<Test::WWW::Selenium::Catalyst>, L<Test::More>, L<HTTP::Request::Common>
326
327 =head1 AUTHORS
328
329 Catalyst Contributors, see Catalyst.pm
330
331 =head1 COPYRIGHT
332
333 This program is free software, you can redistribute it and/or modify it under
334 the same terms as Perl itself.
335
336 =cut
337
338 1;