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