ASP/Test/UserAgent.pm

filter: Statementstmt 90.4% 19 / 21 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.8% 26 / 28 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« ASP/HTTPContext.pm ↑ Summary ASP.pm »
1  
2 package Apache2::ASP::Test::UserAgent;
3  
4 23 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 23 ▶use warnings 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 23 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 23 ▶use HTTP::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 23 ▶use HTTP::Request::AsCGI;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 23 ▶use HTTP::Body;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 0 ▶use Apache2::ASP::HTTPContext;
Subroutine BEGIN: called CC=1 SCAR=2.6
11 use Apache2::ASP::SimpleCGI;
12 use Apache2::ASP::Mock::RequestRec;
13 use Carp 'confess';
14 use IO::File;
15 use Scalar::Util 'weaken';
16 use Cwd 'cwd';
17  
18 our $ContextClass = 'Apache2::ASP::HTTPContext';
19  
20  
21 #==============================================================================
22 sub new
23 {
24 my ($class, %args) = @_;
25
26 return bless {
27 cwd => cwd(),
28 %args,
29 }, $class;
30 }# end new()
31  
32  
33 #==============================================================================
34 sub context
35 {
36 my $s = shift;
37 chdir( $s->{cwd} );
38 return Apache2::ASP::HTTPContext->current || $Apache2::ASP::HTTPContext::ClassName->new;
39 }# end context()
40  
41  
42 #==============================================================================
43 sub post
44 {
45 my ($s, $uri, $args) = @_;
46
47 chdir( $s->{cwd} );
48 no strict 'refs';
49 undef(${"$ContextClass\::instance"});
50 $args ||= [ ];
51 my $req = POST $uri, $args;
52 {
53 no warnings 'uninitialized';
54 %ENV = ( DOCUMENT_ROOT => $ENV{DOCUMENT_ROOT} );
55 }
56 $ENV{REQUEST_METHOD} = 'POST';
57 my $cgi = $s->_setup_cgi( $req );
58 $ENV{CONTENT_TYPE} = 'application/x-www-form-urlencoded';
59
60 my $r = Apache2::ASP::Mock::RequestRec->new();
61 $r->uri( $uri );
62 $r->args( $cgi->{querystring} );
63 $r->{headers_in}->{Cookie} = $ENV{HTTP_COOKIE};
64
65 $s->context->setup_request( $r, $cgi );
66 return $s->_setup_response( $s->context->execute() );
67 }# end post()
68  
69  
70 #==============================================================================
71 sub upload
72 {
73 my ($s, $uri, $args) = @_;
74
75 chdir( $s->{cwd} );
76 no strict 'refs';
77 undef(${"$ContextClass\::instance"});
78 {
79 no warnings 'uninitialized';
80 %ENV = ( DOCUMENT_ROOT => $ENV{DOCUMENT_ROOT} );
81 }
82 my $req = POST $uri, Content_Type => 'form-data', Content => $args;
83 $ENV{REQUEST_METHOD} = 'POST';
84 $ENV{CONTENT_TYPE} = $req->headers->{'content-type'};
85 my $cgi = $s->_setup_cgi( $req );
86 $ENV{CONTENT_TYPE} = 'multipart/form-data';
87
88 my $r = Apache2::ASP::Mock::RequestRec->new();
89 $r->uri( $uri );
90 $r->args( $cgi->{querystring} );
91 $r->{headers_in}->{Cookie} = $ENV{HTTP_COOKIE};
92
93 $s->context->setup_request( $r, $cgi );
94
95 require Apache2::ASP::UploadHook;
96 my $handler_resolver = $s->context->config->web->handler_resolver;
97 $s->context->config->load_class( $handler_resolver );
98 my $hook_obj = Apache2::ASP::UploadHook->new(
99 handler_class => $handler_resolver->new()->resolve_request_handler( $uri ),
100 );
101 my $hook_ref = sub { $hook_obj->hook( @_ ) };
102
103 # Now call the upload hook...
104 require Apache2::ASP::Test::UploadObject;
105 foreach my $uploaded_file ( keys( %{ $cgi->{uploads} } ) )
106 {
107 my $tmpfile = $cgi->upload_info($uploaded_file, 'tempname' );
108 my $filename = $cgi->upload_info( $uploaded_file, 'filename' );
109 my $ifh = IO::File->new;
110 $ifh->open($tmpfile, '<')
111 or die "Cannot open temp file '$tmpfile' for reading: $!";
112 binmode($ifh);
113 while( my $line = <$ifh> )
114 {
115 $hook_ref->(
116 Apache2::ASP::Test::UploadObject->new(
117 filename => $filename,
118 upload_filename => $filename
119 ),
120 $line
121 );
122 }# end while()
123 close($ifh);
124
125 # One more *without* any data (this will signify and EOF condition):
126 $hook_ref->(
127 Apache2::ASP::Test::UploadObject->new(
128 filename => $filename,
129 upload_filename => $filename
130 ),
131 undef
132 );
133 }# end foreach()
134
135 # NOW we can execute...
136 return $s->_setup_response( $s->context->execute() );
137 }# end upload()
138  
139  
140 #==============================================================================
141 sub submit_form
142 {
143 my ($s, $form) = @_;
144
145 chdir( $s->{cwd} );
146 no strict 'refs';
147 undef(${"$ContextClass\::instance"});
148  
149 my $temp_referrer = $ENV{HTTP_REFERER};
150 my $req = $form->click;
151
152 {
153 no warnings 'uninitialized';
154 %ENV = ( DOCUMENT_ROOT => $ENV{DOCUMENT_ROOT} );
155 }
156 $ENV{REQUEST_METHOD} = uc( $req->method );
157 my $cgi = $s->_setup_cgi( $req );
158 $ENV{CONTENT_TYPE} = $form->enctype ? $form->enctype : 'application/x-www-form-urlencoded';
159 $ENV{HTTP_REFERER} = $temp_referrer;
160
161 my $r = Apache2::ASP::Mock::RequestRec->new();
162 $r->uri( $req->uri );
163 $r->args( $cgi->{querystring} );
164 $r->{headers_in}->{Cookie} = $ENV{HTTP_COOKIE};
165
166 $s->context->setup_request( $r, $cgi );
167
168 return $s->_setup_response( $s->context->execute() );
169 }# end submit_form()
170  
171  
172 #==============================================================================
173 sub get
174 {
175 my ($s, $uri) = @_;
176
177 chdir( $s->{cwd} );
178 no strict 'refs';
179 undef(${"$ContextClass\::instance"});
180
181 my $req = GET $uri;
182 {
183 no warnings 'uninitialized';
184 %ENV = ( DOCUMENT_ROOT => $ENV{DOCUMENT_ROOT} );
185 }
186 $ENV{REQUEST_METHOD} = 'GET';
187 my $cgi = $s->_setup_cgi( $req );
188 $ENV{CONTENT_TYPE} = 'application/x-www-form-urlencoded';
189
190 my $r = Apache2::ASP::Mock::RequestRec->new();
191 $r->uri( $uri );
192 $r->args( $cgi->{querystring} );
193 $r->{headers_in}->{Cookie} = $ENV{HTTP_COOKIE};
194
195 $s->context->setup_request( $r, $cgi );
196
197 return $s->_setup_response( $s->context->execute() );
198 }# end get()
199
200
201 #==============================================================================
202 sub add_cookie
203 {
204 my ($s, $name, $value) = @_;
205
206 $s->{cookies}->{$name} = $value;
207 }# end add_cookie()
208
209
210 #==============================================================================
211 sub _setup_response
212 {
213 my ($s, $response_code) = @_;
214
215 $response_code = 200 if $response_code == 0;
216 my $response = HTTP::Response->new( $response_code );
217 $response->content( $s->context->get_prop('r')->buffer );
218
219 $response->header( 'Content-Type' => $s->context->response->{ContentType} );
220
221 foreach my $header ( $s->context->response->Headers )
222 {
223 while( my ($k,$v) = each(%$header) )
224 {
225 $response->header( $k => $v );
226 if( lc($k) eq 'set-cookie' )
227 {
228 my ($data) = split /;/, $v;
229 my ($name,$val) = map { Apache2::ASP::SimpleCGI->unescape( $_ ) } split /\=/, $data;
230 $s->add_cookie( $name => $val );
231 }# end if()
232 }# end while()
233 }# end foreach()
234
235 if( $s->context->session && $s->context->session->{SessionID} )
236 {
237 $s->add_cookie(
238 $s->context->config->data_connections->session->cookie_name => $s->context->session->{SessionID}
239 );
240 }# end if()
241
242 $s->context->r->pool->call_cleanup_handlers();
243 weaken($s->context->{cgi});
244
245 return $response;
246 }# end _setup_response()
247  
248
249 #==============================================================================
250 sub _setup_cgi
251 {
252 my ($s, $req) = @_;
253
254 my $docroot = $ENV{DOCUMENT_ROOT};
255 $s->{c}->DESTROY
256 if $s->{c};
257 $req->referer( $s->{referer} || '' );
258 ($s->{referer}) = $req->uri =~ m/.*?(\/[^\?]+)/;
259  
260 no warnings 'redefine';
261 *HTTP::Request::AsCGI::stdout = sub { 0 };
262
263 $s->{c} = HTTP::Request::AsCGI->new($req)->setup;
264 $ENV{SERVER_NAME} = $ENV{HTTP_HOST} = 'localhost';
265
266 unless( $req->uri =~ m@^/handlers@ )
267 {
268 my ($uri_no_args) = split /\?/, $req->uri;
269 $ENV{SCRIPT_FILENAME} = $s->context->config->web->www_root . $uri_no_args;
270 $ENV{SCRIPT_NAME} = $uri_no_args;
271 }# end unless()
272
273 # User-Agent:
274 $req->header( 'User-Agent' => 'test-useragent v1.0' );
275 $ENV{HTTP_USER_AGENT} = 'test-useragent v1.0';
276
277 # Cookies:
278 my @cookies = ();
279 while( my ($name,$val) = each(%{ $s->{cookies} } ) )
280 {
281 next unless $name && $val;
282 push @cookies, "$name=" . Apache2::ASP::SimpleCGI->escape($val);
283 }# end while()
284
285 $req->header( 'Cookie' => join ';', @cookies ) if @cookies;
286 $ENV{HTTP_COOKIE} = join ';', @cookies;
287 $ENV{DOCUMENT_ROOT} = $docroot
288 if $docroot;
289
290 if( $ENV{REQUEST_METHOD} =~ m/^post$/i )
291 {
292 # Set up the basic params:
293 return Apache2::ASP::SimpleCGI->new(
294 querystring => $ENV{QUERY_STRING},
295 body => $req->content,
296 content_type => $req->headers->{'content-type'},
297 content_length => $req->headers->{'content-length'},
298 );
299 }
300 else
301 {
302 # Simple 'GET' request:
303 return Apache2::ASP::SimpleCGI->new( querystring => $ENV{QUERY_STRING} );
304 }# end if()
305 }# end _setup_cgi()
306  
307 1;# return true:
308  
309 =pod
310  
311 =head1 NAME
312  
313 Apache2::ASP::Test::UserAgent - Execute ASP scripts without a webserver.
314  
315 =head1 SYNOPSIS
316  
317 Generally you will be accessing this class from wither L<Apache2::ASP::Test::Base>
318 or L<Apache2::ASP::API>.
319  
320 my $asp = Apache2::ASP::API->new()
321 -- or --
322 my $asp = Apache2::ASP::Test::Base->new();
323
324 # Get:
325 my $res = $asp->ua->get("/index.asp");
326 if( $res->is_succes ) {
327 ...
328 }
329
330 # Post:
331 my $res = $asp->ua->post("/handlers/contact.form", [
332 name => "Fred",
333 email => 'fred@flintstone.org',
334 message => 'This is a test email message.'
335 ]);
336
337 # Do the same thing, but with HTML::Form:
338 use HTML::Form;
339 my $form = HTML::Form->parse( $asp->ua->get("/contact.asp")->content, '/' );
340 $form->find_input('name')->value('Fred');
341 $form->find_input('email')->value('fred@flintstone.org');
342 $form->find_input('message')->value('This is a test email message');
343 my $res = $asp->ua->submit_form( $form );
344
345 # Upload:
346 my $res = $asp->ua->upload("/handlers/MM?mode=create&uploadID=12334534", [
347 filename => ['/path/to/file.txt'],
348 ]);
349  
350 =head1 PUBLIC PROPERTIES
351  
352 =head2 context
353  
354 Returns the current L<Apache2::ASP::HTTPContext> object.
355  
356 =head1 PUBLIC METHODS
357  
358 =head2 get( $url )
359  
360 Makes a "GET" request to C<$url>
361  
362 =head2 post( $url [,\@args] )
363  
364 Makes a "POST" reqest to C<$url>, using C<@args> as the body.
365  
366 =head2 upload( $url, \@args )
367  
368 Makes a "POST" request with a C<multipart/form-data> type, using C<@args> as the body.
369  
370 =head2 submit_form( HTML::Form $form )
371  
372 Submits the form.
373  
374 B<NOTE:> - this will not work for "upload" forms (yet).
375
376 =head1 BUGS
377
378 It's possible that some bugs have found their way into this release.
379
380 Use RT L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Apache2-ASP> to submit bug reports.
381
382 =head1 HOMEPAGE
383
384 Please visit the Apache2::ASP homepage at L<http://www.devstack.com/> to see examples
385 of Apache2::ASP in action.
386
387 =head1 AUTHOR
388
389 John Drago L<mailto:jdrago_999@yahoo.com>
390
391 =head1 COPYRIGHT AND LICENSE
392
393 Copyright 2007 John Drago, All rights reserved.
394
395 This software is free software. It may be used and distributed under the
396 same terms as Perl itself.
397
398 =cut
399  
« ASP/HTTPContext.pm ↑ Summary ASP.pm »