1 package Catalyst::Test;
7 use Catalyst::Exception;
12 my $build_exports = sub {
13 my ($self, $meth, $args, $defaults) = @_;
16 my $class = $args->{class};
18 if ( $ENV{CATALYST_SERVER} ) {
19 $request = sub { remote_request(@_) };
21 $request = sub { Catalyst::Exception->throw("Must specify a test app: use Catalyst::Test 'TestApp'") };
23 unless (Class::MOP::is_class_loaded($class)) {
24 Class::MOP::load_class($class);
28 $request = sub { local_request( $class, @_ ) };
31 my $get = sub { $request->(@_)->content };
33 my $ctx_request = sub {
34 my $me = ref $self || $self;
36 ### throw an exception if ctx_request is being used against a remote
38 Catalyst::Exception->throw("$me only works with local requests, not remote")
39 if $ENV{CATALYST_SERVER};
41 ### place holder for $c after the request finishes; reset every time
42 ### requests are done.
45 ### hook into 'dispatch' -- the function gets called after all plugins
46 ### have done their work, and it's an easy place to capture $c.
47 no warnings 'redefine';
48 my $dispatch = Catalyst->can('dispatch');
49 local *Catalyst::dispatch = sub {
51 $dispatch->( $c, @_ );
54 ### do the request; C::T::request will know about the class name, and
55 ### we've already stopped it from doing remote requests above.
56 my $res = $request->( @_ );
58 ### return both values
65 ctx_request => $ctx_request,
68 return Test::More->builder->like($get->($action),@_);
72 return Test::More->builder->ok($request->($action)->is_success, @_);
74 action_redirect => sub {
76 return Test::More->builder->ok($request->($action)->is_redirect,@_);
78 action_notfound => sub {
80 return Test::More->builder->is_eq($request->($action)->code,404,@_);
82 contenttype_is => sub {
84 my $res = $request->($action);
85 return Test::More->builder->is_eq(scalar($res->content_type),@_);
93 my $import = Sub::Exporter::build_exporter({
94 groups => [ all => $build_exports ],
100 my ($self, $class, $opts) = @_;
101 $import->($self, '-all' => { class => $class });
102 $opts = {} unless ref $opts eq 'HASH';
103 $default_host = $opts->{default_host} if exists $opts->{default_host};
110 Catalyst::Test - Test Catalyst Applications
118 use Catalyst::Test 'TestApp';
119 my $content = get('index.html'); # Content as string
120 my $response = request('index.html'); # HTTP::Response object
121 my($res, $c) = ctx_request('index.html'); # HTTP::Response & context object
123 use HTTP::Request::Common;
124 my $response = request POST '/foo', [
129 # Run tests against a remote server
130 CATALYST_SERVER='http://localhost:3000/' prove -r -l lib/ t/
132 # Tests with inline apps need to use Catalyst::Engine::Test
138 my ( $self, $c ) = @_;
139 $c->res->output('bar');
142 __PACKAGE__->setup();
146 use Catalyst::Test 'TestApp';
147 use Test::More tests => 1;
149 ok( get('/foo') =~ /bar/ );
152 use Catalyst::Test 'MyApp', { default_host => 'myapp.com' };
153 like( get('/whichhost'), qr/served by myapp.com/ );
154 like( get( '/whichhost', { host => 'yourapp.com' } ), qr/served by yourapp.com/ );
156 local $Catalyst::Test::default_host = 'otherapp.com';
157 like( get('/whichhost'), qr/served by otherapp.com/ );
162 This module allows you to make requests to a Catalyst application either without
163 a server, by simulating the environment of an HTTP request using
164 L<HTTP::Request::AsCGI> or remotely if you define the CATALYST_SERVER
165 environment variable. This module also adds a few catalyst
166 specific testing methods as displayed in the method section.
168 The </get> and </request> functions take either a URI or an L<HTTP::Request>
173 =head2 $content = get( ... )
177 my $content = get('foo/bar?test=1');
179 Note that this method doesn't follow redirects, so to test for a
180 correctly redirecting page you'll need to use a combination of this
181 method and the L<request> method below:
183 my $res = request('/'); # redirects to /y
184 warn $res->header('location');
186 my $uri = URI->new($res->header('location'));
187 is ( $uri->path , '/y');
188 my $content = get($uri->path);
190 =head2 $res = request( ... );
192 Returns a C<HTTP::Response> object. Accepts an optional hashref for request
193 header configuration; currently only supports setting 'host' value.
195 my $res = request('foo/bar?test=1');
196 my $virtual_res = request('foo/bar?test=1', {host => 'virtualhost.com'});
200 =head2 ($res, $c) = ctx_request( ... );
202 Works exactly like C<Catalyst::Test::request>, except it also returns the
203 catalyst context object, C<$c>. Note that this only works for local requests.
205 =head2 $res = Catalyst::Test::local_request( $AppClass, $url );
207 Simulate a request using L<HTTP::Request::AsCGI>.
214 require HTTP::Request::AsCGI;
216 my $request = Catalyst::Utils::request( shift(@_) );
217 _customize_request($request, @_);
218 my $cgi = HTTP::Request::AsCGI->new( $request, %ENV )->setup;
220 $class->handle_request;
222 return $cgi->restore->response;
227 =head2 $res = Catalyst::Test::remote_request( $url );
229 Do an actual remote request using LWP.
235 require LWP::UserAgent;
237 my $request = Catalyst::Utils::request( shift(@_) );
238 my $server = URI->new( $ENV{CATALYST_SERVER} );
240 _customize_request($request, @_);
242 if ( $server->path =~ m|^(.+)?/$| ) {
244 $server->path("$path") if $path; # need to be quoted
247 # the request path needs to be sanitised if $server is using a
248 # non-root path due to potential overlap between request path and
251 # If request path is '/', we have to add a trailing slash to the
253 my $add_trailing = $request->uri->path eq '/';
255 my @sp = split '/', $server->path;
256 my @rp = split '/', $request->uri->path;
257 shift @sp;shift @rp; # leading /
259 foreach my $sp (@sp) {
260 $sp eq $rp[0] ? shift @rp : last
263 $request->uri->path(join '/', @rp);
265 if ( $add_trailing ) {
266 $request->uri->path( $request->uri->path . '/' );
270 $request->uri->scheme( $server->scheme );
271 $request->uri->host( $server->host );
272 $request->uri->port( $server->port );
273 $request->uri->path( $server->path . $request->uri->path );
277 $agent = LWP::UserAgent->new(
282 # work around newer LWP max_redirect 0 bug
283 # http://rt.cpan.org/Ticket/Display.html?id=40260
284 requests_redirectable => [],
290 return $agent->request($request);
293 sub _customize_request {
295 my $opts = pop(@_) || {};
296 $opts = {} unless ref($opts) eq 'HASH';
297 if ( my $host = exists $opts->{host} ? $opts->{host} : $default_host ) {
298 $request->header( 'Host' => $host );
304 Fetches the given url and check that the request was successful
306 =head2 action_redirect
308 Fetches the given url and check that the request was a redirect
310 =head2 action_notfound
312 Fetches the given url and check that the request was not found
316 Fetches the given url and matches the content against it.
318 =head2 contenttype_is
320 Check for given mime type
324 L<Catalyst>, L<Test::WWW::Mechanize::Catalyst>,
325 L<Test::WWW::Selenium::Catalyst>, L<Test::More>, L<HTTP::Request::Common>
329 Catalyst Contributors, see Catalyst.pm
333 This program is free software, you can redistribute it and/or modify it under
334 the same terms as Perl itself.