Merge branch 'master' into psgi
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Test.pm
1 package Catalyst::Test;
2
3 use strict;
4 use warnings;
5 use Test::More ();
6
7 use Plack::Test;
8 use Catalyst::Exception;
9 use Catalyst::Utils;
10 use Class::MOP;
11 use Sub::Exporter;
12 use Carp;
13
14 my $build_exports = sub {
15     my ($self, $meth, $args, $defaults) = @_;
16
17     my $request;
18     my $class = $args->{class};
19
20     if ( $ENV{CATALYST_SERVER} ) {
21         $request = sub { remote_request(@_) };
22     } elsif (!$class) {
23         $request = sub { croak "Must specify a test app: use Catalyst::Test 'TestApp'"; }
24     } else {
25         unless (Class::MOP::is_class_loaded($class)) {
26             Class::MOP::load_class($class);
27         }
28         $class->import;
29
30         my $app = $class->psgi_app;
31
32         $request = sub { local_request( $app, @_ ) };
33     }
34
35     my $get = sub { $request->(@_)->content };
36
37     my $ctx_request = sub {
38         my $me = ref $self || $self;
39
40         ### throw an exception if ctx_request is being used against a remote
41         ### server
42         Catalyst::Exception->throw("$me only works with local requests, not remote")
43             if $ENV{CATALYST_SERVER};
44
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
49         ### place holder for $c after the request finishes; reset every time
50         ### requests are done.
51         my $c;
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.
55
56         my $meta = Class::MOP::get_metaclass_by_name($class);
57         $meta->make_mutable;
58         $meta->add_after_method_modifier( "dispatch", sub {
59             $c = shift;
60         });
61         $meta->make_immutable( replace_constructor => 1 );
62         Class::C3::reinitialize(); # Fixes RT#46459, I've failed to write a test for how/why, but it does.
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
67         ### return both values
68         return ( $res, $c );
69     };
70
71     return {
72         request      => $request,
73         get          => $get,
74         ctx_request  => $ctx_request,
75         content_like => sub {
76             my $action = shift;
77             return Test::More->builder->like($get->($action),@_);
78         },
79         action_ok => sub {
80             my $action = shift;
81             return Test::More->builder->ok($request->($action)->is_success, @_);
82         },
83         action_redirect => sub {
84             my $action = shift;
85             return Test::More->builder->ok($request->($action)->is_redirect,@_);
86         },
87         action_notfound => sub {
88             my $action = shift;
89             return Test::More->builder->is_eq($request->($action)->code,404,@_);
90         },
91         contenttype_is => sub {
92             my $action = shift;
93             my $res = $request->($action);
94             return Test::More->builder->is_eq(scalar($res->content_type),@_);
95         },
96     };
97 };
98
99 our $default_host;
100
101 {
102     my $import = Sub::Exporter::build_exporter({
103         groups => [ all => $build_exports ],
104         into_level => 1,
105     });
106
107
108     sub import {
109         my ($self, $class, $opts) = @_;
110         Carp::carp(
111 qq{Importing Catalyst::Test without an application name is deprecated:\n
112 Instead of saying: use Catalyst::Test;
113 say: use Catalyst::Test (); # If you don't want to import a test app right now.
114 or say: use Catalyst::Test 'MyApp'; # If you do want to import a test app.\n\n})
115         unless $class;
116         $import->($self, '-all' => { class => $class });
117         $opts = {} unless ref $opts eq 'HASH';
118         $default_host = $opts->{default_host} if exists $opts->{default_host};
119         return 1;
120     }
121 }
122
123 =head1 NAME
124
125 Catalyst::Test - Test Catalyst Applications
126
127 =head1 SYNOPSIS
128
129     # Helper
130     script/test.pl
131
132     # Tests
133     use Catalyst::Test 'TestApp';
134     my $content  = get('index.html');           # Content as string
135     my $response = request('index.html');       # HTTP::Response object
136     my($res, $c) = ctx_request('index.html');      # HTTP::Response & context object
137
138     use HTTP::Request::Common;
139     my $response = request POST '/foo', [
140         bar => 'baz',
141         something => 'else'
142     ];
143
144     # Run tests against a remote server
145     CATALYST_SERVER='http://localhost:3000/' prove -r -l lib/ t/
146
147     use Catalyst::Test 'TestApp';
148     use Test::More tests => 1;
149
150     ok( get('/foo') =~ /bar/ );
151
152     # mock virtual hosts
153     use Catalyst::Test 'MyApp', { default_host => 'myapp.com' };
154     like( get('/whichhost'), qr/served by myapp.com/ );
155     like( get( '/whichhost', { host => 'yourapp.com' } ), qr/served by yourapp.com/ );
156     {
157         local $Catalyst::Test::default_host = 'otherapp.com';
158         like( get('/whichhost'), qr/served by otherapp.com/ );
159     }
160
161 =head1 DESCRIPTION
162
163 This module allows you to make requests to a Catalyst application either without
164 a server, by simulating the environment of an HTTP request using
165 L<HTTP::Request::AsCGI> or remotely if you define the CATALYST_SERVER
166 environment variable. This module also adds a few Catalyst-specific
167 testing methods as displayed in the method section.
168
169 The L<get|/"$content = get( ... )"> and L<request|/"$res = request( ... );">
170 functions take either a URI or an L<HTTP::Request> object.
171
172 =head1 INLINE TESTS WILL NO LONGER WORK
173
174 While it used to be possible to inline a whole testapp into a C<.t> file for a
175 distribution, this will no longer work.
176
177 The convention is to place your L<Catalyst> test apps into C<t/lib> in your
178 distribution. E.g.: C<t/lib/TestApp.pm>, C<t/lib/TestApp/Controller/Root.pm>,
179 etc..  Multiple test apps can be used in this way.
180
181 Then write your C<.t> files like so:
182
183     use strict;
184     use warnings;
185     use FindBin '$Bin';
186     use lib "$Bin/lib";
187     use Test::More tests => 6;
188     use Catalyst::Test 'TestApp';
189
190 =head1 METHODS
191
192 =head2 $content = get( ... )
193
194 Returns the content.
195
196     my $content = get('foo/bar?test=1');
197
198 Note that this method doesn't follow redirects, so to test for a
199 correctly redirecting page you'll need to use a combination of this
200 method and the L<request|/"$res = request( ... );"> method below:
201
202     my $res = request('/'); # redirects to /y
203     warn $res->header('location');
204     use URI;
205     my $uri = URI->new($res->header('location'));
206     is ( $uri->path , '/y');
207     my $content = get($uri->path);
208
209 =head2 $res = request( ... );
210
211 Returns an L<HTTP::Response> object. Accepts an optional hashref for request
212 header configuration; currently only supports setting 'host' value.
213
214     my $res = request('foo/bar?test=1');
215     my $virtual_res = request('foo/bar?test=1', {host => 'virtualhost.com'});
216
217 =head1 FUNCTIONS
218
219 =head2 ($res, $c) = ctx_request( ... );
220
221 Works exactly like L<request|/"$res = request( ... );">, except it also returns the Catalyst context object,
222 C<$c>. Note that this only works for local requests.
223
224 =head2 $res = Catalyst::Test::local_request( $AppClass, $url );
225
226 Simulate a request using L<HTTP::Request::AsCGI>.
227
228 =cut
229
230 sub local_request {
231     my $app = shift;
232
233     my $request = Catalyst::Utils::request(shift);
234     my %extra_env;
235     _customize_request($request, \%extra_env, @_);
236
237     my $ret;
238     test_psgi
239         app    => sub { $app->({ %{ $_[0] }, %extra_env }) },
240         client => sub { $ret = shift->($request) };
241
242     return $ret;
243 }
244
245 my $agent;
246
247 =head2 $res = Catalyst::Test::remote_request( $url );
248
249 Do an actual remote request using LWP.
250
251 =cut
252
253 sub remote_request {
254
255     require LWP::UserAgent;
256
257     my $request = Catalyst::Utils::request( shift(@_) );
258     my $server  = URI->new( $ENV{CATALYST_SERVER} );
259
260     _customize_request($request, @_);
261
262     if ( $server->path =~ m|^(.+)?/$| ) {
263         my $path = $1;
264         $server->path("$path") if $path;    # need to be quoted
265     }
266
267     # the request path needs to be sanitised if $server is using a
268     # non-root path due to potential overlap between request path and
269     # response path.
270     if ($server->path) {
271         # If request path is '/', we have to add a trailing slash to the
272         # final request URI
273         my $add_trailing = $request->uri->path eq '/';
274
275         my @sp = split '/', $server->path;
276         my @rp = split '/', $request->uri->path;
277         shift @sp;shift @rp; # leading /
278         if (@rp) {
279             foreach my $sp (@sp) {
280                 $sp eq $rp[0] ? shift @rp : last
281             }
282         }
283         $request->uri->path(join '/', @rp);
284
285         if ( $add_trailing ) {
286             $request->uri->path( $request->uri->path . '/' );
287         }
288     }
289
290     $request->uri->scheme( $server->scheme );
291     $request->uri->host( $server->host );
292     $request->uri->port( $server->port );
293     $request->uri->path( $server->path . $request->uri->path );
294
295     unless ($agent) {
296
297         $agent = LWP::UserAgent->new(
298             keep_alive   => 1,
299             max_redirect => 0,
300             timeout      => 60,
301
302             # work around newer LWP max_redirect 0 bug
303             # http://rt.cpan.org/Ticket/Display.html?id=40260
304             requests_redirectable => [],
305         );
306
307         $agent->env_proxy;
308     }
309
310     return $agent->request($request);
311 }
312
313 sub _customize_request {
314     my $request = shift;
315     my $extra_env = shift;
316     my $opts = pop(@_) || {};
317     $opts = {} unless ref($opts) eq 'HASH';
318     if ( my $host = exists $opts->{host} ? $opts->{host} : $default_host  ) {
319         $request->header( 'Host' => $host );
320     }
321
322     if (my $extra = $opts->{extra_env}) {
323         @{ $extra_env }{keys %{ $extra }} = values %{ $extra };
324     }
325 }
326
327 =head2 action_ok
328
329 Fetches the given URL and checks that the request was successful.
330
331 =head2 action_redirect
332
333 Fetches the given URL and checks that the request was a redirect.
334
335 =head2 action_notfound
336
337 Fetches the given URL and checks that the request was not found.
338
339 =head2 content_like( $url, $regexp [, $test_name] )
340
341 Fetches the given URL and returns whether the content matches the regexp.
342
343 =head2 contenttype_is
344
345 Check for given MIME type.
346
347 =head1 SEE ALSO
348
349 L<Catalyst>, L<Test::WWW::Mechanize::Catalyst>,
350 L<Test::WWW::Selenium::Catalyst>, L<Test::More>, L<HTTP::Request::Common>
351
352 =head1 AUTHORS
353
354 Catalyst Contributors, see Catalyst.pm
355
356 =head1 COPYRIGHT
357
358 This library is free software. You can redistribute it and/or modify it under
359 the same terms as Perl itself.
360
361 =cut
362
363 1;