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