Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re: How to test a module which needs a local HTTP server?

by Realbot (Scribe)
on Feb 03, 2005 at 17:56 UTC ( #427742=note: print w/replies, xml ) Need Help??

in reply to How to test a module which needs a local HTTP server?

I had this problem recently and after having taken a look at Gisle Aas HTTP::Daemon tests, I came up with this structure.
The two main files (, need not to be touched. defines a subroutine (runWebTest) which takes two parameters.
The first parameter is a reference to a test routine to execute (defined in sampletest.t). This test sub will receive the server URL as parameter.
The second one is a file which should contains a subroutine named "handler" which will receive two parameters (HTTP::Request, HTTP::Daemon::ClientConn) and must supply the HTTP server logic for our test.

Here is the code with a sample test:
File: sampletest.t
use strict; use Test::More tests => 2; sub test { my $baseUrl = shift; use LWP::UserAgent; my $ua = new LWP::UserAgent; my $response = $ua->get($baseUrl."sample"); ok($response->is_success, "get ok"); like ($response->content, qr/expected text/, "sample test"); } require ''; runWebTest(\&test, '');
sub handler { my ($r, $c) = @_; if ($r->method eq 'GET' and $r->url->path eq "/sample") { $c->send_basic_header(200); print $c "Content-Type: text/plain\015\012"; $c->send_crlf; print $c "this is the expected text"; } else { $c->send_error(404); } } 1;
use strict; use Config; sub runWebTest { my ($testSub, $handlerScript) = @_; my $perl = $Config{'perlpath'}; $perl = $^X if $^O eq 'VMS' or -x $^X and $^X =~ m,^([a-z]:)?/,i; open(DAEMON, "$perl $handlerScript |") or die " +Can't exec daemon: $!"; my $serverUrl = <DAEMON>; ($serverUrl) = $serverUrl =~ /<([^>]+)>/; sleep(2); $testSub->($serverUrl); quitWebServer($serverUrl); } sub quitWebServer { my $baseUrl = shift; use LWP::UserAgent; my $ua = new LWP::UserAgent; return $ua->get($baseUrl."quit"); } 1;
use strict; $| = 1; # autoflush require IO::Socket; require HTTP::Daemon; my $handlerScript = shift || die "no handler given"; my $d = HTTP::Daemon->new() || die; print "HTTP Server started at: <", $d->url, ">\n"; open(STDOUT, $^O eq 'VMS'? ">nl: " : ">/dev/null"); print STDERR "HTTP Server started\n"; while (my $c = $d->accept) { while (my $r = $c->get_request) { if ($r) { if ($r->method eq 'GET' and $r->url->path eq "/quit") { $c->send_error(503, "Bye, bye"); print STDERR "HTTP Server terminated\n"; exit; # terminate HTTP server } else { require $handlerScript; handler($r, $c); } } } $c->close; $c = undef; # close connection }

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://427742]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2022-12-05 11:03 GMT
Find Nodes?
    Voting Booth?

    No recent polls found