Mocking function of external web call
-
Test::Mock::Simple
-
We have an application that uses LWP::Simple
-
It gets a list of strings and tells us how many times each string appears on that web page.
-
We'll talk about the commented out code a bit later.
package MyWebAPI;
use strict;
use warnings;
use LWP::Simple qw(get);
sub new {
my ($class, $url) = @_;
my $self = bless {}, $class;
$self->{url} = $url;
return $self;
}
sub count_strings {
my ($self, @strings) = @_;
my $content = get $self->{url};
#my $content = LWP::Simple::get $self->{url};
my %data;
foreach my $str (@strings) {
$data{$str} = () = $content =~ /$str/ig;
}
return \%data;
}
1;
use strict;
use warnings;
use MyWebAPI;
my ($url, @names) = @ARGV;
die "Usage: URL 1-or-more-EXPRESSION\n" if not @names;
my $myapi = MyWebAPI->new($url);
my $res = $myapi->count_strings(@names);
for my $name (sort keys %$res) {
print "$name $res->{$name}\n";
}
perl -Ilib bin/count.pl https://code-maven.com/ perl python Java