Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to setup a local, self-contained web server for perl testing?

I'm building a perl application to archive simple web pages (i.e. static pages with no query strings involved). I'd like to write tests to verify the functionality of the module that will be accessing the remote files. To make the tests self-reliant, I'm looking for a simple, self-contained web server that the test scripts can use locally.

Below is an example which outlines what I'm trying to do. I've cut it down to a minimum with the following directory structure:

./MirrorPage.pm
./t/001_get_url.t
./t/test-docroot/test-1.json

Contents of "./MirrorPage.pm":

package MirrorPage;

use Moose;
use LWP::Simple;
use namespace::autoclean;

sub get_url {

    my ($self, $url_to_get) = @_;

    ### grab the contents of the url
    my $url_data = get($url_to_get);

    ### return the contents.
    return $url_data;

}

__PACKAGE__->meta->make_immutable;

1;

Contents of "./t/001_get_url.t":

#!/usr/bin/perl 

use Modern::Perl;
use Test::More;
use MirrorPage;

    ### Start test www server on port 8123 here ###

my $t = new_ok('MirrorPage', undef, 'Create MirrorPage');

is(
    $t->get_url("http://localhost:8123/test-1.json"), 
    '{ testkey: "testvalue" }',
    "Verify the data."
);

    ### Kill test www server here ###

done_testing();

Contents of "./t/test-docroot/test-1.json":

{ testkey: "testvalue" }

The goal is to start and kill a self-contained web server at the corresponding comment locations in "./t/001_get_url.t". The web server needs to serve the contents of the "./t/test-docroot" directory as its document root.

Given all that: What is the best/simplest way to setup a self-contained web server to provide static files for testing in perl?

like image 718
Alan W. Smith Avatar asked Sep 01 '25 20:09

Alan W. Smith


1 Answers

I would mock the HTTP call near the top of your .t file (if you're only wanting to test MirrorPage.pm):

my $mock = new Test::MockObject();
$mock->fake_module( 'LWP::Simple', get => sub { return '{ testkey: "testvalue" }' } );
like image 94
Chris J Avatar answered Sep 03 '25 14:09

Chris J