1 package Catalyst::Test;
8 use Plack::Middleware::OverrideEnv;
9 use Catalyst::Exception;
15 my $build_exports = sub {
16 my ($self, $meth, $args, $defaults) = @_;
19 my $class = $args->{class};
21 if ( $ENV{CATALYST_SERVER} ) {
22 $request = sub { remote_request(@_) };
24 $request = sub { croak "Must specify a test app: use Catalyst::Test 'TestApp'"; }
26 unless (Class::MOP::is_class_loaded($class)) {
27 Class::MOP::load_class($class);
31 my $app = $class->engine->_build_psgi_app($class);
33 $request = sub { local_request( $app, @_ ) };
36 my $get = sub { $request->(@_)->content };
38 my $ctx_request = sub {
39 my $me = ref $self || $self;
41 ### throw an exception if ctx_request is being used against a remote
43 Catalyst::Exception->throw("$me only works with local requests, not remote")
44 if $ENV{CATALYST_SERVER};
46 ### check explicitly for the class here, or the Cat->meta call will blow
48 Catalyst::Exception->throw("Must specify a test app: use Catalyst::Test 'TestApp'") unless $class;
50 ### place holder for $c after the request finishes; reset every time
51 ### requests are done.
54 ### hook into 'dispatch' -- the function gets called after all plugins
55 ### have done their work, and it's an easy place to capture $c.
57 my $meta = Class::MOP::get_metaclass_by_name($class);
59 $meta->add_after_method_modifier( "dispatch", sub {
62 $meta->make_immutable( replace_constructor => 1 );
63 Class::C3::reinitialize(); # Fixes RT#46459, I've failed to write a test for how/why, but it does.
64 ### do the request; C::T::request will know about the class name, and
65 ### we've already stopped it from doing remote requests above.
66 my $res = $request->( @_ );
68 ### return both values
75 ctx_request => $ctx_request,
78 return Test::More->builder->like($get->($action),@_);
82 return Test::More->builder->ok($request->($action)->is_success, @_);
84 action_redirect => sub {
86 return Test::More->builder->ok($request->($action)->is_redirect,@_);
88 action_notfound => sub {
90 return Test::More->builder->is_eq($request->($action)->code,404,@_);
92 contenttype_is => sub {
94 my $res = $request->($action);
95 return Test::More->builder->is_eq(scalar($res->content_type),@_);
103 my $import = Sub::Exporter::build_exporter({
104 groups => [ all => $build_exports ],
110 my ($self, $class, $opts) = @_;
111 $import->($self, '-all' => { class => $class });
112 $opts = {} unless ref $opts eq 'HASH';
113 $default_host = $opts->{default_host} if exists $opts->{default_host};
120 Catalyst::Test - Test Catalyst Applications
128 use Catalyst::Test 'TestApp';
129 my $content = get('index.html'); # Content as string
130 my $response = request('index.html'); # HTTP::Response object
131 my($res, $c) = ctx_request('index.html'); # HTTP::Response & context object
133 use HTTP::Request::Common;
134 my $response = request POST '/foo', [
139 # Run tests against a remote server
140 CATALYST_SERVER='http://localhost:3000/' prove -r -l lib/ t/
142 use Catalyst::Test 'TestApp';
143 use Test::More tests => 1;
145 ok( get('/foo') =~ /bar/ );
148 use Catalyst::Test 'MyApp', { default_host => 'myapp.com' };
149 like( get('/whichhost'), qr/served by myapp.com/ );
150 like( get( '/whichhost', { host => 'yourapp.com' } ), qr/served by yourapp.com/ );
152 local $Catalyst::Test::default_host = 'otherapp.com';
153 like( get('/whichhost'), qr/served by otherapp.com/ );
158 This module allows you to make requests to a Catalyst application either without
159 a server, by simulating the environment of an HTTP request using
160 L<HTTP::Request::AsCGI> or remotely if you define the CATALYST_SERVER
161 environment variable. This module also adds a few Catalyst-specific
162 testing methods as displayed in the method section.
164 The L<get|/"$content = get( ... )"> and L<request|/"$res = request( ... );">
165 functions take either a URI or an L<HTTP::Request> object.
167 =head1 INLINE TESTS WILL NO LONGER WORK
169 While it used to be possible to inline a whole testapp into a C<.t> file for a
170 distribution, this will no longer work.
172 The convention is to place your L<Catalyst> test apps into C<t/lib> in your
173 distribution. E.g.: C<t/lib/TestApp.pm>, C<t/lib/TestApp/Controller/Root.pm>,
174 etc.. Multiple test apps can be used in this way.
176 Then write your C<.t> files like so:
182 use Test::More tests => 6;
183 use Catalyst::Test 'TestApp';
187 =head2 $content = get( ... )
191 my $content = get('foo/bar?test=1');
193 Note that this method doesn't follow redirects, so to test for a
194 correctly redirecting page you'll need to use a combination of this
195 method and the L<request|/"$res = request( ... );"> method below:
197 my $res = request('/'); # redirects to /y
198 warn $res->header('location');
200 my $uri = URI->new($res->header('location'));
201 is ( $uri->path , '/y');
202 my $content = get($uri->path);
204 =head2 $res = request( ... );
206 Returns an L<HTTP::Response> object. Accepts an optional hashref for request
207 header configuration; currently only supports setting 'host' value.
209 my $res = request('foo/bar?test=1');
210 my $virtual_res = request('foo/bar?test=1', {host => 'virtualhost.com'});
214 =head2 ($res, $c) = ctx_request( ... );
216 Works exactly like L<request|/"$res = request( ... );">, except it also returns the Catalyst context object,
217 C<$c>. Note that this only works for local requests.
219 =head2 $res = Catalyst::Test::local_request( $AppClass, $url );
221 Simulate a request using L<HTTP::Request::AsCGI>.
228 my $request = Catalyst::Utils::request(shift);
230 _customize_request($request, \%extra_env, @_);
234 app => Plack::Middleware::OverrideEnv->wrap(
235 $app, env_override => \%extra_env,
238 $ret = shift->($request);
246 =head2 $res = Catalyst::Test::remote_request( $url );
248 Do an actual remote request using LWP.
254 require LWP::UserAgent;
256 my $request = Catalyst::Utils::request( shift(@_) );
257 my $server = URI->new( $ENV{CATALYST_SERVER} );
259 _customize_request($request, @_);
261 if ( $server->path =~ m|^(.+)?/$| ) {
263 $server->path("$path") if $path; # need to be quoted
266 # the request path needs to be sanitised if $server is using a
267 # non-root path due to potential overlap between request path and
270 # If request path is '/', we have to add a trailing slash to the
272 my $add_trailing = $request->uri->path eq '/';
274 my @sp = split '/', $server->path;
275 my @rp = split '/', $request->uri->path;
276 shift @sp;shift @rp; # leading /
278 foreach my $sp (@sp) {
279 $sp eq $rp[0] ? shift @rp : last
282 $request->uri->path(join '/', @rp);
284 if ( $add_trailing ) {
285 $request->uri->path( $request->uri->path . '/' );
289 $request->uri->scheme( $server->scheme );
290 $request->uri->host( $server->host );
291 $request->uri->port( $server->port );
292 $request->uri->path( $server->path . $request->uri->path );
296 $agent = LWP::UserAgent->new(
301 # work around newer LWP max_redirect 0 bug
302 # http://rt.cpan.org/Ticket/Display.html?id=40260
303 requests_redirectable => [],
309 return $agent->request($request);
312 sub _customize_request {
314 my $extra_env = shift;
315 my $opts = pop(@_) || {};
316 $opts = {} unless ref($opts) eq 'HASH';
317 if ( my $host = exists $opts->{host} ? $opts->{host} : $default_host ) {
318 $request->header( 'Host' => $host );
321 if (my $extra = $opts->{extra_env}) {
322 @{ $extra_env }{keys %{ $extra }} = values %{ $extra };
328 Fetches the given URL and checks that the request was successful.
330 =head2 action_redirect
332 Fetches the given URL and checks that the request was a redirect.
334 =head2 action_notfound
336 Fetches the given URL and checks that the request was not found.
338 =head2 content_like( $url, $regexp [, $test_name] )
340 Fetches the given URL and returns whether the content matches the regexp.
342 =head2 contenttype_is
344 Check for given MIME type.
348 L<Catalyst>, L<Test::WWW::Mechanize::Catalyst>,
349 L<Test::WWW::Selenium::Catalyst>, L<Test::More>, L<HTTP::Request::Common>
353 Catalyst Contributors, see Catalyst.pm
357 This library is free software. You can redistribute it and/or modify it under
358 the same terms as Perl itself.