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