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