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