- added Catalyst::Engine::HTTP
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Test.pm
1 package Catalyst::Test;
2
3 use strict;
4 use UNIVERSAL::require;
5
6 $ENV{CATALYST_ENGINE} = 'Test';
7
8 =head1 NAME
9
10 Catalyst::Test - Test Catalyst applications
11
12 =head1 SYNOPSIS
13
14     # Helper
15     script/test.pl
16
17     # Tests
18     use Catalyst::Test 'TestApp';
19     request('index.html');
20     get('index.html');
21
22     # Run tests against a remote server
23     CATALYST_REMOTE='http://localhost:3000/' prove -l lib/ t/
24
25     # Tests with inline apps need to use Catalyst::Engine::Test
26     package TestApp;
27
28     use Catalyst qw[-Engine=Test];
29
30     __PACKAGE__->action(
31         foo => sub {
32             my ( $self, $c ) = @_;
33             $c->res->output('bar');
34         }
35     );
36
37     package main;
38
39     use Test::More tests => 1;
40     use Catalyst::Test 'TestApp';
41
42     ok( get('/foo') =~ /bar/ );
43
44
45 =head1 DESCRIPTION
46
47 Test Catalyst applications.
48
49 =head2 METHODS
50
51 =head3 get
52
53 Returns the content.
54
55     my $content = get('foo/bar?test=1');
56
57 =head3 request
58
59 Returns a C<HTTP::Response> object.
60
61     my $res =request('foo/bar?test=1');
62
63 =cut
64
65 sub import {
66     my $self = shift;
67     my $class = shift;
68
69     my ( $get, $request );
70
71     if ( $ENV{CATALYST_REMOTE} ) {
72         $request = sub { remote_request(@_) };
73         $get     = sub { remote_request(@_)->content };
74     }
75
76     else {
77         $class->require;
78         unless ( $INC{'Test/Builder.pm'} ) {
79             die qq/Couldn't load "$class", "$@"/ if $@;
80         }
81
82         $request = sub { $class->run(@_) };
83         $get     = sub { $class->run(@_)->content };
84     }
85
86     no strict 'refs';
87     my $caller = caller(0);
88     *{"$caller\::request"} = $request;
89     *{"$caller\::get"}     = $get;
90 }
91
92 sub remote_request {
93     my $request = shift;
94
95     require LWP::UserAgent;
96
97     my $remote = URI->new( $ENV{CATALYST_REMOTE} );
98
99     unless ( ref $request ) {
100
101         my $uri = ( $request =~ m/http/i )
102           ? URI->new($request)
103           : URI->new( 'http://localhost' . $request );
104
105         $request = $uri->canonical;
106     }
107
108     $request->scheme( $remote->scheme );
109     $request->host( $remote->host );
110     $request->port( $remote->port );
111
112     unless ( ref $request eq 'HTTP::Request' ) {
113         $request = HTTP::Request->new( 'GET', $request );
114     }
115
116     my $agent = LWP::UserAgent->new;
117
118     return $agent->request($request);
119 }
120
121 =head1 SEE ALSO
122
123 L<Catalyst>.
124
125 =head1 AUTHOR
126
127 Sebastian Riedel, C<sri@cpan.org>
128
129 =head1 COPYRIGHT
130
131 This program is free software, you can redistribute it and/or modify it under
132 the same terms as Perl itself.
133
134 =cut
135
136 1;