1 package Catalyst::Test;
8 use Catalyst::Exception;
12 use Carp 'croak', 'carp';
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 my $meth = $request->($action)->request->method;
114 my @args = @_ ? @_ : ("$meth $action returns successfully");
115 return Test::More->builder->ok($request->($action)->is_success,@args);
117 action_redirect => sub {
119 my $meth = $request->($action)->request->method;
120 my @args = @_ ? @_ : ("$meth $action returns a redirect");
121 return Test::More->builder->ok($request->($action)->is_redirect,@args);
123 action_notfound => sub {
125 my $meth = $request->($action)->request->method;
126 my @args = @_ ? @_ : ("$meth $action returns a 404");
127 return Test::More->builder->is_eq($request->($action)->code,404,@args);
129 contenttype_is => sub {
131 my $res = $request->($action);
132 return Test::More->builder->is_eq(scalar($res->content_type),@_);
140 my $import = Sub::Exporter::build_exporter({
141 groups => [ all => $build_exports ],
147 my ($self, $class, $opts) = @_;
149 qq{Importing Catalyst::Test without an application name is deprecated:\n
150 Instead of saying: use Catalyst::Test;
151 say: use Catalyst::Test (); # If you don't want to import a test app right now.
152 or say: use Catalyst::Test 'MyApp'; # If you do want to import a test app.\n\n})
154 $import->($self, '-all' => { class => $class });
155 $opts = {} unless ref $opts eq 'HASH';
156 $default_host = $opts->{default_host} if exists $opts->{default_host};
163 Catalyst::Test - Test Catalyst Applications
171 use Catalyst::Test 'TestApp';
172 my $content = get('index.html'); # Content as string
173 my $response = request('index.html'); # HTTP::Response object
174 my($res, $c) = ctx_request('index.html'); # HTTP::Response & context object
176 use HTTP::Request::Common;
177 my $response = request POST '/foo', [
182 # Run tests against a remote server
183 CATALYST_SERVER='http://localhost:3000/' prove -r -l lib/ t/
185 use Catalyst::Test 'TestApp';
186 use Test::More tests => 1;
188 ok( get('/foo') =~ /bar/ );
191 use Catalyst::Test 'MyApp', { default_host => 'myapp.com' };
192 like( get('/whichhost'), qr/served by myapp.com/ );
193 like( get( '/whichhost', { host => 'yourapp.com' } ), qr/served by yourapp.com/ );
195 local $Catalyst::Test::default_host = 'otherapp.com';
196 like( get('/whichhost'), qr/served by otherapp.com/ );
201 This module allows you to make requests to a Catalyst application either without
202 a server, by simulating the environment of an HTTP request using
203 L<HTTP::Request::AsCGI> or remotely if you define the CATALYST_SERVER
204 environment variable. This module also adds a few Catalyst-specific
205 testing methods as displayed in the method section.
207 The L<get|/"$content = get( ... )"> and L<request|/"$res = request( ... );">
208 functions take either a URI or an L<HTTP::Request> object.
210 =head1 INLINE TESTS WILL NO LONGER WORK
212 While it used to be possible to inline a whole test app into a C<.t> file for
213 a distribution, this will no longer work.
215 The convention is to place your L<Catalyst> test apps into C<t/lib> in your
216 distribution. E.g.: C<t/lib/TestApp.pm>, C<t/lib/TestApp/Controller/Root.pm>,
217 etc.. Multiple test apps can be used in this way.
219 Then write your C<.t> files like so:
225 use Test::More tests => 6;
226 use Catalyst::Test 'TestApp';
230 =head2 $content = get( ... )
234 my $content = get('foo/bar?test=1');
236 Note that this method doesn't follow redirects, so to test for a
237 correctly redirecting page you'll need to use a combination of this
238 method and the L<request|/"$res = request( ... );"> method below:
240 my $res = request('/'); # redirects to /y
241 warn $res->header('location');
243 my $uri = URI->new($res->header('location'));
244 is ( $uri->path , '/y');
245 my $content = get($uri->path);
247 Note also that the content is returned as raw bytes, without any attempt
248 to decode it into characters.
250 =head2 $res = request( ... );
252 Returns an L<HTTP::Response> object. Accepts an optional hashref for request
253 header configuration; currently only supports setting 'host' value.
255 my $res = request('foo/bar?test=1');
256 my $virtual_res = request('foo/bar?test=1', {host => 'virtualhost.com'});
258 =head2 ($res, $c) = ctx_request( ... );
260 Works exactly like L<request|/"$res = request( ... );">, except it also returns the Catalyst context object,
261 C<$c>. Note that this only works for local requests.
268 my $request = Catalyst::Utils::request(shift);
271 _customize_request($request, \%extra_env, @_);
272 $args->{mangle_request}->($request) if $args->{mangle_request};
277 app => sub { $args->{app}->({ %{ $_[0] }, %extra_env }) },
280 my $resp = $psgi_app->($request);
281 $args->{mangle_response}->($resp) if $args->{mangle_response};
292 app => ref($class) eq "CODE" ? $class : $class->_finalized_psgi_app,
293 mangle_response => sub {
296 # HTML head parsing based on LWP::UserAgent
298 # This is because if you make a remote request with LWP, then the
299 # <BASE HREF="..."> from the returned HTML document will be used
300 # to fill in $res->base, as documented in HTTP::Response. We need
301 # to support this in local test requests so that they work 'the same'.
303 # This is not just horrible and possibly broken, but also really
304 # doesn't belong here. Whoever wants this should be working on
305 # getting it into Plack::Test, or make a middleware out of it, or
306 # whatever. Seriously - horrible.
308 if (!$resp->content_type || $resp->content_is_html) {
309 require HTML::HeadParser;
311 my $parser = HTML::HeadParser->new();
312 $parser->xml_mode(1) if $resp->content_is_xhtml;
313 $parser->utf8_mode(1) if $] >= 5.008 && $HTML::Parser::VERSION >= 3.40;
315 $parser->parse( $resp->content );
316 my $h = $parser->header;
317 for my $f ( $h->header_field_names ) {
318 $resp->init_header( $f, [ $h->header($f) ] );
321 # Another horrible hack to make the response headers have a
322 # 'status' field. This is for back-compat, but you should
323 # call $resp->code instead!
324 $resp->init_header('status', [ $resp->code ]);
331 sub _remote_request {
332 require LWP::UserAgent;
333 local $Plack::Test::Impl = 'ExternalServer';
336 $agent = LWP::UserAgent->new(
341 # work around newer LWP max_redirect 0 bug
342 # http://rt.cpan.org/Ticket/Display.html?id=40260
343 requests_redirectable => [],
350 my $server = URI->new($ENV{CATALYST_SERVER});
351 if ( $server->path =~ m|^(.+)?/$| ) {
353 $server->path("$path") if $path; # need to be quoted
359 mangle_request => sub {
362 # the request path needs to be sanitised if $server is using a
363 # non-root path due to potential overlap between request path and
366 # If request path is '/', we have to add a trailing slash to the
368 my $add_trailing = ($request->uri->path eq '/' || $request->uri->path eq '') ? 1 : 0;
370 my @sp = split '/', $server->path;
371 my @rp = split '/', $request->uri->path;
372 shift @sp; shift @rp; # leading /
374 foreach my $sp (@sp) {
375 $sp eq $rp[0] ? shift @rp : last
378 $request->uri->path(join '/', @rp);
380 if ( $add_trailing ) {
381 $request->uri->path( $request->uri->path . '/' );
388 for my $name (qw(local_request remote_request)) {
391 Calling Catalyst::Test::${name}() directly is deprecated.
393 Please import Catalyst::Test into your namespace and use the provided request()
396 return __PACKAGE__->can("_${name}")->(@_);
403 sub _customize_request {
405 my $extra_env = shift;
406 my $opts = pop(@_) || {};
407 $opts = {} unless ref($opts) eq 'HASH';
408 if ( my $host = exists $opts->{host} ? $opts->{host} : $default_host ) {
409 $request->header( 'Host' => $host );
412 if (my $extra = $opts->{extra_env}) {
413 @{ $extra_env }{keys %{ $extra }} = values %{ $extra };
417 =head2 action_ok($url [, $test_name ])
419 Fetches the given URL and checks that the request was successful. An optional
420 second argument can be given to specify the name of the test.
422 =head2 action_redirect($url [, $test_name ])
424 Fetches the given URL and checks that the request was a redirect. An optional
425 second argument can be given to specify the name of the test.
427 =head2 action_notfound($url [, $test_name ])
429 Fetches the given URL and checks that the request was not found. An optional
430 second argument can be given to specify the name of the test.
432 =head2 content_like( $url, $regexp [, $test_name ] )
434 Fetches the given URL and returns whether the content matches the regexp. An
435 optional third argument can be given to specify the name of the test.
437 =head2 contenttype_is($url, $type [, $test_name ])
439 Verify the given URL has a content type of $type and optionally specify a test name.
443 L<Catalyst>, L<Test::WWW::Mechanize::Catalyst>,
444 L<Test::WWW::Selenium::Catalyst>, L<Test::More>, L<HTTP::Request::Common>
448 Catalyst Contributors, see Catalyst.pm
452 This library is free software. You can redistribute it and/or modify it under
453 the same terms as Perl itself.