smonff
smonff

Reputation: 3499

How to check network availability in my Perl module tests?

Working on a Perl module using networking tasks, I have to check the network availability or failure when testing. More exactly, I need to test network availability, then a specific API availability.

Here is some code from my api-interraction.t test :

use strict;
use warnings;
use Test::More;

# Foo::Module is using WWW::Curl::Simple
my $requester = Foo::Module->new();

my $query = "http://existing-doma.in?with=some&useful=parameters";
# We should be able to test a bad request too
my $wrong_query = "http://deaddoma.in";

my $api_test_code = $requester->get_api_status($query);

if ($api_test_code == 200) {
    cmp_ok($api_test_code, "==", 200, "API reachable - HTTP status = 200");
} else {
    cmp_ok($api_test_code, "!=", 200, "API not reachable - HTTP status != 200");
}            

It seems it can't work when network fails. Any recommendation on how I could achieve this better ?

Upvotes: 3

Views: 244

Answers (1)

mcduffee
mcduffee

Reputation: 1257

use strict;
use warnings;
use LWP::Simple;
use Test::More tests => 1;

my $query = "http://existing-doma.in";
my $browser = LWP::UserAgent->new;
my $response = $browser->get( $query );

is $response->code, 200;

Upvotes: 4

Related Questions