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