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 = Class::MOP::get_metaclass_by_name($class);
54 $meta->add_around_method_modifier( "prepare", sub {
58 $c = $self->$orig(@_);
60 $meta->make_immutable( replace_constructor => 1 );
61 Class::C3::reinitialize(); # Fixes RT#46459, I've failed to write a test for how/why, but it does.
62 ### do the request; C::T::request will know about the class name, and
63 ### we've already stopped it from doing remote requests above.
64 my $res = $request->( @_ );
66 ### return both values
73 ctx_request => $ctx_request,
76 return Test::More->builder->like($get->($action),@_);
80 return Test::More->builder->ok($request->($action)->is_success, @_);
82 action_redirect => sub {
84 return Test::More->builder->ok($request->($action)->is_redirect,@_);
86 action_notfound => sub {
88 return Test::More->builder->is_eq($request->($action)->code,404,@_);
90 contenttype_is => sub {
92 my $res = $request->($action);
93 return Test::More->builder->is_eq(scalar($res->content_type),@_);
101 my $import = Sub::Exporter::build_exporter({
102 groups => [ all => $build_exports ],
108 my ($self, $class, $opts) = @_;
109 $import->($self, '-all' => { class => $class });
110 $opts = {} unless ref $opts eq 'HASH';
111 $default_host = $opts->{default_host} if exists $opts->{default_host};
118 Catalyst::Test - Test Catalyst Applications
126 use Catalyst::Test 'TestApp';
127 my $content = get('index.html'); # Content as string
128 my $response = request('index.html'); # HTTP::Response object
129 my($res, $c) = ctx_request('index.html'); # HTTP::Response & context object
131 use HTTP::Request::Common;
132 my $response = request POST '/foo', [
137 # Run tests against a remote server
138 CATALYST_SERVER='http://localhost:3000/' prove -r -l lib/ t/
140 use Catalyst::Test 'TestApp';
141 use Test::More tests => 1;
143 ok( get('/foo') =~ /bar/ );
146 use Catalyst::Test 'MyApp', { default_host => 'myapp.com' };
147 like( get('/whichhost'), qr/served by myapp.com/ );
148 like( get( '/whichhost', { host => 'yourapp.com' } ), qr/served by yourapp.com/ );
150 local $Catalyst::Test::default_host = 'otherapp.com';
151 like( get('/whichhost'), qr/served by otherapp.com/ );
156 This module allows you to make requests to a Catalyst application either without
157 a server, by simulating the environment of an HTTP request using
158 L<HTTP::Request::AsCGI> or remotely if you define the CATALYST_SERVER
159 environment variable. This module also adds a few Catalyst-specific
160 testing methods as displayed in the method section.
162 The L<get|/"$content = get( ... )"> and L<request|/"$res = request( ... );">
163 functions take either a URI or an L<HTTP::Request> object.
165 =head1 INLINE TESTS WILL NO LONGER WORK
167 While it used to be possible to inline a whole testapp into a C<.t> file for a
168 distribution, this will no longer work.
170 The convention is to place your L<Catalyst> test apps into C<t/lib> in your
171 distribution. E.g.: C<t/lib/TestApp.pm>, C<t/lib/TestApp/Controller/Root.pm>,
172 etc.. Multiple test apps can be used in this way.
174 Then write your C<.t> files like so:
180 use Test::More tests => 6;
181 use Catalyst::Test 'TestApp';
185 =head2 $content = get( ... )
189 my $content = get('foo/bar?test=1');
191 Note that this method doesn't follow redirects, so to test for a
192 correctly redirecting page you'll need to use a combination of this
193 method and the L<request|/"$res = request( ... );"> method below:
195 my $res = request('/'); # redirects to /y
196 warn $res->header('location');
198 my $uri = URI->new($res->header('location'));
199 is ( $uri->path , '/y');
200 my $content = get($uri->path);
202 =head2 $res = request( ... );
204 Returns an L<HTTP::Response> object. Accepts an optional hashref for request
205 header configuration; currently only supports setting 'host' value.
207 my $res = request('foo/bar?test=1');
208 my $virtual_res = request('foo/bar?test=1', {host => 'virtualhost.com'});
212 =head2 ($res, $c) = ctx_request( ... );
214 Works exactly like L<request|/"$res = request( ... );">, except it also returns the Catalyst context object,
215 C<$c>. Note that this only works for local requests.
217 =head2 $res = Catalyst::Test::local_request( $AppClass, $url );
219 Simulate a request using L<HTTP::Request::AsCGI>.
226 require HTTP::Request::AsCGI;
228 my $request = Catalyst::Utils::request( shift(@_) );
229 _customize_request($request, @_);
230 my $cgi = HTTP::Request::AsCGI->new( $request, %ENV )->setup;
232 $class->handle_request( env => \%ENV );
234 my $response = $cgi->restore->response;
235 $response->request( $request );
241 =head2 $res = Catalyst::Test::remote_request( $url );
243 Do an actual remote request using LWP.
249 require LWP::UserAgent;
251 my $request = Catalyst::Utils::request( shift(@_) );
252 my $server = URI->new( $ENV{CATALYST_SERVER} );
254 _customize_request($request, @_);
256 if ( $server->path =~ m|^(.+)?/$| ) {
258 $server->path("$path") if $path; # need to be quoted
261 # the request path needs to be sanitised if $server is using a
262 # non-root path due to potential overlap between request path and
265 # If request path is '/', we have to add a trailing slash to the
267 my $add_trailing = $request->uri->path eq '/';
269 my @sp = split '/', $server->path;
270 my @rp = split '/', $request->uri->path;
271 shift @sp;shift @rp; # leading /
273 foreach my $sp (@sp) {
274 $sp eq $rp[0] ? shift @rp : last
277 $request->uri->path(join '/', @rp);
279 if ( $add_trailing ) {
280 $request->uri->path( $request->uri->path . '/' );
284 $request->uri->scheme( $server->scheme );
285 $request->uri->host( $server->host );
286 $request->uri->port( $server->port );
287 $request->uri->path( $server->path . $request->uri->path );
291 $agent = LWP::UserAgent->new(
296 # work around newer LWP max_redirect 0 bug
297 # http://rt.cpan.org/Ticket/Display.html?id=40260
298 requests_redirectable => [],
304 return $agent->request($request);
307 sub _customize_request {
309 my $opts = pop(@_) || {};
310 $opts = {} unless ref($opts) eq 'HASH';
311 if ( my $host = exists $opts->{host} ? $opts->{host} : $default_host ) {
312 $request->header( 'Host' => $host );
318 Fetches the given URL and checks that the request was successful.
320 =head2 action_redirect
322 Fetches the given URL and checks that the request was a redirect.
324 =head2 action_notfound
326 Fetches the given URL and checks that the request was not found.
328 =head2 content_like( $url, $regexp [, $test_name] )
330 Fetches the given URL and returns whether the content matches the regexp.
332 =head2 contenttype_is
334 Check for given MIME type.
338 L<Catalyst>, L<Test::WWW::Mechanize::Catalyst>,
339 L<Test::WWW::Selenium::Catalyst>, L<Test::More>, L<HTTP::Request::Common>
343 Catalyst Contributors, see Catalyst.pm
347 This library is free software. You can redistribute it and/or modify it under
348 the same terms as Perl itself.