Skip to content

Commit

Permalink
make the API methods more generic by factoring out bits assuming HTTP…
Browse files Browse the repository at this point in the history
…::Response
  • Loading branch information
karenetheridge committed Aug 16, 2015
1 parent 3f6583c commit 71a1a79
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 18 deletions.
2 changes: 2 additions & 0 deletions Changes
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ Revision history for Test-LWP-UserAgent
{{$NEXT}}
- change network tests from hitting example.com to cpan.org, in the
hopes of getting past more testers' firewalls
- factor a few bits of HTTP::Response-specific code out into private
methods, to ease future refactoring

0.029 2015-05-23 03:43:46Z
- add use of Test::RequiresInternet to avoid failing tests on
Expand Down
45 changes: 27 additions & 18 deletions lib/Test/LWP/UserAgent.pm
Original file line number Diff line number Diff line change
Expand Up @@ -91,17 +91,11 @@ sub map_network_response
{
my ($self, $request_description) = @_;

if (blessed $self)
{
# we cannot call ::request here, or we end up in an infinite loop
push @{$self->{__response_map}},
[ $request_description, sub { $self->SUPER::send_request($_[0]) } ];
}
else
{
push @response_map,
[ $request_description, sub { LWP::UserAgent->new->send_request($_[0]) } ];
}
push (
@{ blessed($self) ? $self->{__response_map} : \@response_map },
[ $request_description, $self->_response_send_request ],
);

return $self;
}

Expand Down Expand Up @@ -132,13 +126,7 @@ sub register_psgi
carp 'register_psgi: app is not a coderef, it\'s a ', ref($app)
unless __isa_coderef($app);

carp 'register_psgi: did you forget to load HTTP::Message::PSGI?'
unless HTTP::Request->can('to_psgi') and HTTP::Response->can('from_psgi');

return $self->map_response(
$domain,
sub { HTTP::Response->from_psgi($app->($_[0]->to_psgi)) },
);
return $self->map_response($domain, $self->_psgi_to_response($app));
}

sub unregister_psgi
Expand Down Expand Up @@ -316,6 +304,27 @@ sub send_request
return $response;
}

# turns a PSGI app into a subref returning an HTTP::Response
sub _psgi_to_response
{
my ($self, $app) = @_;

carp 'register_psgi: did you forget to load HTTP::Message::PSGI?'
unless HTTP::Request->can('to_psgi') and HTTP::Response->can('from_psgi');

return sub { HTTP::Response->from_psgi($app->($_[0]->to_psgi)) };
}

# returns a subref that returns an HTTP::Response from a real network request
sub _response_send_request
{
my $self = shift;

# we cannot call ::request here, or we end up in an infinite loop
return sub { $self->SUPER::send_request($_[0]) } if blessed $self;
return sub { LWP::UserAgent->new->send_request($_[0]) };
}

sub __isa_coderef
{
ref $_[0] eq 'CODE'
Expand Down

0 comments on commit 71a1a79

Please sign in to comment.