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