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