1 package Catalyst::Test;
8 use Catalyst::Exception;
14 my $build_exports = sub {
15 my ($self, $meth, $args, $defaults) = @_;
18 my $class = $args->{class};
20 if ( $ENV{CATALYST_SERVER} ) {
21 $request = sub { remote_request(@_) };
23 $request = sub { croak "Must specify a test app: use Catalyst::Test 'TestApp'"; }
25 unless (Class::MOP::is_class_loaded($class)) {
26 Class::MOP::load_class($class);
30 my $app = $class->run;
32 $request = sub { local_request( $app, @_ ) };
35 my $get = sub { $request->(@_)->content };
37 my $ctx_request = sub {
38 my $me = ref $self || $self;
40 ### throw an exception if ctx_request is being used against a remote
42 Catalyst::Exception->throw("$me only works with local requests, not remote")
43 if $ENV{CATALYST_SERVER};
45 ### check explicitly for the class here, or the Cat->meta call will blow
47 Catalyst::Exception->throw("Must specify a test app: use Catalyst::Test 'TestApp'") unless $class;
49 ### place holder for $c after the request finishes; reset every time
50 ### requests are done.
53 ### hook into 'dispatch' -- the function gets called after all plugins
54 ### have done their work, and it's an easy place to capture $c.
56 my $meta = Class::MOP::get_metaclass_by_name($class);
58 $meta->add_after_method_modifier( "dispatch", sub {
61 $meta->make_immutable( replace_constructor => 1 );
62 Class::C3::reinitialize(); # Fixes RT#46459, I've failed to write a test for how/why, but it does.
63 ### do the request; C::T::request will know about the class name, and
64 ### we've already stopped it from doing remote requests above.
65 my $res = $request->( @_ );
67 ### return both values
74 ctx_request => $ctx_request,
77 return Test::More->builder->like($get->($action),@_);
81 return Test::More->builder->ok($request->($action)->is_success, @_);
83 action_redirect => sub {
85 return Test::More->builder->ok($request->($action)->is_redirect,@_);
87 action_notfound => sub {
89 return Test::More->builder->is_eq($request->($action)->code,404,@_);
91 contenttype_is => sub {
93 my $res = $request->($action);
94 return Test::More->builder->is_eq(scalar($res->content_type),@_);
102 my $import = Sub::Exporter::build_exporter({
103 groups => [ all => $build_exports ],
109 my ($self, $class, $opts) = @_;
110 $import->($self, '-all' => { class => $class });
111 $opts = {} unless ref $opts eq 'HASH';
112 $default_host = $opts->{default_host} if exists $opts->{default_host};
119 Catalyst::Test - Test Catalyst Applications
127 use Catalyst::Test 'TestApp';
128 my $content = get('index.html'); # Content as string
129 my $response = request('index.html'); # HTTP::Response object
130 my($res, $c) = ctx_request('index.html'); # HTTP::Response & context object
132 use HTTP::Request::Common;
133 my $response = request POST '/foo', [
138 # Run tests against a remote server
139 CATALYST_SERVER='http://localhost:3000/' prove -r -l lib/ t/
141 use Catalyst::Test 'TestApp';
142 use Test::More tests => 1;
144 ok( get('/foo') =~ /bar/ );
147 use Catalyst::Test 'MyApp', { default_host => 'myapp.com' };
148 like( get('/whichhost'), qr/served by myapp.com/ );
149 like( get( '/whichhost', { host => 'yourapp.com' } ), qr/served by yourapp.com/ );
151 local $Catalyst::Test::default_host = 'otherapp.com';
152 like( get('/whichhost'), qr/served by otherapp.com/ );
157 This module allows you to make requests to a Catalyst application either without
158 a server, by simulating the environment of an HTTP request using
159 L<HTTP::Request::AsCGI> or remotely if you define the CATALYST_SERVER
160 environment variable. This module also adds a few Catalyst-specific
161 testing methods as displayed in the method section.
163 The L<get|/"$content = get( ... )"> and L<request|/"$res = request( ... );">
164 functions take either a URI or an L<HTTP::Request> object.
166 =head1 INLINE TESTS WILL NO LONGER WORK
168 While it used to be possible to inline a whole testapp into a C<.t> file for a
169 distribution, this will no longer work.
171 The convention is to place your L<Catalyst> test apps into C<t/lib> in your
172 distribution. E.g.: C<t/lib/TestApp.pm>, C<t/lib/TestApp/Controller/Root.pm>,
173 etc.. Multiple test apps can be used in this way.
175 Then write your C<.t> files like so:
181 use Test::More tests => 6;
182 use Catalyst::Test 'TestApp';
186 =head2 $content = get( ... )
190 my $content = get('foo/bar?test=1');
192 Note that this method doesn't follow redirects, so to test for a
193 correctly redirecting page you'll need to use a combination of this
194 method and the L<request|/"$res = request( ... );"> method below:
196 my $res = request('/'); # redirects to /y
197 warn $res->header('location');
199 my $uri = URI->new($res->header('location'));
200 is ( $uri->path , '/y');
201 my $content = get($uri->path);
203 =head2 $res = request( ... );
205 Returns an L<HTTP::Response> object. Accepts an optional hashref for request
206 header configuration; currently only supports setting 'host' value.
208 my $res = request('foo/bar?test=1');
209 my $virtual_res = request('foo/bar?test=1', {host => 'virtualhost.com'});
213 =head2 ($res, $c) = ctx_request( ... );
215 Works exactly like L<request|/"$res = request( ... );">, except it also returns the Catalyst context object,
216 C<$c>. Note that this only works for local requests.
218 =head2 $res = Catalyst::Test::local_request( $AppClass, $url );
220 Simulate a request using L<HTTP::Request::AsCGI>.
227 my $request = Catalyst::Utils::request(shift);
228 _customize_request($request, @_);
231 test_psgi app => $app, client => sub { $ret = shift->($request) };
238 =head2 $res = Catalyst::Test::remote_request( $url );
240 Do an actual remote request using LWP.
246 require LWP::UserAgent;
248 my $request = Catalyst::Utils::request( shift(@_) );
249 my $server = URI->new( $ENV{CATALYST_SERVER} );
251 _customize_request($request, @_);
253 if ( $server->path =~ m|^(.+)?/$| ) {
255 $server->path("$path") if $path; # need to be quoted
258 # the request path needs to be sanitised if $server is using a
259 # non-root path due to potential overlap between request path and
262 # If request path is '/', we have to add a trailing slash to the
264 my $add_trailing = $request->uri->path eq '/';
266 my @sp = split '/', $server->path;
267 my @rp = split '/', $request->uri->path;
268 shift @sp;shift @rp; # leading /
270 foreach my $sp (@sp) {
271 $sp eq $rp[0] ? shift @rp : last
274 $request->uri->path(join '/', @rp);
276 if ( $add_trailing ) {
277 $request->uri->path( $request->uri->path . '/' );
281 $request->uri->scheme( $server->scheme );
282 $request->uri->host( $server->host );
283 $request->uri->port( $server->port );
284 $request->uri->path( $server->path . $request->uri->path );
288 $agent = LWP::UserAgent->new(
293 # work around newer LWP max_redirect 0 bug
294 # http://rt.cpan.org/Ticket/Display.html?id=40260
295 requests_redirectable => [],
301 return $agent->request($request);
304 sub _customize_request {
306 my $opts = pop(@_) || {};
307 $opts = {} unless ref($opts) eq 'HASH';
308 if ( my $host = exists $opts->{host} ? $opts->{host} : $default_host ) {
309 $request->header( 'Host' => $host );
315 Fetches the given URL and checks that the request was successful.
317 =head2 action_redirect
319 Fetches the given URL and checks that the request was a redirect.
321 =head2 action_notfound
323 Fetches the given URL and checks that the request was not found.
325 =head2 content_like( $url, $regexp [, $test_name] )
327 Fetches the given URL and returns whether the content matches the regexp.
329 =head2 contenttype_is
331 Check for given MIME type.
335 L<Catalyst>, L<Test::WWW::Mechanize::Catalyst>,
336 L<Test::WWW::Selenium::Catalyst>, L<Test::More>, L<HTTP::Request::Common>
340 Catalyst Contributors, see Catalyst.pm
344 This library is free software. You can redistribute it and/or modify it under
345 the same terms as Perl itself.