.\" Automatically generated by Pod::Man 4.07 (Pod::Simple 3.32) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .if !\nF .nr F 0 .if \nF>0 \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} .\} .\" ======================================================================== .\" .IX Title "Test::LWP::UserAgent 3pm" .TH Test::LWP::UserAgent 3pm "2016-11-15" "perl v5.24.1" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Test::LWP::UserAgent \- A LWP::UserAgent suitable for simulating and testing network calls .SH "VERSION" .IX Header "VERSION" version 0.031 .SH "SYNOPSIS" .IX Header "SYNOPSIS" In your application code: .PP .Vb 3 \& use URI; \& use HTTP::Request::Common; \& use LWP::UserAgent; \& \& my $useragent = $self\->useragent || LWP::UserAgent\->new; \& \& my $uri = URI\->new(\*(Aqhttp://example.com\*(Aq); \& $uri\->port(\*(Aq3000\*(Aq); \& $uri\->path(\*(Aqsuccess\*(Aq); \& my $request = POST($uri, a => 1); \& my $response = $useragent\->request($request); .Ve .PP Then, in your tests: .PP .Vb 2 \& use Test::LWP::UserAgent; \& use Test::More; \& \& my $useragent = Test::LWP::UserAgent\->new; \& $useragent\->map_response( \& qr{example.com/success}, HTTP::Response\->new(\*(Aq200\*(Aq, \*(AqOK\*(Aq, [\*(AqContent\-Type\*(Aq => \*(Aqtext/plain\*(Aq], \*(Aq\*(Aq)); \& $useragent\->map_response( \& qr{example.com/fail}, HTTP::Response\->new(\*(Aq500\*(Aq, \*(AqERROR\*(Aq, [\*(AqContent\-Type\*(Aq => \*(Aqtext/plain\*(Aq], \*(Aq\*(Aq)); \& \& # now, do something that sends a request, and test how your application \& # responds to that response .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module is a subclass of LWP::UserAgent which overrides a few key low-level methods that are concerned with actually sending your request over the network, allowing an interception of that request and simulating a particular response. This greatly facilitates testing of client networking code where the server follows a known protocol. .PP The synopsis describes a typical case where you want to test how your application reacts to various responses from the server. This module will let you send back various responses depending on the request, without having to set up a real server to test against. This can be invaluable when you need to test edge cases or error conditions that are not normally returned from the server. .PP There are a lot of different ways you can set up the response mappings, and hook into this module; see the documentation for the individual interface methods. .PP You can use a \s-1PSGI\s0 app to handle the requests \- see \fIexamples/call_psgi.t\fR in this dist, and also \*(L"register_psgi\*(R" below. .PP \&\s-1OR,\s0 you can route some or all requests through the network as normal, but still gain the hooks provided by this class to test what was sent and received: .PP .Vb 1 \& my $useragent = Test::LWP::UserAgent\->new(network_fallback => 1); .Ve .PP or: .PP .Vb 1 \& $useragent\->map_network_response(qr/real.network.host/); \& \& # ... generate a request... \& \& # and then in your tests: \& is( \& $useragent\->last_useragent\->timeout, \& 180, \& \*(Aqtimeout was overridden properly\*(Aq, \& ); \& is( \& $useragent\->last_http_request_sent\->uri, \& \*(Aquri my code should have constructed\*(Aq, \& ); \& is( \& $useragent\->last_http_response_received\->code, \& \*(Aq200\*(Aq, \& \*(AqI should have gotten an OK response\*(Aq, \& ); .Ve .SS "Ensuring the right useragent is used" .IX Subsection "Ensuring the right useragent is used" Note that LWP::UserAgent itself is not monkey-patched \- you must use this module (or a subclass) to send your request, or it cannot be caught and processed. .PP One common mechanism to swap out the useragent implementation is via a lazily-built Moose attribute; if no override is provided at construction time, default to \f(CW\*(C`LWP::UserAgent\->new(%options)\*(C'\fR. .PP Additionally, most methods can be called as class methods, which will store the settings globally, so that any instance of Test::LWP::UserAgent can use them, which can simplify some of your application code. .SH "METHODS" .IX Header "METHODS" .ie n .SS """new""" .el .SS "\f(CWnew\fP" .IX Subsection "new" Accepts all options as in LWP::UserAgent, including \f(CW\*(C`use_eval\*(C'\fR, an undocumented boolean which is enabled by default. When set, sending the \s-1HTTP\s0 request is wrapped in an \f(CW\*(C`eval {}\*(C'\fR, allowing all exceptions to be caught and an appropriate error response (usually \s-1HTTP 500\s0) to be returned. You may want to unset this if you really want to test extraordinary errors within your networking code. Normally, you should leave it alone, as LWP::UserAgent and this module are capable of handling normal errors. .PP Plus, this option is added: .IP "\(bu" 4 \&\f(CW\*(C`network_fallback => \*(C'\fR .Sp If true, requests passing through this object that do not match a previously-configured mapping or registration will be directed to the network. (To only divert \fImatched\fR requests rather than unmatched requests, use \&\f(CW\*(C`map_network_response\*(C'\fR, see below.) .Sp This option is also available as a read/write accessor via \&\f(CW\*(C`$useragent\->network_fallback()\*(C'\fR. .PP \&\fBAll other methods below may be called on a specific object instance, or as a class method.\fR If called as on a blessed object, the action performed or data returned is limited to just that object; if called as a class method, the action or data is global. .ie n .SS """map_response($request_specification, $http_response)""" .el .SS "\f(CWmap_response($request_specification, $http_response)\fP" .IX Subsection "map_response($request_specification, $http_response)" With this method, you set up what HTTP::Response should be returned for each request received. .PP The request match specification can be described in multiple ways: .IP "\(bu" 4 string .Sp The string is matched identically against the \f(CW\*(C`host\*(C'\fR field of the \s-1URI\s0 in the request. .Sp .Vb 1 \& $test_ua\->map_response(\*(Aqexample.com\*(Aq, HTTP::Response\->new(\*(Aq500\*(Aq)); .Ve .IP "\(bu" 4 regexp .Sp The regexp is matched against the \s-1URI\s0 in the request. .Sp .Vb 2 \& $test_ua\->map_response(qr{foo/bar}, HTTP::Response\->new(\*(Aq200\*(Aq)); \& $test_ua\->map_response(qr{baz/quux}, HTTP::Response\->new(\*(Aq500\*(Aq)); .Ve .IP "\(bu" 4 code .Sp The provided coderef is passed a single argument, the HTTP::Request, and returns a boolean indicating if there is a match. .Sp .Vb 7 \& # matches all GET and POST requests \& $test_ua\->map_response(sub { \& my $request = shift; \& return 1 if $request\->method eq \*(AqGET\*(Aq || $request\->method eq \*(AqPOST\*(Aq; \& }, \& HTTP::Response\->new(\*(Aq200\*(Aq), \& ); .Ve .IP "\(bu" 4 HTTP::Request object .Sp The HTTP::Request object is matched identically (including all query parameters, headers etc) against the provided object. .PP The response can be represented in multiple ways: .IP "\(bu" 4 a literal HTTP::Response object: .Sp .Vb 1 \& HTTP::Response\->new(...); .Ve .IP "\(bu" 4 as a coderef that is run at the time of matching, with the request passed as the single argument: .Sp .Vb 4 \& sub { \& my $request = shift; \& return HTTP::Response\->new(...); \& } .Ve .IP "\(bu" 4 .Sp a blessed object that implements the \f(CW\*(C`request\*(C'\fR method, which will be saved as a coderef thusly (this allows you to use your own dispatcher implementation): .Sp .Vb 4 \& sub { \& my $request = shift; \& return $response\->request($request); \& } .Ve .PP Instance mappings take priority over global (class method) mappings \- if no matches are found from mappings added to the instance, the global mappings are then examined. When no matches have been found, a 404 response is returned. .PP This method returns the \f(CW\*(C`Test::LWP::UserAgent\*(C'\fR object or class. .ie n .SS """map_network_response($request_specification)""" .el .SS "\f(CWmap_network_response($request_specification)\fP" .IX Subsection "map_network_response($request_specification)" Same as \f(CW\*(C`map_response\*(C'\fR above, only requests that match this specification will not use a response that you specify, but instead uses a real LWP::UserAgent to dispatch your request to the network. .PP If called on an instance, all options passed to the constructor (e.g. timeout) are used for making the real network call. If called as a class method, a pristine LWP::UserAgent object with no customized options will be used instead. .PP This method returns the \f(CW\*(C`Test::LWP::UserAgent\*(C'\fR object or class. .ie n .SS """unmap_all(instance_only?)""" .el .SS "\f(CWunmap_all(instance_only?)\fP" .IX Subsection "unmap_all(instance_only?)" When called as a class method, removes all mappings set up globally (across all objects). Mappings set up on an individual object will still remain. .PP When called as an object method, removes \fIall\fR mappings both globally and on this instance, unless a true value is passed as an argument, in which only mappings local to the object will be removed. (Any true value will do, so you can pass a meaningful string.) .PP This method returns the \f(CW\*(C`Test::LWP::UserAgent\*(C'\fR object or class. .ie n .SS """register_psgi($domain, $app)""" .el .SS "\f(CWregister_psgi($domain, $app)\fP" .IX Subsection "register_psgi($domain, $app)" Register a particular \s-1PSGI\s0 app (code reference) to be used when requests for a domain are received (matches are made exactly against \&\f(CW\*(C`$request\->uri\->host\*(C'\fR). The request is passed to the \f(CW$app\fR for processing, and the \s-1PSGI\s0 response is converted back to an HTTP::Response (you must already have loaded HTTP::Message::PSGI or equivalent, as this is not done for you). .PP You can also use \f(CW\*(C`register_psgi\*(C'\fR with a regular expression as the first argument, or any of the other forms used by \f(CW\*(C`map_response\*(C'\fR, if you wish, as calling \f(CW\*(C`$test_ua\->register_psgi($domain, $app)\*(C'\fR is equivalent to: .PP .Vb 4 \& $test_ua\->map_response( \& $domain, \& sub { HTTP::Response\->from_psgi($app\->($_[0]\->to_psgi)) }, \& ); .Ve .PP This feature is useful for testing your \s-1PSGI\s0 applications, or for simulating a server so as to test your client code. .PP You might find using Plack::Test or Plack::Test::ExternalServer easier for your needs, so check those out as well. .PP This method returns the \f(CW\*(C`Test::LWP::UserAgent\*(C'\fR object or class. .ie n .SS """unregister_psgi($domain, instance_only?)""" .el .SS "\f(CWunregister_psgi($domain, instance_only?)\fP" .IX Subsection "unregister_psgi($domain, instance_only?)" When called as a class method, removes a domain\->\s-1PSGI\s0 app entry that had been registered globally. Some mappings set up on an individual object may still remain. .PP When called as an object method, removes a domain registration that was made both globally and locally, unless a true value was passed as the second argument, in which case only the registration local to the object will be removed. This allows a different mapping made globally to take over. .PP If you want to mask a global registration on just one particular instance, then add \f(CW\*(C`undef\*(C'\fR as a mapping on your instance: .PP .Vb 1 \& $useragent\->map_response($domain, undef); .Ve .PP This method returns the \f(CW\*(C`Test::LWP::UserAgent\*(C'\fR object or class. .ie n .SS """last_http_request_sent""" .el .SS "\f(CWlast_http_request_sent\fP" .IX Subsection "last_http_request_sent" The last HTTP::Request object that this object (if called on an object) or module (if called as a class method) processed, whether or not it matched a mapping you set up earlier. .PP Note that this is also available via \f(CW\*(C`last_http_response_received\->request\*(C'\fR. .ie n .SS """last_http_response_received""" .el .SS "\f(CWlast_http_response_received\fP" .IX Subsection "last_http_response_received" The last HTTP::Response object that this module returned, as a result of a mapping you set up earlier with \f(CW\*(C`map_response\*(C'\fR. You shouldn't normally need to use this, as you know what you responded with \- you should instead be testing how your code reacted to receiving this response. .ie n .SS """last_useragent""" .el .SS "\f(CWlast_useragent\fP" .IX Subsection "last_useragent" The last Test::LWP::UserAgent object that was used to send a request. Obviously this only provides new information if called as a class method; you can use this if you don't have direct control over the useragent itself, to get the object that was used, to verify options such as the network timeout. .ie n .SS """network_fallback""" .el .SS "\f(CWnetwork_fallback\fP" .IX Subsection "network_fallback" Getter/setter method for the network_fallback preference that will be used on this object (if called as an instance method), or globally, if called as a class method. Note that the actual behaviour used on an object is the ORed value of the instance setting and the global setting. .ie n .SS """send_request($request)""" .el .SS "\f(CWsend_request($request)\fP" .IX Subsection "send_request($request)" This is the only method from LWP::UserAgent that has been overridden, which processes the HTTP::Request, sends to the network, then creates the HTTP::Response object from the reply received. Here, we loop through your local and global domain registrations, and local and global mappings (in this order) and returns the \fBfirst match found\fR; otherwise, a simple 404 response is returned (unless \f(CW\*(C`network_fallback\*(C'\fR was specified as a constructor option, in which case unmatched requests will be delivered to the network.) .PP All other methods from LWP::UserAgent are available unchanged. .SH "Usage with SOAP requests" .IX Header "Usage with SOAP requests" .SS "SOAP::Lite" .IX Subsection "SOAP::Lite" To use this module when communicating via SOAP::Lite with a \s-1SOAP\s0 server (either a real one, with live network requests, see above or with one simulated with mapped responses), simply do this: .PP .Vb 3 \& use SOAP::Lite; \& use SOAP::Transport::HTTP; \& $SOAP::Transport::HTTP::Client::USERAGENT_CLASS = \*(AqTest::LWP::UserAgent\*(Aq; .Ve .PP You must then make all your configuration changes and mappings globally. .PP See also \*(L"\s-1CHANGING THE DEFAULT USERAGENT CLASS\*(R"\s0 in SOAP::Transport. .SS "XML::Compile::SOAP" .IX Subsection "XML::Compile::SOAP" When using XML::Compile::SOAP with a compiled \s-1WSDL,\s0 you can change the useragent object via XML::Compile::Transport::SOAPHTTP: .PP .Vb 7 \& my $call = $wsdl\->compileClient( \& $interface_name, \& transport => XML::Compile::Transport::SOAPHTTP\->new( \& user_agent => $useragent, \& address => $wsdl\->endPoint, \& ), \& ); .Ve .PP See also \*(L"Adding \s-1HTTP\s0 headers\*(R" in XML::Compile::SOAP::FAQ. .SH "MOTIVATION" .IX Header "MOTIVATION" Most mock libraries on the \s-1CPAN\s0 use Test::MockObject, which is widely considered not good practice (among other things, \f(CW@ISA\fR is violated, it requires knowing far too much about the module's internals, and is very clumsy to work with). (This blog entry is one of many that chronicles its issues.) .PP This module is a direct descendant of LWP::UserAgent, exports nothing into your namespace, and all access is via method calls, so it is fully inheritable should you desire to add more features or override some bits of functionality. .PP (Aside from the constructor), it only overrides the one method in LWP::UserAgent that issues calls to the network, so real HTTP::Request and HTTP::Headers objects are used throughout. It provides a method (\f(CW\*(C`last_http_request_sent\*(C'\fR) to access the last HTTP::Request, for testing things like the \s-1URI\s0 and headers that your code sent to LWP::UserAgent. .SH "ACKNOWLEDGEMENTS" .IX Header "ACKNOWLEDGEMENTS" AirG Inc. , my former employer, and the first user of this distribution. .PP mst \- Matt S. Trout , for the better name of this distribution, and for the \s-1PSGI\s0 registration concept. .PP Also Yury Zavarin, whose Test::Mock::LWP::Dispatch inspired me to write this module, and from where I borrowed some aspects of the \s-1API.\s0 .SH "SEE ALSO" .IX Header "SEE ALSO" .IP "\(bu" 4 Perl advent article, 2012 .IP "\(bu" 4 Test::Mock::LWP::Dispatch .IP "\(bu" 4 Test::Mock::LWP::UserAgent .IP "\(bu" 4 \&\s-1URI\s0, HTTP::Request, HTTP::Response .IP "\(bu" 4 LWP::UserAgent .IP "\(bu" 4 \&\s-1PSGI\s0, HTTP::Message::PSGI, LWP::Protocol::PSGI, .IP "\(bu" 4 Plack::Test, Plack::Test::ExternalServer .SH "SUPPORT" .IX Header "SUPPORT" Bugs may be submitted through the \s-1RT\s0 bug tracker (or bug\-Test\-LWP\-UserAgent@rt.cpan.org ). .PP There is also a mailing list available for users of this distribution, at . .PP There is also an irc channel available for users of this distribution, at \&\f(CW\*(C`#perl\*(C'\fR on \f(CW\*(C`irc.perl.org\*(C'\fR . .PP I am also usually active on irc, as 'ether' at \f(CW\*(C`irc.perl.org\*(C'\fR. .SH "AUTHOR" .IX Header "AUTHOR" Karen Etheridge .SH "CONTRIBUTOR" .IX Header "CONTRIBUTOR" Tom Hukins .SH "COPYRIGHT AND LICENCE" .IX Header "COPYRIGHT AND LICENCE" This software is copyright (c) 2012 by Karen Etheridge. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.