Test::Override::UserAgent
I have just uploaded a new module to the CPAN: Test::Override::UserAgent. This is geared toward developers that use LWP::UserAgent in their modules and want to easily test their code without having a live Internet connection or starting up a test server to make requests against. Just about every single module I have on the CPAN uses LWP::UserAgent and makes requests against live servers (usually they are doing web scraping). Before I was using Test::MockObject, but that was tedious at best.
The goal of Test::Override::UserAgent is to be able to write response overrides easily. The module allows for the author to create a class consisting of only definitions for overrides so the override definitions do not have to be repeated in each test file. An example override class would look like:
package t::CustomUA; use 5.008; use Test::Override::UserAgent for => 'configuration'; # Disable live requests (the default, anyhow) allow_live(0); override_request host => 'localhost', path => '/test', sub { return [200, ['content-type' => 'text/plain'], ['Test response']]; }; 1; |
This will cause requests that have a host of localhost
and a path of /test
to get a response back of text/plain
with the Test response
body. This configuration can then be used in a test file:
#!perl -T use 5.008; use Test::More tests => 1; use t::CustomUA; use My::Module; # Your awesome module to test my $object = new_ok 'My::Module'; # Your module has a way to set the user agent it uses t::CustomUA->configuration->install_in_user_agent($object->user_agent); # Perhaps your module has no way to set the user agent # or there is something down stream that uses a user agent. my $scope = t::CustomUA->configuration->install_in_scope; # Do tests that make requests by LWP::UserAgent # End the scope override undef $scope; |