Add the test from r9505, move the new method out of the POD where patch put it, and...
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Test.pm
CommitLineData
fc7ec1d9 1package Catalyst::Test;
2
d9d04ded 3use strict;
4use warnings;
b474372a 5use Test::More ();
e8d0f69a 6
a2f2cde9 7use Catalyst::Exception;
d837e1a7 8use Catalyst::Utils;
7dd4f037 9use Class::MOP;
87cbe5e6 10use Sub::Exporter;
11
e0a78010 12my $build_exports = sub {
87cbe5e6 13 my ($self, $meth, $args, $defaults) = @_;
e8d0f69a 14
87cbe5e6 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 {
7dd4f037 23 unless (Class::MOP::is_class_loaded($class)) {
24 Class::MOP::load_class($class);
87cbe5e6 25 }
26 $class->import;
27
28 $request = sub { local_request( $class, @_ ) };
29 }
30
31 my $get = sub { $request->(@_)->content };
32
269194b4 33 my $crequest = sub {
34 my $me = ref $self || $self;
35
36 ### throw an exception if crequest 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
87cbe5e6 62 return {
269194b4 63 request => $request,
64 get => $get,
65 crequest => $crequest,
87cbe5e6 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 };
e0a78010 88};
e8d0f69a 89
d9d04ded 90our $default_host;
6e6df63d 91
92{
93 my $import = Sub::Exporter::build_exporter({
e0a78010 94 groups => [ all => $build_exports ],
6e6df63d 95 into_level => 1,
96 });
97
d9d04ded 98
6e6df63d 99 sub import {
d9d04ded 100 my ($self, $class, $opts) = @_;
6e6df63d 101 $import->($self, '-all' => { class => $class });
d258fcb2 102 $opts = {} unless ref $opts eq 'HASH';
d9d04ded 103 $default_host = $opts->{default_host} if exists $opts->{default_host};
269194b4 104 return 1;
6e6df63d 105 }
106}
107
fc7ec1d9 108=head1 NAME
109
8d2fa70c 110Catalyst::Test - Test Catalyst Applications
fc7ec1d9 111
112=head1 SYNOPSIS
113
49faa307 114 # Helper
49faa307 115 script/test.pl
116
fc7ec1d9 117 # Tests
118 use Catalyst::Test 'TestApp';
26dd6d9f 119 my $content = get('index.html'); # Content as string
120 my $response = request('index.html'); # HTTP::Response object
121 my($res, $c) = crequest('index.html'); # HTTP::Response & context object
fc7ec1d9 122
2f381252 123 use HTTP::Request::Common;
124 my $response = request POST '/foo', [
125 bar => 'baz',
126 something => 'else'
127 ];
128
45374ac6 129 # Run tests against a remote server
21465c88 130 CATALYST_SERVER='http://localhost:3000/' prove -r -l lib/ t/
45374ac6 131
b6898a9f 132 # Tests with inline apps need to use Catalyst::Engine::Test
133 package TestApp;
134
8d2fa70c 135 use Catalyst;
b6898a9f 136
c46c32fa 137 sub foo : Global {
b6898a9f 138 my ( $self, $c ) = @_;
139 $c->res->output('bar');
c46c32fa 140 }
141
142 __PACKAGE__->setup();
b6898a9f 143
144 package main;
145
b6898a9f 146 use Catalyst::Test 'TestApp';
e8d0f69a 147 use Test::More tests => 1;
b6898a9f 148
149 ok( get('/foo') =~ /bar/ );
150
d9d04ded 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
fc7ec1d9 160=head1 DESCRIPTION
161
2f381252 162This module allows you to make requests to a Catalyst application either without
163a server, by simulating the environment of an HTTP request using
164L<HTTP::Request::AsCGI> or remotely if you define the CATALYST_SERVER
e8d0f69a 165environment variable. This module also adds a few catalyst
166specific testing methods as displayed in the method section.
2f381252 167
168The </get> and </request> functions take either a URI or an L<HTTP::Request>
169object.
fc7ec1d9 170
171=head2 METHODS
172
26dd6d9f 173=head2 $content = get( ... )
fc7ec1d9 174
175Returns the content.
176
177 my $content = get('foo/bar?test=1');
178
f13fc03f 179Note that this method doesn't follow redirects, so to test for a
180correctly redirecting page you'll need to use a combination of this
181method 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
26dd6d9f 190=head2 $res = request( ... );
fc7ec1d9 191
d9d04ded 192Returns a C<HTTP::Response> object. Accepts an optional hashref for request
193header configuration; currently only supports setting 'host' value.
fc7ec1d9 194
795117cf 195 my $res = request('foo/bar?test=1');
d9d04ded 196 my $virtual_res = request('foo/bar?test=1', {host => 'virtualhost.com'});
fc7ec1d9 197
26dd6d9f 198=head1 FUNCTIONS
199
200=head2 ($res, $c) = crequest( ... );
201
202Works exactly like C<Catalyst::Test::request>, except it also returns the
203catalyst context object, C<$c>. Note that this only works for local requests.
204
26dd6d9f 205=head2 $res = Catalyst::Test::local_request( $AppClass, $url );
0f895006 206
2f381252 207Simulate a request using L<HTTP::Request::AsCGI>.
208
0f895006 209=cut
210
211sub local_request {
212 my $class = shift;
213
214 require HTTP::Request::AsCGI;
215
216 my $request = Catalyst::Utils::request( shift(@_) );
d9d04ded 217 _customize_request($request, @_);
0f895006 218 my $cgi = HTTP::Request::AsCGI->new( $request, %ENV )->setup;
219
220 $class->handle_request;
221
222 return $cgi->restore->response;
223}
224
523d44ec 225my $agent;
226
26dd6d9f 227=head2 $res = Catalyst::Test::remote_request( $url );
bea4160a 228
b77e7869 229Do an actual remote request using LWP.
bea4160a 230
231=cut
232
45374ac6 233sub remote_request {
45374ac6 234
68eb5874 235 require LWP::UserAgent;
236
d837e1a7 237 my $request = Catalyst::Utils::request( shift(@_) );
0f895006 238 my $server = URI->new( $ENV{CATALYST_SERVER} );
523d44ec 239
d9d04ded 240 _customize_request($request, @_);
241
523d44ec 242 if ( $server->path =~ m|^(.+)?/$| ) {
890e8d18 243 my $path = $1;
244 $server->path("$path") if $path; # need to be quoted
f4c0f6f7 245 }
cdae055a 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) {
f4c0f6f7 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
cdae055a 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) {
a7daf37e 260 $sp eq $rp[0] ? shift @rp : last
cdae055a 261 }
262 }
263 $request->uri->path(join '/', @rp);
f4c0f6f7 264
265 if ( $add_trailing ) {
266 $request->uri->path( $request->uri->path . '/' );
267 }
523d44ec 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
68eb5874 275 unless ($agent) {
9ffadf88 276
d837e1a7 277 $agent = LWP::UserAgent->new(
523d44ec 278 keep_alive => 1,
279 max_redirect => 0,
280 timeout => 60,
d11e0c1d 281
282 # work around newer LWP max_redirect 0 bug
283 # http://rt.cpan.org/Ticket/Display.html?id=40260
284 requests_redirectable => [],
523d44ec 285 );
d837e1a7 286
523d44ec 287 $agent->env_proxy;
288 }
45374ac6 289
290 return $agent->request($request);
fc7ec1d9 291}
292
d9d04ded 293sub _customize_request {
294 my $request = shift;
295 my $opts = pop(@_) || {};
4348c28b 296 $opts = {} unless ref($opts) eq 'HASH';
d9d04ded 297 if ( my $host = exists $opts->{host} ? $opts->{host} : $default_host ) {
298 $request->header( 'Host' => $host );
299 }
300}
301
e8d0f69a 302=head2 action_ok
303
304Fetches the given url and check that the request was successful
305
306=head2 action_redirect
307
308Fetches the given url and check that the request was a redirect
309
310=head2 action_notfound
311
312Fetches the given url and check that the request was not found
313
314=head2 content_like
315
316Fetches the given url and matches the content against it.
317
318=head2 contenttype_is
319
320Check for given mime type
321
fc7ec1d9 322=head1 SEE ALSO
323
2f381252 324L<Catalyst>, L<Test::WWW::Mechanize::Catalyst>,
325L<Test::WWW::Selenium::Catalyst>, L<Test::More>, L<HTTP::Request::Common>
fc7ec1d9 326
2f381252 327=head1 AUTHORS
fc7ec1d9 328
2f381252 329Catalyst Contributors, see Catalyst.pm
fc7ec1d9 330
331=head1 COPYRIGHT
332
333This program is free software, you can redistribute it and/or modify it under
334the same terms as Perl itself.
335
336=cut
337
3381;