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