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