- Test::Mock::Simple
Mocking function of external web call
- 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.
examples/mock-lwp/lib/MyWebAPI.pm
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;
examples/mock-lwp/bin/count.pl
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