Doc, add new upgrading caveat, and start what works on Moose docs for lack of a bette...
[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 {
269194b4 34 my $me = ref $self || $self;
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
ba151d0d 52 my $meta = Catalyst->meta;
53 $meta->make_mutable;
54 $meta->add_after_method_modifier( "dispatch", sub {
55 $c = shift;
56 });
57 $meta->make_immutable;
58
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) = @_;
6e6df63d 106 $import->($self, '-all' => { class => $class });
d258fcb2 107 $opts = {} unless ref $opts eq 'HASH';
d9d04ded 108 $default_host = $opts->{default_host} if exists $opts->{default_host};
269194b4 109 return 1;
6e6df63d 110 }
111}
112
fc7ec1d9 113=head1 NAME
114
8d2fa70c 115Catalyst::Test - Test Catalyst Applications
fc7ec1d9 116
117=head1 SYNOPSIS
118
49faa307 119 # Helper
49faa307 120 script/test.pl
121
fc7ec1d9 122 # Tests
123 use Catalyst::Test 'TestApp';
26dd6d9f 124 my $content = get('index.html'); # Content as string
125 my $response = request('index.html'); # HTTP::Response object
4fbc0e85 126 my($res, $c) = ctx_request('index.html'); # HTTP::Response & context object
fc7ec1d9 127
2f381252 128 use HTTP::Request::Common;
129 my $response = request POST '/foo', [
130 bar => 'baz',
131 something => 'else'
132 ];
133
45374ac6 134 # Run tests against a remote server
21465c88 135 CATALYST_SERVER='http://localhost:3000/' prove -r -l lib/ t/
45374ac6 136
b6898a9f 137 # Tests with inline apps need to use Catalyst::Engine::Test
138 package TestApp;
139
8d2fa70c 140 use Catalyst;
b6898a9f 141
c46c32fa 142 sub foo : Global {
b6898a9f 143 my ( $self, $c ) = @_;
144 $c->res->output('bar');
c46c32fa 145 }
146
147 __PACKAGE__->setup();
b6898a9f 148
149 package main;
150
b6898a9f 151 use Catalyst::Test 'TestApp';
e8d0f69a 152 use Test::More tests => 1;
b6898a9f 153
154 ok( get('/foo') =~ /bar/ );
155
d9d04ded 156 # mock virtual hosts
157 use Catalyst::Test 'MyApp', { default_host => 'myapp.com' };
158 like( get('/whichhost'), qr/served by myapp.com/ );
159 like( get( '/whichhost', { host => 'yourapp.com' } ), qr/served by yourapp.com/ );
160 {
161 local $Catalyst::Test::default_host = 'otherapp.com';
162 like( get('/whichhost'), qr/served by otherapp.com/ );
163 }
164
fc7ec1d9 165=head1 DESCRIPTION
166
2f381252 167This module allows you to make requests to a Catalyst application either without
168a server, by simulating the environment of an HTTP request using
169L<HTTP::Request::AsCGI> or remotely if you define the CATALYST_SERVER
e8d0f69a 170environment variable. This module also adds a few catalyst
171specific testing methods as displayed in the method section.
2f381252 172
51a75afc 173The L<get> and L<request> functions take either a URI or an L<HTTP::Request>
2f381252 174object.
fc7ec1d9 175
03f7a71b 176=head1 METHODS
fc7ec1d9 177
26dd6d9f 178=head2 $content = get( ... )
fc7ec1d9 179
180Returns the content.
181
182 my $content = get('foo/bar?test=1');
183
f13fc03f 184Note that this method doesn't follow redirects, so to test for a
185correctly redirecting page you'll need to use a combination of this
186method and the L<request> method below:
187
188 my $res = request('/'); # redirects to /y
189 warn $res->header('location');
190 use URI;
191 my $uri = URI->new($res->header('location'));
192 is ( $uri->path , '/y');
193 my $content = get($uri->path);
194
26dd6d9f 195=head2 $res = request( ... );
fc7ec1d9 196
51a75afc 197Returns a L<HTTP::Response> object. Accepts an optional hashref for request
d9d04ded 198header configuration; currently only supports setting 'host' value.
fc7ec1d9 199
795117cf 200 my $res = request('foo/bar?test=1');
d9d04ded 201 my $virtual_res = request('foo/bar?test=1', {host => 'virtualhost.com'});
fc7ec1d9 202
26dd6d9f 203=head1 FUNCTIONS
204
f2e13bbd 205=head2 ($res, $c) = ctx_request( ... );
26dd6d9f 206
51a75afc 207Works exactly like L<request>, except it also returns the Catalyst context object,
208C<$c>. Note that this only works for local requests.
26dd6d9f 209
26dd6d9f 210=head2 $res = Catalyst::Test::local_request( $AppClass, $url );
0f895006 211
2f381252 212Simulate a request using L<HTTP::Request::AsCGI>.
213
0f895006 214=cut
215
216sub local_request {
217 my $class = shift;
218
219 require HTTP::Request::AsCGI;
220
221 my $request = Catalyst::Utils::request( shift(@_) );
d9d04ded 222 _customize_request($request, @_);
0f895006 223 my $cgi = HTTP::Request::AsCGI->new( $request, %ENV )->setup;
224
225 $class->handle_request;
226
227 return $cgi->restore->response;
228}
229
523d44ec 230my $agent;
231
26dd6d9f 232=head2 $res = Catalyst::Test::remote_request( $url );
bea4160a 233
b77e7869 234Do an actual remote request using LWP.
bea4160a 235
236=cut
237
45374ac6 238sub remote_request {
45374ac6 239
68eb5874 240 require LWP::UserAgent;
241
d837e1a7 242 my $request = Catalyst::Utils::request( shift(@_) );
0f895006 243 my $server = URI->new( $ENV{CATALYST_SERVER} );
523d44ec 244
d9d04ded 245 _customize_request($request, @_);
246
523d44ec 247 if ( $server->path =~ m|^(.+)?/$| ) {
890e8d18 248 my $path = $1;
249 $server->path("$path") if $path; # need to be quoted
f4c0f6f7 250 }
cdae055a 251
252 # the request path needs to be sanitised if $server is using a
253 # non-root path due to potential overlap between request path and
254 # response path.
255 if ($server->path) {
f4c0f6f7 256 # If request path is '/', we have to add a trailing slash to the
257 # final request URI
258 my $add_trailing = $request->uri->path eq '/';
259
cdae055a 260 my @sp = split '/', $server->path;
261 my @rp = split '/', $request->uri->path;
262 shift @sp;shift @rp; # leading /
263 if (@rp) {
264 foreach my $sp (@sp) {
a7daf37e 265 $sp eq $rp[0] ? shift @rp : last
cdae055a 266 }
267 }
268 $request->uri->path(join '/', @rp);
f4c0f6f7 269
270 if ( $add_trailing ) {
271 $request->uri->path( $request->uri->path . '/' );
272 }
523d44ec 273 }
274
275 $request->uri->scheme( $server->scheme );
276 $request->uri->host( $server->host );
277 $request->uri->port( $server->port );
278 $request->uri->path( $server->path . $request->uri->path );
279
68eb5874 280 unless ($agent) {
9ffadf88 281
d837e1a7 282 $agent = LWP::UserAgent->new(
523d44ec 283 keep_alive => 1,
284 max_redirect => 0,
285 timeout => 60,
d11e0c1d 286
287 # work around newer LWP max_redirect 0 bug
288 # http://rt.cpan.org/Ticket/Display.html?id=40260
289 requests_redirectable => [],
523d44ec 290 );
d837e1a7 291
523d44ec 292 $agent->env_proxy;
293 }
45374ac6 294
295 return $agent->request($request);
fc7ec1d9 296}
297
d9d04ded 298sub _customize_request {
299 my $request = shift;
300 my $opts = pop(@_) || {};
4348c28b 301 $opts = {} unless ref($opts) eq 'HASH';
d9d04ded 302 if ( my $host = exists $opts->{host} ? $opts->{host} : $default_host ) {
303 $request->header( 'Host' => $host );
304 }
305}
306
e8d0f69a 307=head2 action_ok
308
51a75afc 309Fetches the given URL and check that the request was successful
e8d0f69a 310
311=head2 action_redirect
312
51a75afc 313Fetches the given URL and check that the request was a redirect
e8d0f69a 314
315=head2 action_notfound
316
51a75afc 317Fetches the given URL and check that the request was not found
e8d0f69a 318
319=head2 content_like
320
51a75afc 321Fetches the given URL and matches the content against it.
e8d0f69a 322
323=head2 contenttype_is
324
51a75afc 325Check for given MIME type
e8d0f69a 326
fc7ec1d9 327=head1 SEE ALSO
328
2f381252 329L<Catalyst>, L<Test::WWW::Mechanize::Catalyst>,
330L<Test::WWW::Selenium::Catalyst>, L<Test::More>, L<HTTP::Request::Common>
fc7ec1d9 331
2f381252 332=head1 AUTHORS
fc7ec1d9 333
2f381252 334Catalyst Contributors, see Catalyst.pm
fc7ec1d9 335
336=head1 COPYRIGHT
337
338This program is free software, you can redistribute it and/or modify it under
339the same terms as Perl itself.
340
341=cut
342
3431;