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 ### check explicitly for the class here, or the Cat->meta call will blow
43 Catalyst::Exception->throw("Must specify a test app: use Catalyst::Test 'TestApp'") unless $class;
45 ### place holder for $c after the request finishes; reset every time
46 ### requests are done.
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.
52 my $meta = Catalyst->meta;
54 $meta->add_after_method_modifier( "dispatch", sub {
57 $meta->make_immutable;
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->( @_ );
63 ### return both values
70 ctx_request => $ctx_request,
73 return Test::More->builder->like($get->($action),@_);
77 return Test::More->builder->ok($request->($action)->is_success, @_);
79 action_redirect => sub {
81 return Test::More->builder->ok($request->($action)->is_redirect,@_);
83 action_notfound => sub {
85 return Test::More->builder->is_eq($request->($action)->code,404,@_);
87 contenttype_is => sub {
89 my $res = $request->($action);
90 return Test::More->builder->is_eq(scalar($res->content_type),@_);
98 my $import = Sub::Exporter::build_exporter({
99 groups => [ all => $build_exports ],
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};
115 Catalyst::Test - Test Catalyst Applications
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
128 use HTTP::Request::Common;
129 my $response = request POST '/foo', [
134 # Run tests against a remote server
135 CATALYST_SERVER='http://localhost:3000/' prove -r -l lib/ t/
137 # Tests with inline apps need to use Catalyst::Engine::Test
143 my ( $self, $c ) = @_;
144 $c->res->output('bar');
147 __PACKAGE__->setup();
151 use Catalyst::Test 'TestApp';
152 use Test::More tests => 1;
154 ok( get('/foo') =~ /bar/ );
157 use Catalyst::Test 'MyApp', { default_host => 'myapp.com' };
158 like( get('/whichhost'), qr/served by myapp.com/ );
159 like( get( '/whichhost', { host => 'yourapp.com' } ), qr/served by yourapp.com/ );
161 local $Catalyst::Test::default_host = 'otherapp.com';
162 like( get('/whichhost'), qr/served by otherapp.com/ );
167 This module allows you to make requests to a Catalyst application either without
168 a server, by simulating the environment of an HTTP request using
169 L<HTTP::Request::AsCGI> or remotely if you define the CATALYST_SERVER
170 environment variable. This module also adds a few catalyst
171 specific testing methods as displayed in the method section.
173 The L<get> and L<request> functions take either a URI or an L<HTTP::Request>
178 =head2 $content = get( ... )
182 my $content = get('foo/bar?test=1');
184 Note that this method doesn't follow redirects, so to test for a
185 correctly redirecting page you'll need to use a combination of this
186 method and the L<request> method below:
188 my $res = request('/'); # redirects to /y
189 warn $res->header('location');
191 my $uri = URI->new($res->header('location'));
192 is ( $uri->path , '/y');
193 my $content = get($uri->path);
195 =head2 $res = request( ... );
197 Returns a L<HTTP::Response> object. Accepts an optional hashref for request
198 header configuration; currently only supports setting 'host' value.
200 my $res = request('foo/bar?test=1');
201 my $virtual_res = request('foo/bar?test=1', {host => 'virtualhost.com'});
205 =head2 ($res, $c) = ctx_request( ... );
207 Works exactly like L<request>, except it also returns the Catalyst context object,
208 C<$c>. Note that this only works for local requests.
210 =head2 $res = Catalyst::Test::local_request( $AppClass, $url );
212 Simulate a request using L<HTTP::Request::AsCGI>.
219 require HTTP::Request::AsCGI;
221 my $request = Catalyst::Utils::request( shift(@_) );
222 _customize_request($request, @_);
223 my $cgi = HTTP::Request::AsCGI->new( $request, %ENV )->setup;
225 $class->handle_request;
227 return $cgi->restore->response;
232 =head2 $res = Catalyst::Test::remote_request( $url );
234 Do an actual remote request using LWP.
240 require LWP::UserAgent;
242 my $request = Catalyst::Utils::request( shift(@_) );
243 my $server = URI->new( $ENV{CATALYST_SERVER} );
245 _customize_request($request, @_);
247 if ( $server->path =~ m|^(.+)?/$| ) {
249 $server->path("$path") if $path; # need to be quoted
252 # the request path needs to be sanitised if $server is using a
253 # non-root path due to potential overlap between request path and
256 # If request path is '/', we have to add a trailing slash to the
258 my $add_trailing = $request->uri->path eq '/';
260 my @sp = split '/', $server->path;
261 my @rp = split '/', $request->uri->path;
262 shift @sp;shift @rp; # leading /
264 foreach my $sp (@sp) {
265 $sp eq $rp[0] ? shift @rp : last
268 $request->uri->path(join '/', @rp);
270 if ( $add_trailing ) {
271 $request->uri->path( $request->uri->path . '/' );
275 $request->uri->scheme( $server->scheme );
276 $request->uri->host( $server->host );
277 $request->uri->port( $server->port );
278 $request->uri->path( $server->path . $request->uri->path );
282 $agent = LWP::UserAgent->new(
287 # work around newer LWP max_redirect 0 bug
288 # http://rt.cpan.org/Ticket/Display.html?id=40260
289 requests_redirectable => [],
295 return $agent->request($request);
298 sub _customize_request {
300 my $opts = pop(@_) || {};
301 $opts = {} unless ref($opts) eq 'HASH';
302 if ( my $host = exists $opts->{host} ? $opts->{host} : $default_host ) {
303 $request->header( 'Host' => $host );
309 Fetches the given URL and check that the request was successful
311 =head2 action_redirect
313 Fetches the given URL and check that the request was a redirect
315 =head2 action_notfound
317 Fetches the given URL and check that the request was not found
321 Fetches the given URL and matches the content against it.
323 =head2 contenttype_is
325 Check for given MIME type
329 L<Catalyst>, L<Test::WWW::Mechanize::Catalyst>,
330 L<Test::WWW::Selenium::Catalyst>, L<Test::More>, L<HTTP::Request::Common>
334 Catalyst Contributors, see Catalyst.pm
338 This program is free software, you can redistribute it and/or modify it under
339 the same terms as Perl itself.