home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / TestRequest.pm < prev    next >
Encoding:
Perl POD Document  |  2004-07-31  |  29.7 KB  |  1,066 lines

  1. # Copyright 2001-2004 The Apache Software Foundation
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. #     http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. package Apache::TestRequest;
  16.  
  17. use strict;
  18. use warnings FATAL => 'all';
  19.  
  20. BEGIN { 
  21.     $ENV{PERL_LWP_USE_HTTP_10}   = 1;    # default to http/1.0
  22.     $ENV{APACHE_TEST_HTTP_09_OK} ||= 0;  # 0.9 responses are ok
  23. }
  24.  
  25. use Apache::Test ();
  26. use Apache::TestConfig ();
  27.  
  28. use Carp;
  29.  
  30. use constant TRY_TIMES => 200;
  31. use constant INTERP_KEY => 'X-PerlInterpreter';
  32. use constant UA_TIMEOUT => 60 * 10; #longer timeout for debugging
  33.  
  34. my $have_lwp = 0;
  35.  
  36. # APACHE_TEST_PRETEND_NO_LWP=1 pretends that LWP is not available so
  37. # one can test whether the test suite survives if the user doesn't
  38. # have lwp installed
  39. unless ($ENV{APACHE_TEST_PRETEND_NO_LWP}) {
  40.     $have_lwp = eval {
  41.         require LWP::UserAgent;
  42.         require HTTP::Request::Common;
  43.  
  44.         unless (defined &HTTP::Request::Common::OPTIONS) {
  45.             package HTTP::Request::Common;
  46.             no strict 'vars';
  47.             *OPTIONS = sub { _simple_req(OPTIONS => @_) };
  48.             push @EXPORT, 'OPTIONS';
  49.         }
  50.         1;
  51.     };
  52. }
  53.  
  54. unless ($have_lwp) {
  55.     require Apache::TestClient;
  56. }
  57.  
  58. sub has_lwp { $have_lwp }
  59.  
  60. unless ($have_lwp) {
  61.     #need to define the shortcuts even though the wont be used
  62.     #so Perl can parse test scripts
  63.     @HTTP::Request::Common::EXPORT = qw(GET HEAD POST PUT OPTIONS);
  64. }
  65.  
  66. sub install_http11 {
  67.     eval {
  68.         die "no LWP" unless $have_lwp;
  69.         LWP->VERSION(5.60); #minimal version
  70.         require LWP::Protocol::http;
  71.         #LWP::Protocol::http10 is used by default
  72.         LWP::Protocol::implementor('http', 'LWP::Protocol::http');
  73.     };
  74. }
  75.  
  76. use vars qw(@EXPORT @ISA $RedirectOK $DebugLWP);
  77.  
  78. require Exporter;
  79. *import = \&Exporter::import;
  80. @EXPORT = @HTTP::Request::Common::EXPORT;
  81.  
  82. @ISA = qw(LWP::UserAgent);
  83.  
  84. my $UA;
  85.  
  86. sub module {
  87.     my $module = shift;
  88.     $Apache::TestRequest::Module = $module if $module;
  89.     $Apache::TestRequest::Module;
  90. }
  91.  
  92. sub scheme {
  93.     my $scheme = shift;
  94.     $Apache::TestRequest::Scheme = $scheme if $scheme;
  95.     $Apache::TestRequest::Scheme;
  96. }
  97.  
  98. sub module2path {
  99.     my $package = shift;
  100.  
  101.     # httpd (1.3 && 2) / winFU have problems when the first path's
  102.     # segment includes ':' (security precaution which breaks the rfc)
  103.     # so we can't use /TestFoo::bar as path_info
  104.     (my $path = $package) =~ s/::/__/g;
  105.  
  106.     return $path;
  107. }
  108.  
  109. sub user_agent {
  110.     my $args = {@_};
  111.  
  112.     if (delete $args->{reset}) {
  113.         $UA = undef;
  114.     }
  115.  
  116.     if (exists $args->{requests_redirectable}) {
  117.         my $redir = $args->{requests_redirectable};
  118.         if (ref $redir and (@$redir > 1 or $redir->[0] ne 'POST')) {
  119.             $RedirectOK = 1;
  120.         } elsif ($redir) {
  121.             $args->{requests_redirectable} = [ qw/GET HEAD POST/ ]
  122.                 if $have_lwp;
  123.             $RedirectOK = 1;
  124.         } else {
  125.             $RedirectOK = 0;
  126.         }
  127.     }
  128.  
  129.     $args->{keep_alive} ||= $ENV{APACHE_TEST_HTTP11};
  130.  
  131.     if ($args->{keep_alive}) {
  132.         install_http11();
  133.         eval {
  134.             require LWP::Protocol::https; #https10 is the default
  135.             LWP::Protocol::implementor('https', 'LWP::Protocol::https');
  136.         };
  137.     }
  138.  
  139.     eval { $UA ||= __PACKAGE__->new(%$args); };
  140. }
  141.  
  142. sub user_agent_request_num {
  143.     my $res = shift;
  144.     $res->header('Client-Request-Num') ||  #lwp 5.60
  145.         $res->header('Client-Response-Num'); #lwp 5.62+
  146. }
  147.  
  148. sub user_agent_keepalive {
  149.     $ENV{APACHE_TEST_HTTP11} = shift;
  150. }
  151.  
  152. sub do_request {
  153.     my($ua, $method, $url, $callback) = @_;
  154.     my $r = HTTP::Request->new($method, resolve_url($url));
  155.     my $response = $ua->request($r, $callback);
  156.     lwp_trace($response);
  157. }
  158.  
  159. sub hostport {
  160.     my $config = shift || Apache::Test::config();
  161.     local $config->{vars}->{scheme} =
  162.       $Apache::TestRequest::Scheme || $config->{vars}->{scheme};
  163.     my $hostport = $config->hostport;
  164.  
  165.     if (my $module = $Apache::TestRequest::Module) {
  166.         $hostport = $config->{vhosts}->{$module}->{hostport}
  167.           unless $module eq 'default';
  168.     }
  169.  
  170.     $hostport;
  171. }
  172.  
  173. sub resolve_url {
  174.     my $url = shift;
  175.     Carp::croak("no url passed") unless defined $url;
  176.  
  177.     return $url if $url =~ m,^(\w+):/,;
  178.     $url = "/$url" unless $url =~ m,^/,;
  179.  
  180.     my $vars = Apache::Test::vars();
  181.  
  182.     local $vars->{scheme} =
  183.       $Apache::TestRequest::Scheme || $vars->{scheme} || 'http';
  184.  
  185.     scheme_fixup($vars->{scheme});
  186.  
  187.     my $hostport = hostport();
  188.  
  189.     return "$vars->{scheme}://$hostport$url";
  190. }
  191.  
  192. my %wanted_args = map {$_, 1} qw(username password realm content filename
  193.                                  redirect_ok cert);
  194.  
  195. sub wanted_args {
  196.     \%wanted_args;
  197. }
  198.  
  199. $RedirectOK = 1;
  200.  
  201. sub redirect_ok {
  202.     my($self, $request) = @_;
  203.     return 0 if $request->method eq 'POST';
  204.     $RedirectOK;
  205. }
  206.  
  207. my %credentials;
  208.  
  209. #subclass LWP::UserAgent
  210. sub new {
  211.     my $self = shift->SUPER::new(@_);
  212.  
  213.     lwp_debug(); #init from %ENV (set by Apache::TestRun)
  214.  
  215.     my $config = Apache::Test::config();
  216.     if (my $proxy = $config->configure_proxy) {
  217.         #t/TEST -proxy
  218.         $self->proxy(http => "http://$proxy");
  219.     }
  220.  
  221.     $self->timeout(UA_TIMEOUT);
  222.  
  223.     $self;
  224. }
  225.  
  226. sub get_basic_credentials {
  227.     my($self, $realm, $uri, $proxy) = @_;
  228.  
  229.     for ($realm, '__ALL__') {
  230.         next unless $credentials{$_};
  231.         return @{ $credentials{$_} };
  232.     }
  233.  
  234.     return (undef,undef);
  235. }
  236.  
  237. sub vhost_socket {
  238.     my $module = shift;
  239.     local $Apache::TestRequest::Module = $module if $module;
  240.  
  241.     my $hostport = hostport(Apache::Test::config());
  242.     die "can't find hostport for '$module',\n",
  243.         "make sure that vhost_socket() was passed a valid module name"
  244.             unless defined $hostport;
  245.     my($host, $port) = split ':', $hostport;
  246.     my(%args) = (PeerAddr => $host, PeerPort => $port);
  247.  
  248.     if ($module and $module =~ /ssl/) {
  249.         require Net::SSL;
  250.         local $ENV{https_proxy} ||= ""; #else uninitialized value in Net/SSL.pm
  251.         return Net::SSL->new(%args, Timeout => UA_TIMEOUT);
  252.     }
  253.     else {
  254.         require IO::Socket;
  255.         return IO::Socket::INET->new(%args);
  256.     }
  257. }
  258.  
  259. #Net::SSL::getline is nothing like IO::Handle::getline
  260. #could care less about performance here, just need a getline()
  261. #that returns the same results with or without ssl
  262. my %getline = (
  263.     'Net::SSL' => sub {
  264.         my $self = shift;
  265.         my $buf = '';
  266.         my $c = '';
  267.         do {
  268.             $self->read($c, 1);
  269.             $buf .= $c;
  270.         } until ($c eq "\n");
  271.         $buf;
  272.     },
  273. );
  274.  
  275. sub getline {
  276.     my $sock = shift;
  277.     my $class = ref $sock;
  278.     my $method = $getline{$class} || 'getline';
  279.     $sock->$method();
  280. }
  281.  
  282. sub socket_trace {
  283.     my $sock = shift;
  284.     return unless $sock->can('get_peer_certificate');
  285.  
  286.     #like having some -v info
  287.     my $cert = $sock->get_peer_certificate;
  288.     print "#Cipher:  ", $sock->get_cipher, "\n";
  289.     print "#Peer DN: ", $cert->subject_name, "\n";
  290. }
  291.  
  292. sub prepare {
  293.     my $url = shift;
  294.  
  295.     if ($have_lwp) {
  296.         user_agent();
  297.         $url = resolve_url($url);
  298.     }
  299.     else {
  300.         lwp_debug() if $ENV{APACHE_TEST_DEBUG_LWP};
  301.     }
  302.  
  303.     my($pass, $keep) = Apache::TestConfig::filter_args(\@_, \%wanted_args);
  304.  
  305.     %credentials = ();
  306.     if (defined $keep->{username}) {
  307.         $credentials{$keep->{realm} || '__ALL__'} =
  308.           [$keep->{username}, $keep->{password}];
  309.     }
  310.     if (defined(my $content = $keep->{content})) {
  311.         if ($content eq '-') {
  312.             $content = join '', <STDIN>;
  313.         }
  314.         elsif ($content =~ /^x(\d+)$/) {
  315.             $content = 'a' x $1;
  316.         }
  317.         push @$pass, content => $content;
  318.     }
  319.     if ($keep->{cert}) {
  320.         set_client_cert($keep->{cert});
  321.     }
  322.  
  323.     return ($url, $pass, $keep);
  324. }
  325.  
  326. sub UPLOAD {
  327.     my($url, $pass, $keep) = prepare(@_);
  328.  
  329.     local $RedirectOK = exists $keep->{redirect_ok} 
  330.         ? $keep->{redirect_ok}
  331.         : $RedirectOK;
  332.  
  333.     if ($keep->{filename}) {
  334.         return upload_file($url, $keep->{filename}, $pass);
  335.     }
  336.     else {
  337.         return upload_string($url, $keep->{content});
  338.     }
  339. }
  340.  
  341. sub UPLOAD_BODY {
  342.     UPLOAD(@_)->content;
  343. }
  344.  
  345. sub UPLOAD_BODY_ASSERT {
  346.     content_assert(UPLOAD(@_));
  347. }
  348.  
  349. #lwp only supports files
  350. sub upload_string {
  351.     my($url, $data) = @_;
  352.  
  353.     my $CRLF = "\015\012";
  354.     my $bound = 742617000027;
  355.     my $req = HTTP::Request->new(POST => $url);
  356.  
  357.     my $content = join $CRLF,
  358.       "--$bound",
  359.       "Content-Disposition: form-data; name=\"HTTPUPLOAD\"; filename=\"b\"",
  360.       "Content-Type: text/plain", "",
  361.       $data, "--$bound--", "";
  362.  
  363.     $req->header("Content-Length", length($content));
  364.     $req->content_type("multipart/form-data; boundary=$bound");
  365.     $req->content($content);
  366.  
  367.     $UA->request($req);
  368. }
  369.  
  370. sub upload_file {
  371.     my($url, $file, $args) = @_;
  372.  
  373.     my $content = [@$args, filename => [$file]];
  374.  
  375.     $UA->request(HTTP::Request::Common::POST($url,
  376.                  Content_Type => 'form-data',
  377.                  Content      => $content,
  378.     ));
  379. }
  380.  
  381. #useful for POST_HEAD and $DebugLWP (see below)
  382. sub lwp_as_string {
  383.     my($r, $want_body) = @_;
  384.     my $content = $r->content;
  385.  
  386.     unless ($r->isa('HTTP::Request') or
  387.             $r->header('Content-Length') or
  388.             $r->header('Transfer-Encoding'))
  389.     {
  390.         $r->header('Content-Length' => length $content);
  391.         $r->header('X-Content-length-note' => 'added by Apache::TestRequest');
  392.     }
  393.  
  394.     $r->content('') unless $want_body;
  395.  
  396.     (my $string = $r->as_string) =~ s/^/\#/mg;
  397.     $r->content($content); #reset
  398.     $string;
  399. }
  400.  
  401. $DebugLWP = 0; #1 == print METHOD URL and header response for all requests
  402.                #2 == #1 + response body
  403.                #other == passed to LWP::Debug->import
  404.  
  405. sub lwp_debug {
  406.     package main; #wtf: else package in perldb changes
  407.     my $val = $_[0] || $ENV{APACHE_TEST_DEBUG_LWP};
  408.  
  409.     return unless $val;
  410.  
  411.     if ($val =~ /^\d+$/) {
  412.         $Apache::TestRequest::DebugLWP = $val;
  413.         return "\$Apache::TestRequest::DebugLWP = $val\n";
  414.     }
  415.     else {
  416.         my(@args) = @_ ? @_ : split /\s+/, $val;
  417.         require LWP::Debug;
  418.         LWP::Debug->import(@args);
  419.         return "LWP::Debug->import(@args)\n";
  420.     }
  421. }
  422.  
  423. sub lwp_trace {
  424.     my $r = shift;
  425.  
  426.     unless ($r->request->protocol) {
  427.         #lwp always sends a request, but never sets
  428.         #$r->request->protocol, happens deeper in the
  429.         #LWP::Protocol::http* modules
  430.         my $proto = user_agent_request_num($r) ? "1.1" : "1.0";
  431.         $r->request->protocol("HTTP/$proto");
  432.     }
  433.  
  434.     my $want_body = $DebugLWP > 1;
  435.     print "#lwp request:\n",
  436.       lwp_as_string($r->request, $want_body);
  437.  
  438.     print "#server response:\n",
  439.       lwp_as_string($r, $want_body);
  440. }
  441.  
  442. sub lwp_call {
  443.     my($name, $shortcut) = (shift, shift);
  444.  
  445.     my $r = (\&{$name})->(@_);
  446.  
  447.     Carp::croak("$name(@_) didn't return a response object") unless $r;
  448.  
  449.     my $error = "";
  450.     unless ($shortcut) {
  451.         #GET, HEAD, POST
  452.         if ($r->method eq "POST" && !defined($r->header("Content-Length"))) {
  453.             $r->header('Content-Length' => length($r->content));
  454.         }
  455.         $r = $UA ? $UA->request($r) : $r;
  456.         my $proto = $r->protocol;
  457.         if (defined($proto)) {
  458.             if ($proto !~ /^HTTP\/(\d\.\d)$/) {
  459.                 $error = "response had no protocol (is LWP broken or something?)";
  460.             }
  461.             if ($1 ne "1.0" && $1 ne "1.1") {
  462.                 $error = "response had protocol HTTP/$1 (headers not sent?)"
  463.                     unless ($1 eq "0.9" && $ENV{APACHE_TEST_HTTP_09_OK});
  464.             }
  465.         }
  466.     }
  467.  
  468.     if ($DebugLWP and not $shortcut) {
  469.         lwp_trace($r);
  470.     }
  471.  
  472.     Carp::croak($error) if $error;
  473.  
  474.     return $shortcut ? $r->$shortcut() : $r;
  475. }
  476.  
  477. my %shortcuts = (RC   => sub { shift->code },
  478.                  OK   => sub { shift->is_success },
  479.                  STR  => sub { shift->as_string },
  480.                  HEAD => sub { lwp_as_string(shift, 0) },
  481.                  BODY => sub { shift->content },
  482.                  BODY_ASSERT => sub { content_assert(shift) },
  483. );
  484.  
  485. for my $name (@EXPORT) {
  486.     my $package = $have_lwp ?
  487.       'HTTP::Request::Common': 'Apache::TestClient';
  488.  
  489.     my $method = join '::', $package, $name;
  490.     no strict 'refs';
  491.  
  492.     next unless defined &$method;
  493.  
  494.     *$name = sub {
  495.         my($url, $pass, $keep) = prepare(@_);
  496.         local $RedirectOK = exists $keep->{redirect_ok}
  497.             ? $keep->{redirect_ok}
  498.             : $RedirectOK;
  499.         return lwp_call($method, undef, $url, @$pass);
  500.     };
  501.  
  502.     while (my($shortcut, $cv) = each %shortcuts) {
  503.         my $alias = join '_', $name, $shortcut;
  504.         *$alias = sub { lwp_call($name, $cv, @_) };
  505.     }
  506. }
  507.  
  508. my @export_std = @EXPORT;
  509. for my $method (@export_std) {
  510.     push @EXPORT, map { join '_', $method, $_ } keys %shortcuts;
  511. }
  512.  
  513. push @EXPORT, qw(UPLOAD UPLOAD_BODY UPLOAD_BODY_ASSERT);
  514.  
  515. sub to_string {
  516.     my $obj = shift;
  517.     ref($obj) ? $obj->as_string : $obj;
  518. }
  519.  
  520. # request an interpreter instance and use this interpreter id to
  521. # select the same interpreter in requests below
  522. sub same_interp_tie {
  523.     my($url) = @_;
  524.  
  525.     my $res = GET($url, INTERP_KEY, 'tie');
  526.  
  527.     my $same_interp = $res->header(INTERP_KEY);
  528.  
  529.     return $same_interp;
  530. }
  531.  
  532. # run the request though the selected perl interpreter, by polling
  533. # until we found it
  534. # currently supports only GET, HEAD, PUT, POST subs
  535. sub same_interp_do {
  536.     my($same_interp, $sub, $url, @args) = @_;
  537.  
  538.     die "must pass an interpreter id to work with"
  539.         unless defined $same_interp and $same_interp;
  540.  
  541.     push @args, (INTERP_KEY, $same_interp);
  542.  
  543.     my $res      = '';
  544.     my $times    = 0;
  545.     my $found_same_interp = '';
  546.     do {
  547.         #loop until we get a response from our interpreter instance
  548.         $res = $sub->($url, @args);
  549.  
  550.         if ($res and $res->code == 200) {
  551.             $found_same_interp = $res->header(INTERP_KEY) || '';
  552.         }
  553.  
  554.         unless ($found_same_interp eq $same_interp) {
  555.             $found_same_interp = '';
  556.         }
  557.  
  558.         if ($times++ > TRY_TIMES) { #prevent endless loop
  559.             die "unable to find interp $same_interp\n";
  560.         }
  561.     } until ($found_same_interp);
  562.  
  563.     return $found_same_interp ? $res : undef;
  564. }
  565.  
  566.  
  567. sub set_client_cert {
  568.     my $name = shift;
  569.     my $vars = Apache::Test::vars();
  570.     my $dir = join '/', $vars->{sslca}, $vars->{sslcaorg};
  571.  
  572.     if ($name) {
  573.         $ENV{HTTPS_CERT_FILE} = "$dir/certs/$name.crt";
  574.         $ENV{HTTPS_KEY_FILE}  = "$dir/keys/$name.pem";
  575.     }
  576.     else {
  577.         for (qw(CERT KEY)) {
  578.             delete $ENV{"HTTPS_${_}_FILE"};
  579.         }
  580.     }
  581. }
  582.  
  583. #want news: urls to work with the LWP shortcuts
  584. #but cant find a clean way to override the default nntp port
  585. #by brute force we trick Net::NTTP into calling FixupNNTP::new
  586. #instead of IO::Socket::INET::new, we fixup the args then forward
  587. #to IO::Socket::INET::new
  588.  
  589. #also want KeepAlive on for Net::HTTP
  590. #XXX libwww-perl 5.53_xx has: LWP::UserAgent->new(keep_alive => 1);
  591.  
  592. sub install_net_socket_new {
  593.     my($module, $code) = @_;
  594.  
  595.     return unless Apache::Test::have_module($module);
  596.  
  597.     no strict 'refs';
  598.  
  599.     my $new;
  600.     my $isa = \@{"$module\::ISA"};
  601.  
  602.     for (@$isa) {
  603.         last if $new = $_->can('new');
  604.     }
  605.  
  606.     my $fixup_class = "Apache::TestRequest::$module";
  607.     unshift @$isa, $fixup_class;
  608.  
  609.     *{"$fixup_class\::new"} = sub {
  610.         my $class = shift;
  611.         my $args = {@_};
  612.         $code->($args);
  613.         return $new->($class, %$args);
  614.     };
  615. }
  616.  
  617. my %scheme_fixups = (
  618.     'news' => sub {
  619.         return if $INC{'Net/NNTP.pm'};
  620.         eval {
  621.             install_net_socket_new('Net::NNTP' => sub {
  622.                 my $args = shift;
  623.                 my($host, $port) = split ':',
  624.                   Apache::TestRequest::hostport();
  625.                 $args->{PeerPort} = $port;
  626.                 $args->{PeerAddr} = $host;
  627.             });
  628.         };
  629.     },
  630. );
  631.  
  632. sub scheme_fixup {
  633.     my $scheme = shift;
  634.     my $fixup = $scheme_fixups{$scheme};
  635.     return unless $fixup;
  636.     $fixup->();
  637. }
  638.  
  639. # when the client side simply prints the response body which should
  640. # include the test's output, we need to make sure that the request
  641. # hasn't failed, or the test will be skipped instead of indicating the
  642. # error.
  643. sub content_assert {
  644.     my $res = shift;
  645.  
  646.     return $res->content if $res->is_success;
  647.  
  648.     die join "\n", 
  649.         "request has failed (the response code was: " . $res->code . ")",
  650.         "see t/logs/error_log for more details\n";
  651. }
  652.  
  653. 1;
  654.  
  655. =head1 NAME
  656.  
  657. Apache::TestRequest - Send requests to your Apache test server
  658.  
  659. =head1 SYNOPSIS
  660.  
  661.   use Apache::Test qw(ok have_lwp);
  662.   use Apache::TestRequest qw(GET POST);
  663.   use Apache::Constants qw(HTTP_OK);
  664.  
  665.   plan tests => 1, have_lwp;
  666.  
  667.   my $res = GET '/test.html';
  668.   ok $res->code == HTTP_OK, "Request is ok";
  669.  
  670. =head1 DESCRIPTION
  671.  
  672. B<Apache::TestRequest> provides convenience functions to allow you to
  673. make requests to your Apache test server in your test scripts. It
  674. subclasses C<LWP::UserAgent>, so that you have access to all if its
  675. methods, but also exports a number of useful functions likely useful
  676. for majority of your test requests. Users of the old C<Apache::test>
  677. (or C<Apache::testold>) module, take note! Herein lie most of the
  678. functions you'll need to use to replace C<Apache::test> in your test
  679. suites.
  680.  
  681. Each of the functions exported by C<Apache::TestRequest> uses an
  682. C<LWP::UserAgent> object to submit the request and retrieve its
  683. results. The return value for many of these functions is an
  684. HTTP::Response object. See L<HTTP::Response|HTTP::Response> for
  685. documentation of its methods, which you can use in your tests. For
  686. example, use the C<code()> and C<content()> methods to test the
  687. response code and content of your request. Using C<GET>, you can
  688. perform a couple of tests using these methods like this:
  689.  
  690.   use Apache::Test qw(ok have_lwp);
  691.   use Apache::TestRequest qw(GET POST);
  692.   use Apache::Constants qw(HTTP_OK);
  693.  
  694.   plan tests => 2, have_lwp;
  695.  
  696.   my $uri = "/test.html?foo=1&bar=2";
  697.   my $res = GET $uri;
  698.   ok $res->code == HTTP_OK, "Check that the request was OK";
  699.   ok $res->content eq "foo => 1, bar => 2", "Check its content";
  700.  
  701. Note that you can also use C<Apache::TestRequest> with
  702. C<Test::Builder> and its derivatives, including C<Test::More>:
  703.  
  704.   use Test::More;
  705.   # ...
  706.   is $res->code, HTTP_OK, "Check that the request was OK";
  707.   is $res->content, "foo => 1, bar => 2", "Check its content";
  708.  
  709. =head1 CONFIGURATION FUNCTION
  710.  
  711. You can tell C<Apache::TestRequest> what kind of C<LWP::UserAgent>
  712. object to use for its convenience functions with C<user_agent()>. This
  713. function uses its arguments to construct an internal global
  714. C<LWP::UserAgent> object that will be used for all subsequent requests
  715. made by the convenience functions. The arguments it takes are the same
  716. as for the C<LWP::UserAgent> constructor. See the
  717. C<L<LWP::UserAgent|LWP::UserAgent>> documentation for a complete list.
  718.  
  719. The C<user_agent()> function only creates the internal
  720. C<LWP::UserAgent> object the first time it is called. Since this
  721. function is called internally by C<Apache::TestRequest>, you should
  722. always use the C<reset> parameter to force it to create a new global
  723. C<LWP::UserAgent> Object:
  724.  
  725.   Apache::TestRequest::user_agent(reset => 1, %params);
  726.  
  727. C<user_agent()> differs from C<< LWP::UserAgent->new >> in two
  728. additional ways. First, it supports an additional parameter,
  729. C<keep_alive>, which enables connection persistence, where the same
  730. connection is used to process multiple requests (and, according to the
  731. C<L<LWP::UserAgent|LWP::UserAgent>> documentation, has the effect of
  732. loading and enabling the new experimental HTTP/1.1 protocol module).
  733.  
  734. And finally, the semantics of the C<requests_redirectable> parameter is
  735. different than for C<LWP::UserAgent> in that you can pass it a boolean
  736. value as well as an array for C<LWP::UserAgent>. To force
  737. C<Apache::TestRequest> not to follow redirects in any of its convenience
  738. functions, pass a false value to C<requests_redirectable>:
  739.  
  740.   Apache::TestRequest::user_agent(reset => 1,
  741.                                   requests_redirectable => 0);
  742.  
  743. If LWP is not installed, then you can still pass in an array reference
  744. as C<LWP::UserAgent> expects. C<Apache::TestRequest> will examine the
  745. array and allow redirects if the array contains more than one value or
  746. if there is only one value and that value is not "POST":
  747.  
  748.   # Always allow redirection.
  749.   my $redir = have_lwp ? [qw(GET HEAD POST)] : 1;
  750.   Apache::TestRequest::user_agent(reset => 1,
  751.                                   requests_redirectable => $redir);
  752.  
  753. =head1 FUNCTIONS
  754.  
  755. C<Apache::TestRequest> exports a number of functions that will likely
  756. prove convenient for use in the majority of your request tests.
  757.  
  758. =head2 Optional Parameters
  759.  
  760. Each function also takes a number of optional arguments.
  761.  
  762. =over 4
  763.  
  764. =item redirect_ok
  765.  
  766. By default a request will follow redirects retrieved from the server. To
  767. prevent this behavior, pass a false value to a C<redirect_ok>
  768. parameter:
  769.  
  770.   my $res = GET $uri, redirect_ok => 0;
  771.  
  772. Alternately, if all of your tests need to disable redirects, tell
  773. C<Apache::TestRequest> to use an C<LWP::UserAgent> object that
  774. disables redirects:
  775.  
  776.   Apache::TestRequest::user_agent( reset => 1,
  777.                                    requests_redirectable => 0 );
  778.  
  779. =item cert
  780.  
  781. If you need to force an SSL request to use a particular SSL
  782. certificate, pass the name of the certificate via the C<cert>
  783. parameter:
  784.  
  785.   my $res = GET $uri, cert => 'my_cert';
  786.  
  787. =item content
  788.  
  789. If you need to add content to your request, use the C<content>
  790. parameter:
  791.  
  792.   my $res = GET $uri, content => 'hello world!';
  793.  
  794. =item filename
  795.  
  796. The name of a local file on the file system to be sent to the Apache
  797. test server via C<UPLOAD()> and its friends.
  798.  
  799. =back
  800.  
  801. =head2 The Functions
  802.  
  803. =head3 GET
  804.  
  805.   my $res = GET $uri;
  806.  
  807. Sends a simple GET request to the Apache test server. Returns an
  808. C<HTTP::Response> object.
  809.  
  810. =head3 GET_STR
  811.  
  812. A shortcut function for C<GET($uri)-E<gt>as_string>.
  813.  
  814. =head3 GET_BODY
  815.  
  816. A shortcut function for C<GET($uri)-E<gt>content>.
  817.  
  818. =head3 GET_BODY_ASSERT
  819.  
  820. Use this function when your test is outputting content that you need
  821. to check, and you want to make sure that the request was successful
  822. before comparing the contents of the request. If the request was
  823. unsuccessful, C<GET_BODY_ASSERT> will return an error
  824. message. Otherwise it will simply return the content of the request
  825. just as C<GET_BODY> would.
  826.  
  827. =head3 GET_OK
  828.  
  829. A shortcut function for C<GET($uri)-E<gt>is_success>.
  830.  
  831. =head3 GET_RC
  832.  
  833. A shortcut function for C<GET($uri)-E<gt>code>.
  834.  
  835. =head3 GET_HEAD
  836.  
  837. Throws out the content of the request, and returns the string
  838. representation of the request. Since the body has been thrown out, the
  839. representation will consist solely of the headers. Furthermore,
  840. C<GET_HEAD> inserts a "#" at the beginning of each line of the return
  841. string, so that the contents are suitable for printing to STDERR
  842. during your tests without interfering with the workings of
  843. C<Test::Harness>.
  844.  
  845. =head3 HEAD
  846.  
  847.   my $res = HEAD $uri;
  848.  
  849. Sends a HEAD request to the Apache test server. Returns an
  850. C<HTTP::Response> object.
  851.  
  852. =head3 HEAD_STR
  853.  
  854. A shortcut function for C<HEAD($uri)-E<gt>as_string>.
  855.  
  856. =head3 HEAD_BODY
  857.  
  858. A shortcut function for C<HEAD($uri)-E<gt>content>. Of course, this
  859. means that it will likely return nothing.
  860.  
  861. =head3 HEAD_BODY_ASSERT
  862.  
  863. Use this function when your test is outputting content that you need
  864. to check, and you want to make sure that the request was successful
  865. before comparing the contents of the request. If the request was
  866. unsuccessful, C<HEAD_BODY_ASSERT> will return an error
  867. message. Otherwise it will simply return the content of the request
  868. just as C<HEAD_BODY> would.
  869.  
  870. =head3 HEAD_OK
  871.  
  872. A shortcut function for C<GET($uri)-E<gt>is_success>.
  873.  
  874. =head3 HEAD_RC
  875.  
  876. A shortcut function for C<GET($uri)-E<gt>code>.
  877.  
  878. =head3 HEAD_HEAD
  879.  
  880. Throws out the content of the request, and returns the string
  881. representation of the request. Since the body has been thrown out, the
  882. representation will consist solely of the headers. Furthermore,
  883. C<GET_HEAD> inserts a "#" at the beginning of each line of the return
  884. string, so that the contents are suitable for printing to STDERR
  885. during your tests without interfering with the workings of
  886. C<Test::Harness>.
  887.  
  888. =head3 PUT
  889.  
  890.   my $res = PUT $uri;
  891.  
  892. Sends a simple PUT request to the Apache test server. Returns an
  893. C<HTTP::Response> object.
  894.  
  895. =head3 PUT_STR
  896.  
  897. A shortcut function for C<PUT($uri)-E<gt>as_string>.
  898.  
  899. =head3 PUT_BODY
  900.  
  901. A shortcut function for C<PUT($uri)-E<gt>content>.
  902.  
  903. =head3 PUT_BODY_ASSERT
  904.  
  905. Use this function when your test is outputting content that you need
  906. to check, and you want to make sure that the request was successful
  907. before comparing the contents of the request. If the request was
  908. unsuccessful, C<PUT_BODY_ASSERT> will return an error
  909. message. Otherwise it will simply return the content of the request
  910. just as C<PUT_BODY> would.
  911.  
  912. =head3 PUT_OK
  913.  
  914. A shortcut function for C<PUT($uri)-E<gt>is_success>.
  915.  
  916. =head3 PUT_RC
  917.  
  918. A shortcut function for C<PUT($uri)-E<gt>code>.
  919.  
  920. =head3 PUT_HEAD
  921.  
  922. Throws out the content of the request, and returns the string
  923. representation of the request. Since the body has been thrown out, the
  924. representation will consist solely of the headers. Furthermore,
  925. C<PUT_HEAD> inserts a "#" at the beginning of each line of the return
  926. string, so that the contents are suitable for printing to STDERR
  927. during your tests without interfering with the workings of
  928. C<Test::Harness>.
  929.  
  930. =head3 POST
  931.  
  932.   my $res = POST $uri, [ arg => $val, arg2 => $val ];
  933.  
  934. Sends a POST request to the Apache test server and returns an
  935. C<HTTP::Response> object. An array reference of parameters passed as
  936. the second argument will be submitted to the Apache test server as the
  937. POST content. Parameters corresponding to those documented in
  938. L<Optional Parameters|/Optional
  939. Parameters> can follow the optional array reference of parameters, or after
  940. C<$uri>.
  941.  
  942. To upload a chunk of data, simply use:
  943.  
  944.   my $res = POST $uri, content => $data;
  945.  
  946. =head3 POST_STR
  947.  
  948. A shortcut function for C<POST($uri, @args)-E<gt>content>.
  949.  
  950. =head3 POST_BODY
  951.  
  952. A shortcut function for C<POST($uri, @args)-E<gt>content>.
  953.  
  954. =head3 POST_BODY_ASSERT
  955.  
  956. Use this function when your test is outputting content that you need
  957. to check, and you want to make sure that the request was successful
  958. before comparing the contents of the request. If the request was
  959. unsuccessful, C<POST_BODY_ASSERT> will return an error
  960. message. Otherwise it will simply return the content of the request
  961. just as C<POST_BODY> would.
  962.  
  963. =head3 POST_OK
  964.  
  965. A shortcut function for C<POST($uri, @args)-E<gt>is_success>.
  966.  
  967. =head3 POST_RC
  968.  
  969. A shortcut function for C<POST($uri, @args)-E<gt>code>.
  970.  
  971. =head3 POST_HEAD
  972.  
  973. Throws out the content of the request, and returns the string
  974. representation of the request. Since the body has been thrown out, the
  975. representation will consist solely of the headers. Furthermore,
  976. C<POST_HEAD> inserts a "#" at the beginning of each line of the return
  977. string, so that the contents are suitable for printing to STDERR
  978. during your tests without interfering with the workings of
  979. C<Test::Harness>.
  980.  
  981. =head3 UPLOAD
  982.  
  983.   my $res = UPLOAD $uri, \@args, filename => $filename;
  984.  
  985. Sends a request to the Apache test server that includes an uploaded
  986. file. Other POST parameters can be passed as a second argument as an
  987. array reference.
  988.  
  989. C<Apache::TestRequest> will read in the contents of the file named via
  990. the C<filename> parameter for submission to the server. If you'd
  991. rather, you can submit use the C<content> parameter instead of
  992. C<filename>, and its value will be submitted to the Apache server as
  993. file contents:
  994.  
  995.   my $res = UPLOAD $uri, undef, content => "This is file content";
  996.  
  997. The name of the file sent to the server will simply be "b". Note that
  998. in this case, you cannot pass other POST arguments to C<UPLOAD()> --
  999. they would be ignored.
  1000.  
  1001. =head3 UPLOAD_BODY
  1002.  
  1003. A shortcut function for C<UPLOAD($uri, @params)-E<gt>content>.
  1004.  
  1005. =head3 UPLOAD_BODY_ASSERT
  1006.  
  1007. Use this function when your test is outputting content that you need
  1008. to check, and you want to make sure that the request was successful
  1009. before comparing the contents of the request. If the request was
  1010. unsuccessful, C<UPLOAD_BODY_ASSERT> will return an error
  1011. message. Otherwise it will simply return the content of the request
  1012. just as C<UPLOAD_BODY> would.
  1013.  
  1014. =head3 OPTIONS
  1015.  
  1016.   my $res = OPTIONS $uri;
  1017.  
  1018. Sends an C<OPTIONS> request to the Apache test server. Returns an
  1019. C<HTTP::Response> object with the I<Allow> header, indicating which
  1020. methods the server supports. Possible methods include C<OPTIONS>,
  1021. C<GET>, C<HEAD> and C<POST>. This function thus can be useful for
  1022. testing what options the Apache server supports. Consult the HTTPD 1.1
  1023. specification, section 9.2, at
  1024. I<http://www.faqs.org/rfcs/rfc2616.html> for more information.
  1025.  
  1026. =head1 ENVIRONMENT VARIABLES
  1027.  
  1028. The following environment variables can affect the behavior of
  1029. C<Apache::TestRequest>:
  1030.  
  1031. =over
  1032.  
  1033. =item APACHE_TEST_PRETEND_NO_LWP
  1034.  
  1035. If the environment variable C<APACHE_TEST_PRETEND_NO_LWP> is set to a
  1036. true value, C<Apache::TestRequest> will pretend that LWP is not
  1037. available so one can test whether the test suite will survive on a
  1038. system which doesn't have libwww-perl installed.
  1039.  
  1040. =item APACHE_TEST_HTTP_09_OK
  1041.  
  1042. If the environment variable C<APACHE_TEST_HTTP_09_OK> is set to a
  1043. true value, C<Apache::TestRequest> will allow HTTP/0.9 responses
  1044. from the server to proceed.  The default behavior is to die if
  1045. the response protocol is not either HTTP/1.0 or HTTP/1.1.
  1046.  
  1047. =back
  1048.  
  1049. =head1 SEE ALSO
  1050.  
  1051. L<Apache::Test|Apache::Test> is the main Apache testing module. Use it
  1052. to set up your tests, create a plan, and to ensure that you have the
  1053. Apache version and modules you need.
  1054.  
  1055. Use L<Apache::TestMM|Apache::TestMM> in your I<Makefile.PL> to set up
  1056. your distribution for testing.
  1057.  
  1058. =head1 AUTHOR
  1059.  
  1060. Doug MacEachern with contributions from Geoffrey Young, Philippe
  1061. M. Chiasson, Stas Bekman and others. Documentation by David Wheeler.
  1062.  
  1063. Questions can be asked at the test-dev <at> httpd.apache.org list. For
  1064. more information see: I<http://httpd.apache.org/test/> and
  1065. I<http://perl.apache.org/docs/general/testing/testing.html>.
  1066.