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