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