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