WWW-Mechanize
view release on metacpan or search on metacpan
t/local/LocalServer.pm view on Meta::CPAN
package LocalServer;
# start a fake webserver, fork, and connect to ourselves
use warnings;
use strict;
# this has to happen here because LWP::Simple creates a $ua
# on load so any time after this is too late.
BEGIN {
delete @ENV{
qw(
HTTP_PROXY http_proxy CGI_HTTP_PROXY
HTTPS_PROXY https_proxy HTTP_PROXY_ALL http_proxy_all
)
};
}
use Carp qw( carp croak );
use File::Temp ();
use LWP::Simple qw( get );
use Path::Tiny qw( path );
use URI::URL ();
=head1 SYNOPSIS
use LWP::Simple qw(get);
my $server = Test::HTTP::LocalServer->spawn;
ok get $server->url, "Retrieve " . $server->url;
$server->stop;
=head1 METHODS
=head2 C<Test::HTTP::LocalServer-E<gt>spawn %ARGS>
This spawns a new HTTP server. The server will stay running until C<< $server->stop >> is called.
Valid arguments are:
=over 4
=item *
C<< html => >> scalar containing the page to be served
=item *
C<< file => >> filename containing the page to be served
=item *
C<< debug => 1 >> to make the spawned server output debug information
=item *
C<< eval => >> string that will get evaluated per request in the server
Try to avoid characters that are special to the shell, especially quotes. A good idea for a slow
server would be
eval => sleep+10
=back
All served HTML will have the first %s replaced by the current location.
The following entries will be removed from C<%ENV>:
HTTP_PROXY
http_proxy
CGI_HTTP_PROXY
HTTPS_PROXY
https_proxy
HTTP_PROXY_ALL
http_proxy_all
=cut
sub spawn {
my ( $class, %args ) = @_;
my $self = {%args};
bless $self, $class;
local $ENV{TEST_HTTP_VERBOSE};
$ENV{TEST_HTTP_VERBOSE} = 1
if ( delete $args{debug} );
$self->{delete} = [];
if ( my $html = delete $args{html} ) {
# write the html to a temp file
my ( $fh, $tempfile ) = File::Temp::tempfile();
binmode $fh;
print $fh $html
or die "Couldn't write tempfile $tempfile : $!";
close $fh;
push @{ $self->{delete} }, $tempfile;
$args{file} = $tempfile;
}
my ( $fh, $logfile ) = File::Temp::tempfile();
close $fh;
push @{ $self->{delete} }, $logfile;
$self->{logfile} = $logfile;
my $web_page = delete $args{file} || q{};
my $server_file = path('t/local/log-server')->absolute;
my @opts;
push @opts, "-e" => qq{"} . delete( $args{eval} ) . qq{"}
if $args{eval};
my $pid = open my $server,
qq'$^X "$server_file" "$web_page" "$logfile" @opts|'
or croak "Couldn't spawn local server $server_file : $!";
my $url = <$server>;
chomp $url;
die "Couldn't read back local server url"
unless $url;
$self->{_server_url} = URI::URL->new($url);
$self->{_fh} = $server;
$self->{_pid} = $pid;
$self;
}
=head2 C<< $server->port >>
This returns the port of the current server. As new instances will most likely run under a
different port, this is convenient if you need to compare results from two runs.
=cut
sub port {
carp __PACKAGE__ . '::port called without a server'
( run in 0.317 second using v1.01-cache-2.11-cpan-d7a12ab2c7f )