1 package Catalyst::Test;
8 use Catalyst::Exception;
14 sub _build_request_export {
15 my ($self, $args) = @_;
17 return sub { remote_request(@_) }
20 my $class = $args->{class};
22 # Here we should be failing right away, but for some stupid backcompat thing
23 # I don't quite remember we fail lazily here. Needs a proper deprecation and
25 return sub { croak "Must specify a test app: use Catalyst::Test 'TestApp'" }
28 Class::MOP::load_class($class) unless Class::MOP::is_class_loaded($class);
31 return sub { local_request( $class, @_ ) };
34 sub _build_get_export {
35 my ($self, $args) = @_;
36 my $request = $args->{request};
38 return sub { $request->(@_)->content };
40 sub _build_ctx_request_export {
41 my ($self, $args) = @_;
42 my ($class, $request) = @{ $args }{qw(class request)};
45 my $me = ref $self || $self;
47 # fail if ctx_request is being used against a remote server
48 Catalyst::Exception->throw("$me only works with local requests, not remote")
49 if $ENV{CATALYST_SERVER};
51 # check explicitly for the class here, or the Cat->meta call will blow
53 Catalyst::Exception->throw("Must specify a test app: use Catalyst::Test 'TestApp'") unless $class;
55 # place holder for $c after the request finishes; reset every time
59 # hook into 'dispatch' -- the function gets called after all plugins
60 # have done their work, and it's an easy place to capture $c.
61 my $meta = Class::MOP::get_metaclass_by_name($class);
63 $meta->add_after_method_modifier( "dispatch", sub {
64 $ctx_closed_over = shift;
66 $meta->make_immutable( replace_constructor => 1 );
67 Class::C3::reinitialize(); # Fixes RT#46459, I've failed to write a test for how/why, but it does.
69 # do the request; C::T::request will know about the class name, and
70 # we've already stopped it from doing remote requests above.
71 my $res = $args->{request}->( @_ );
73 # Make sure not to leave a reference $ctx hanging around.
74 # This means that the context will go out of scope as soon as the
75 # caller disposes of it, rather than waiting till the next time
76 # that ctx_request is called. This can be important if your $ctx
77 # ends up with a reference to a shared resource or lock (for example)
78 # which you want to clean up in test teardown - if the $ctx is still
79 # closed over then you're stuffed...
80 my $ctx = $ctx_closed_over;
81 undef $ctx_closed_over;
83 return ( $res, $ctx );
87 my $build_exports = sub {
88 my ($self, $meth, $args, $defaults) = @_;
89 my $class = $args->{class};
91 my $request = $self->_build_request_export({
93 remote => $ENV{CATALYST_SERVER},
96 my $get = $self->_build_get_export({ request => $request });
98 my $ctx_request = $self->_build_ctx_request_export({
106 ctx_request => $ctx_request,
107 content_like => sub {
109 return Test::More->builder->like($get->($action),@_);
113 return Test::More->builder->ok($request->($action)->is_success, @_);
115 action_redirect => sub {
117 return Test::More->builder->ok($request->($action)->is_redirect,@_);
119 action_notfound => sub {
121 return Test::More->builder->is_eq($request->($action)->code,404,@_);
123 contenttype_is => sub {
125 my $res = $request->($action);
126 return Test::More->builder->is_eq(scalar($res->content_type),@_);
134 my $import = Sub::Exporter::build_exporter({
135 groups => [ all => $build_exports ],
141 my ($self, $class, $opts) = @_;
143 qq{Importing Catalyst::Test without an application name is deprecated:\n
144 Instead of saying: use Catalyst::Test;
145 say: use Catalyst::Test (); # If you don't want to import a test app right now.
146 or say: use Catalyst::Test 'MyApp'; # If you do want to import a test app.\n\n})
148 $import->($self, '-all' => { class => $class });
149 $opts = {} unless ref $opts eq 'HASH';
150 $default_host = $opts->{default_host} if exists $opts->{default_host};
157 Catalyst::Test - Test Catalyst Applications
165 use Catalyst::Test 'TestApp';
166 my $content = get('index.html'); # Content as string
167 my $response = request('index.html'); # HTTP::Response object
168 my($res, $c) = ctx_request('index.html'); # HTTP::Response & context object
170 use HTTP::Request::Common;
171 my $response = request POST '/foo', [
176 # Run tests against a remote server
177 CATALYST_SERVER='http://localhost:3000/' prove -r -l lib/ t/
179 use Catalyst::Test 'TestApp';
180 use Test::More tests => 1;
182 ok( get('/foo') =~ /bar/ );
185 use Catalyst::Test 'MyApp', { default_host => 'myapp.com' };
186 like( get('/whichhost'), qr/served by myapp.com/ );
187 like( get( '/whichhost', { host => 'yourapp.com' } ), qr/served by yourapp.com/ );
189 local $Catalyst::Test::default_host = 'otherapp.com';
190 like( get('/whichhost'), qr/served by otherapp.com/ );
195 This module allows you to make requests to a Catalyst application either without
196 a server, by simulating the environment of an HTTP request using
197 L<HTTP::Request::AsCGI> or remotely if you define the CATALYST_SERVER
198 environment variable. This module also adds a few Catalyst-specific
199 testing methods as displayed in the method section.
201 The L<get|/"$content = get( ... )"> and L<request|/"$res = request( ... );">
202 functions take either a URI or an L<HTTP::Request> object.
204 =head1 INLINE TESTS WILL NO LONGER WORK
206 While it used to be possible to inline a whole testapp into a C<.t> file for a
207 distribution, this will no longer work.
209 The convention is to place your L<Catalyst> test apps into C<t/lib> in your
210 distribution. E.g.: C<t/lib/TestApp.pm>, C<t/lib/TestApp/Controller/Root.pm>,
211 etc.. Multiple test apps can be used in this way.
213 Then write your C<.t> files like so:
219 use Test::More tests => 6;
220 use Catalyst::Test 'TestApp';
224 =head2 $content = get( ... )
228 my $content = get('foo/bar?test=1');
230 Note that this method doesn't follow redirects, so to test for a
231 correctly redirecting page you'll need to use a combination of this
232 method and the L<request|/"$res = request( ... );"> method below:
234 my $res = request('/'); # redirects to /y
235 warn $res->header('location');
237 my $uri = URI->new($res->header('location'));
238 is ( $uri->path , '/y');
239 my $content = get($uri->path);
241 Note also that the content is returned as raw bytes, without any attempt
242 to decode it into characters.
244 =head2 $res = request( ... );
246 Returns an L<HTTP::Response> object. Accepts an optional hashref for request
247 header configuration; currently only supports setting 'host' value.
249 my $res = request('foo/bar?test=1');
250 my $virtual_res = request('foo/bar?test=1', {host => 'virtualhost.com'});
254 =head2 ($res, $c) = ctx_request( ... );
256 Works exactly like L<request|/"$res = request( ... );">, except it also returns the Catalyst context object,
257 C<$c>. Note that this only works for local requests.
259 =head2 $res = Catalyst::Test::local_request( $AppClass, $url );
261 Simulate a request using L<HTTP::Request::AsCGI>.
268 my $app = ref($class) eq "CODE" ? $class : $class->_finalized_psgi_app;
270 my $request = Catalyst::Utils::request(shift);
272 _customize_request($request, \%extra_env, @_);
276 app => sub { $app->({ %{ $_[0] }, %extra_env }) },
278 my $psgi_app = shift;
280 my $resp = $psgi_app->($request);
282 # HTML head parsing based on LWP::UserAgent
284 # This is not just horrible and possibly broken, but also really
285 # doesn't belong here. Whoever wants this should be working on
286 # getting it into Plack::Test, or make a middleware out of it, or
287 # whatever. Seriously - horrible.
289 require HTML::HeadParser;
291 my $parser = HTML::HeadParser->new();
292 $parser->xml_mode(1) if $resp->content_is_xhtml;
293 $parser->utf8_mode(1) if $] >= 5.008 && $HTML::Parser::VERSION >= 3.40;
295 $parser->parse( $resp->content );
296 my $h = $parser->header;
297 for my $f ( $h->header_field_names ) {
298 $resp->init_header( $f, [ $h->header($f) ] );
309 =head2 $res = Catalyst::Test::remote_request( $url );
311 Do an actual remote request using LWP.
317 require LWP::UserAgent;
319 my $request = Catalyst::Utils::request( shift(@_) );
320 my $server = URI->new( $ENV{CATALYST_SERVER} );
322 _customize_request($request, @_);
324 if ( $server->path =~ m|^(.+)?/$| ) {
326 $server->path("$path") if $path; # need to be quoted
329 # the request path needs to be sanitised if $server is using a
330 # non-root path due to potential overlap between request path and
333 # If request path is '/', we have to add a trailing slash to the
335 my $add_trailing = $request->uri->path eq '/';
337 my @sp = split '/', $server->path;
338 my @rp = split '/', $request->uri->path;
339 shift @sp;shift @rp; # leading /
341 foreach my $sp (@sp) {
342 $sp eq $rp[0] ? shift @rp : last
345 $request->uri->path(join '/', @rp);
347 if ( $add_trailing ) {
348 $request->uri->path( $request->uri->path . '/' );
352 $request->uri->scheme( $server->scheme );
353 $request->uri->host( $server->host );
354 $request->uri->port( $server->port );
355 $request->uri->path( $server->path . $request->uri->path );
359 $agent = LWP::UserAgent->new(
364 # work around newer LWP max_redirect 0 bug
365 # http://rt.cpan.org/Ticket/Display.html?id=40260
366 requests_redirectable => [],
372 return $agent->request($request);
375 sub _customize_request {
377 my $extra_env = shift;
378 my $opts = pop(@_) || {};
379 $opts = {} unless ref($opts) eq 'HASH';
380 if ( my $host = exists $opts->{host} ? $opts->{host} : $default_host ) {
381 $request->header( 'Host' => $host );
384 if (my $extra = $opts->{extra_env}) {
385 @{ $extra_env }{keys %{ $extra }} = values %{ $extra };
391 Fetches the given URL and checks that the request was successful.
393 =head2 action_redirect
395 Fetches the given URL and checks that the request was a redirect.
397 =head2 action_notfound
399 Fetches the given URL and checks that the request was not found.
401 =head2 content_like( $url, $regexp [, $test_name] )
403 Fetches the given URL and returns whether the content matches the regexp.
405 =head2 contenttype_is
407 Check for given MIME type.
411 L<Catalyst>, L<Test::WWW::Mechanize::Catalyst>,
412 L<Test::WWW::Selenium::Catalyst>, L<Test::More>, L<HTTP::Request::Common>
416 Catalyst Contributors, see Catalyst.pm
420 This library is free software. You can redistribute it and/or modify it under
421 the same terms as Perl itself.