| Title: | Stubbing and Setting Expectations on 'HTTP' Requests | 
| Description: | Stubbing and setting expectations on 'HTTP' requests. Includes tools for stubbing 'HTTP' requests, including expected request conditions and response conditions. Match on 'HTTP' method, query parameters, request body, headers and more. Can be used for unit tests or outside of a testing context. | 
| Version: | 2.2.0 | 
| License: | MIT + file LICENSE | 
| URL: | https://github.com/ropensci/webmockr, https://books.ropensci.org/http-testing/, https://docs.ropensci.org/webmockr/ | 
| BugReports: | https://github.com/ropensci/webmockr/issues | 
| Encoding: | UTF-8 | 
| Language: | en-US | 
| Depends: | R(≥ 4.1.0) | 
| Imports: | curl, jsonlite, magrittr (≥ 1.5), R6 (≥ 2.1.3), urltools (≥ 1.6.0), fauxpas, rlang, cli | 
| Suggests: | testthat (≥ 3.0.0), xml2, crul, httr, httr2, diffobj, withr | 
| RoxygenNote: | 7.3.2 | 
| Config/testthat/edition: | 3 | 
| Config/testthat/parallel: | true | 
| X-schema.org-applicationCategory: | Web | 
| X-schema.org-keywords: | http, https, API, web-services, curl, mock, mocking, fakeweb, http-mocking, testing, testing-tools, tdd | 
| X-schema.org-isPartOf: | https://ropensci.org | 
| NeedsCompilation: | no | 
| Packaged: | 2025-07-17 17:53:01 UTC; sckott | 
| Author: | Scott Chamberlain | 
| Maintainer: | Scott Chamberlain <myrmecocystus+r@gmail.com> | 
| Repository: | CRAN | 
| Date/Publication: | 2025-07-21 05:00:02 UTC | 
webmockr: Stubbing and Setting Expectations on 'HTTP' Requests
Description
Stubbing and setting expectations on 'HTTP' requests. Includes tools for stubbing 'HTTP' requests, including expected request conditions and response conditions. Match on 'HTTP' method, query parameters, request body, headers and more. Can be used for unit tests or outside of a testing context.
Features
- Stubbing HTTP requests at low http client lib level 
- Setting and verifying expectations on HTTP requests 
- Matching requests based on method, URI, headers and body 
- Supports multiple HTTP libraries, including crul, httr, and httr2 
- Supports async http request mocking with crul only 
Author(s)
Maintainer: Scott Chamberlain myrmecocystus+r@gmail.com (ORCID)
Other contributors:
- Aaron Wolen (ORCID) [contributor] 
- rOpenSci (019jywm96) [funder] 
See Also
Useful links:
- Report bugs at https://github.com/ropensci/webmockr/issues 
Examples
library(webmockr)
stub_request("get", "https://httpbin.org/get")
stub_request("post", "https://httpbin.org/post")
stub_registry()
Pipe operator
Description
Pipe operator
Usage
lhs %>% rhs
BodyPattern
Description
body matcher
Public fields
- pattern
- a list 
- partial
- bool, default: - FALSE
- partial_type
- a string, default: NULL 
Methods
Public methods
Method new()
Create a new BodyPattern object
Usage
BodyPattern$new(pattern)
Arguments
- pattern
- (list) a body object - from a request stub (i.e., the mock) 
Returns
A new BodyPattern object
Method matches()
Match a request body pattern against a pattern
Usage
BodyPattern$matches(body, content_type = "")
Arguments
- body
- (list) the body, i.e., from the HTTP request 
- content_type
- (character) content type 
Returns
a boolean
Method to_s()
Print pattern for easy human consumption
Usage
BodyPattern$to_s()
Returns
a string
Method clone()
The objects of this class are cloneable with this method.
Usage
BodyPattern$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
Adapters for Modifying HTTP Requests
Description
Adapter is the base parent class used to implement
webmockr support for different HTTP clients. It should not be used
directly. Instead, use one of the client-specific adapters that webmockr
currently provides:
-  CrulAdapterfor crul
-  HttrAdapterfor httr
-  Httr2Adapterfor httr2
Details
Note that the documented fields and methods are the same across all client-specific adapters.
Super class
webmockr::Adapter -> CrulAdapter
Public fields
- client
- HTTP client package name 
- name
- adapter name 
Methods
Public methods
Inherited methods
Method clone()
The objects of this class are cloneable with this method.
Usage
CrulAdapter$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
Super class
webmockr::Adapter -> HttrAdapter
Public fields
- client
- HTTP client package name 
- name
- adapter name 
Methods
Public methods
Inherited methods
Method clone()
The objects of this class are cloneable with this method.
Usage
HttrAdapter$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
Super class
webmockr::Adapter -> Httr2Adapter
Public fields
- client
- HTTP client package name 
- name
- adapter name 
Methods
Public methods
Inherited methods
Method clone()
The objects of this class are cloneable with this method.
Usage
Httr2Adapter$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
Public fields
- client
- HTTP client package name 
- name
- adapter name 
Methods
Public methods
Method new()
Create a new Adapter object
Usage
Adapter$new()
Method enable()
Enable the adapter
Usage
Adapter$enable(quiet = FALSE)
Arguments
- quiet
- (logical) suppress messages? default: - FALSE
Returns
TRUE, invisibly
Method disable()
Disable the adapter
Usage
Adapter$disable(quiet = FALSE)
Arguments
- quiet
- (logical) suppress messages? default: - FALSE
Returns
FALSE, invisibly
Method handle_request()
All logic for handling a request
Usage
Adapter$handle_request(req)
Arguments
- req
- a request 
Returns
various outcomes
Method remove_stubs()
Remove all stubs
Usage
Adapter$remove_stubs()
Returns
nothing returned; removes all request stubs
Method clone()
The objects of this class are cloneable with this method.
Usage
Adapter$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
HashCounter
Description
hash with counter, to store requests, and count each time it is used
Public fields
- hash
- (list) a list for internal use only, with elements - key,- sig, and- count
Methods
Public methods
Method put()
Register a request by it's key
Usage
HashCounter$put(req_sig)
Arguments
- req_sig
- an object of class - RequestSignature
Returns
nothing returned; registers request and iterates internal counter
Method get()
Get a request by key
Usage
HashCounter$get(req_sig)
Arguments
- req_sig
- an object of class - RequestSignature
Returns
(integer) the count of how many times the request has been made
Method clone()
The objects of this class are cloneable with this method.
Usage
HashCounter$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
See Also
Other request-registry: 
RequestRegistry,
request_registry()
HeadersPattern
Description
headers matcher
Details
webmockr normalises headers and treats all forms of same headers as equal:
i.e the following two sets of headers are equal:
list(Header1 = "value1", content_length = 123, X_CuStOm_hEAder = "foo")
and
list(header1 = "value1", "Content-Length" = 123, "x-cuSTOM-HeAder" = "foo")
Public fields
- pattern
- a list 
Methods
Public methods
Method new()
Create a new HeadersPattern object
Usage
HeadersPattern$new(pattern)
Arguments
- pattern
- (list) a pattern, as a named list, must be named, e.g,. - list(a = 5, b = 6)
Returns
A new HeadersPattern object
Method matches()
Match a list of headers against that stored
Usage
HeadersPattern$matches(headers)
Arguments
- headers
- (list) named list of headers, e.g,. - list(a = 5, b = 6)
Returns
a boolean
Method empty_headers()
Are headers empty? tests if null or length==0
Usage
HeadersPattern$empty_headers(headers)
Arguments
- headers
- named list of headers 
Returns
a boolean
Method to_s()
Print pattern for easy human consumption
Usage
HeadersPattern$to_s()
Returns
a string
Method clone()
The objects of this class are cloneable with this method.
Usage
HeadersPattern$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
HttpLibAdapaterRegistry
Description
http lib adapter registry
Public fields
- adapters
- list 
Methods
Public methods
Method print()
print method for the HttpLibAdapaterRegistry class
Usage
HttpLibAdapaterRegistry$print(x, ...)
Arguments
- x
- self 
- ...
- ignored 
Method register()
Register an http library adapter
Usage
HttpLibAdapaterRegistry$register(x)
Arguments
- x
- an http lib adapter, e.g., CrulAdapter 
Returns
nothing, registers the library adapter
Method clone()
The objects of this class are cloneable with this method.
Usage
HttpLibAdapaterRegistry$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
MethodPattern
Description
method matcher
Details
Matches regardless of case. e.g., POST will match to post
Public fields
- pattern
- (character) an http method 
Methods
Public methods
Method new()
Create a new MethodPattern object
Usage
MethodPattern$new(pattern)
Arguments
- pattern
- (character) a HTTP method, lowercase 
Returns
A new MethodPattern object
Method matches()
test if the pattern matches a given http method
Usage
MethodPattern$matches(method)
Arguments
- method
- (character) a HTTP method, lowercase 
Returns
a boolean
Method to_s()
Print pattern for easy human consumption
Usage
MethodPattern$to_s()
Returns
a string
Method clone()
The objects of this class are cloneable with this method.
Usage
MethodPattern$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
RequestPattern class
Description
Class handling all request matchers
Public fields
- method_pattern
- xxx 
- uri_pattern
- xxx 
- body_pattern
- xxx 
- headers_pattern
- xxx 
Methods
Public methods
Method new()
Create a new RequestPattern object
Usage
RequestPattern$new( method, uri = NULL, uri_regex = NULL, query = NULL, body = NULL, headers = NULL, basic_auth = NULL )
Arguments
- method
- the HTTP method (any, head, options, get, post, put, patch, trace, or delete). "any" matches any HTTP method. required. 
- uri
- (character) request URI. required or uri_regex 
- uri_regex
- (character) request URI as regex. required or uri 
- query
- (list) query parameters, optional 
- body
- (list) body request, optional 
- headers
- (list) headers, optional 
- basic_auth
- (list) vector of length 2 (username, password), optional 
Returns
A new RequestPattern object
Method matches()
does a request signature match the selected matchers?
Usage
RequestPattern$matches(request_signature)
Arguments
- request_signature
- a RequestSignature object 
Returns
a boolean
Method to_s()
Print pattern for easy human consumption
Usage
RequestPattern$to_s()
Returns
a string
Method clone()
The objects of this class are cloneable with this method.
Usage
RequestPattern$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
See Also
pattern classes for HTTP method MethodPattern, headers HeadersPattern, body BodyPattern, and URI/URL UriPattern
RequestRegistry
Description
keeps track of HTTP requests
Public fields
- request_signatures
- a HashCounter object 
Methods
Public methods
Method print()
print method for the RequestRegistry class
Usage
RequestRegistry$print(x, ...)
Arguments
- x
- self 
- ...
- ignored 
Method reset()
Reset the registry to no registered requests
Usage
RequestRegistry$reset()
Returns
nothing returned; resets registry to no requests
Method register_request()
Register a request
Usage
RequestRegistry$register_request(request)
Arguments
- request
- a character string of the request, serialized from a - RequestSignature$new(...)$to_s()
Returns
nothing returned; registers the request
Method times_executed()
How many times has a request been made
Usage
RequestRegistry$times_executed(request_pattern)
Arguments
- request_pattern
- an object of class - RequestPattern
Details
if no match is found for the request pattern, 0 is returned
Returns
integer, the number of times the request has been made
Method clone()
The objects of this class are cloneable with this method.
Usage
RequestRegistry$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
See Also
stub_registry() and StubRegistry
Other request-registry: 
HashCounter,
request_registry()
RequestSignature
Description
General purpose request signature builder
Public fields
- method
- (character) an http method 
- uri
- (character) a uri 
- body
- (various) request body 
- headers
- (list) named list of headers 
- proxies
- (list) proxies as a named list 
- auth
- (list) authentication details, as a named list 
- url
- internal use 
- disk
- (character) if writing to disk, the path 
- fields
- (various) request body details 
- output
- (various) request output details, disk, memory, etc 
Methods
Public methods
Method new()
Create a new RequestSignature object
Usage
RequestSignature$new(method, uri, options = list())
Arguments
- method
- the HTTP method (any, head, options, get, post, put, patch, trace, or delete). "any" matches any HTTP method. required. 
- uri
- (character) request URI. required. 
- options
- (list) options. optional. See Details. 
Returns
A new RequestSignature object
Method print()
print method for the RequestSignature class
Usage
RequestSignature$print()
Arguments
- x
- self 
- ...
- ignored 
Method to_s()
Request signature to a string
Usage
RequestSignature$to_s()
Returns
a character string representation of the request signature
Method clone()
The objects of this class are cloneable with this method.
Usage
RequestSignature$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
Examples
# make request signature
x <- RequestSignature$new(method = "get", uri = "https:/httpbin.org/get")
# method
x$method
# uri
x$uri
# request signature to string
x$to_s()
# headers
w <- RequestSignature$new(
  method = "get",
  uri = "https:/httpbin.org/get",
  options = list(headers = list(`User-Agent` = "foobar", stuff = "things"))
)
w
w$headers
w$to_s()
# headers and body
bb <- RequestSignature$new(
  method = "get",
  uri = "https:/httpbin.org/get",
  options = list(
    headers = list(`User-Agent` = "foobar", stuff = "things"),
    body = list(a = "tables")
  )
)
bb
bb$headers
bb$body
bb$to_s()
# with disk path
f <- tempfile()
bb <- RequestSignature$new(
  method = "get",
  uri = "https:/httpbin.org/get",
  options = list(disk = f)
)
bb
bb$disk
bb$to_s()
Response
Description
custom webmockr http response class
Public fields
- url
- (character) a url 
- body
- (various) list, character, etc 
- content
- (various) response content/body 
- request_headers
- (list) a named list 
- response_headers
- (list) a named list 
- options
- (character) list 
- status_code
- (integer) an http status code 
- exception
- (character) an exception message 
- should_timeout
- (logical) should the response timeout? 
Methods
Public methods
Method new()
Create a new Response object
Usage
Response$new(options = list())
Arguments
- options
- (list) a list of options 
Returns
A new Response object
Method print()
print method for the Response class
Usage
Response$print(x, ...)
Arguments
- x
- self 
- ...
- ignored 
Method set_url()
set the url for the response
Usage
Response$set_url(url)
Arguments
- url
- (character) a url 
Returns
nothing returned; sets url
Method get_url()
get the url for the response
Usage
Response$get_url()
Returns
(character) a url
Method set_request_headers()
set the request headers for the response
Usage
Response$set_request_headers(headers, capitalize = TRUE)
Arguments
- headers
- (list) named list 
- capitalize
- (logical) whether to capitalize first letters of each header; default: - TRUE
Returns
nothing returned; sets request headers on the response
Method get_request_headers()
get the request headers for the response
Usage
Response$get_request_headers()
Returns
(list) request headers, a named list
Method set_response_headers()
set the response headers for the response
Usage
Response$set_response_headers(headers, capitalize = TRUE)
Arguments
- headers
- (list) named list 
- capitalize
- (logical) whether to capitalize first letters of each header; default: - TRUE
Returns
nothing returned; sets response headers on the response
Method get_respone_headers()
get the response headers for the response
Usage
Response$get_respone_headers()
Returns
(list) response headers, a named list
Method set_body()
set the body of the response
Usage
Response$set_body(body, disk = FALSE)
Arguments
- body
- (various types) 
- disk
- (logical) whether its on disk; default: - FALSE
Returns
nothing returned; sets body on the response
Method get_body()
get the body of the response
Usage
Response$get_body()
Returns
various
Method set_status()
set the http status of the response
Usage
Response$set_status(status)
Arguments
- status
- (integer) the http status 
Returns
nothing returned; sets the http status of the response
Method get_status()
get the http status of the response
Usage
Response$get_status()
Returns
(integer) the http status
Method set_exception()
set an exception
Usage
Response$set_exception(exception)
Arguments
- exception
- (character) an exception string 
Returns
nothing returned; sets an exception
Method get_exception()
get the exception, if set
Usage
Response$get_exception()
Returns
(character) an exception
Method clone()
The objects of this class are cloneable with this method.
Usage
Response$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
Examples
(x <- Response$new())
x$set_url("https://httpbin.org/get")
x
x$set_request_headers(list("Content-Type" = "application/json"))
x
x$request_headers
x$set_response_headers(list("Host" = "httpbin.org"))
x
x$response_headers
x$set_status(404)
x
x$get_status()
x$set_body("hello world")
x
x$get_body()
# raw body
x$set_body(charToRaw("hello world"))
x
x$get_body()
x$set_exception("exception")
x
x$get_exception()
StubCounter
Description
hash with counter to store requests and count number of requests made against the stub
Public fields
- hash
- (list) a list for internal use only, with elements - key,- sig, and- count
Methods
Public methods
Method put()
Register a request by it's key
Usage
StubCounter$put(x)
Arguments
- x
- an object of class - RequestSignature
Returns
nothing returned; registers request & iterates internal counter
Method count()
Get the count of number of times any matching request has been made against this stub
Usage
StubCounter$count()
Method clone()
The objects of this class are cloneable with this method.
Usage
StubCounter$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
StubRegistry
Description
stub registry to keep track of StubbedRequest stubs
Public fields
- request_stubs
- (list) list of request stubs 
Methods
Public methods
Method print()
print method for the StubRegistry class
Usage
StubRegistry$print(x, ...)
Arguments
- x
- self 
- ...
- ignored 
Method register_stub()
Register a stub
Usage
StubRegistry$register_stub(stub)
Arguments
- stub
- an object of type StubbedRequest 
Returns
nothing returned; registers the stub
Method find_stubbed_request()
Find a stubbed request
Usage
StubRegistry$find_stubbed_request(req)
Arguments
- req
- an object of class RequestSignature 
Returns
an object of type StubbedRequest, if matched
Method request_stub_for()
Find a stubbed request
Usage
StubRegistry$request_stub_for(request_signature, count = TRUE)
Arguments
- request_signature
- an object of class RequestSignature 
- count
- (bool) iterate counter or not. default: - TRUE
Returns
logical, 1 or more
Method remove_request_stub()
Remove a stubbed request by matching request signature
Usage
StubRegistry$remove_request_stub(stub)
Arguments
- stub
- an object of type StubbedRequest 
Returns
nothing returned; removes the stub from the registry
Method remove_all_request_stubs()
Remove all request stubs
Usage
StubRegistry$remove_all_request_stubs()
Returns
nothing returned; removes all request stubs
Method is_registered()
Find a stubbed request from a request signature
Usage
StubRegistry$is_registered(x)
Arguments
- x
- an object of class RequestSignature 
Returns
nothing returned; registers the stub
Method is_stubbed()
Check if a stubbed request is in the stub registry
Usage
StubRegistry$is_stubbed(stub)
Arguments
- stub
- an object of class StubbedRequest 
Returns
single boolean, TRUE or FALSE
Method clone()
The objects of this class are cloneable with this method.
Usage
StubRegistry$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
See Also
Other stub-registry: 
remove_request_stub(),
stub_registry(),
stub_registry_clear()
StubbedRequest
Description
stubbed request class underlying stub_request()
Public fields
- method
- (xx) xx 
- uri
- (xx) xx 
- uri_regex
- (xx) xx 
- regex
- a logical 
- uri_parts
- (xx) xx 
- host
- (xx) xx 
- query
- (xx) xx 
- body
- (xx) xx 
- basic_auth
- (xx) xx 
- request_headers
- (xx) xx 
- response_headers
- (xx) xx 
- responses_sequences
- (xx) xx 
- status_code
- (xx) xx 
- counter
- a StubCounter object 
Methods
Public methods
Method new()
Create a new StubbedRequest object
Usage
StubbedRequest$new(method, uri = NULL, uri_regex = NULL)
Arguments
- method
- the HTTP method (any, head, get, post, put, patch, or delete). "any" matches any HTTP method. required. 
- uri
- (character) request URI. either this or - uri_regexrequired. webmockr can match uri's without the "http" scheme, but does not match if the scheme is "https". required, unless- uri_regexgiven. See UriPattern for more.
- uri_regex
- (character) request URI as regex. either this or - urirequired
Returns
A new StubbedRequest object
Method print()
print method for the StubbedRequest class
Usage
StubbedRequest$print(x, ...)
Arguments
- x
- self 
- ...
- ignored 
Method with()
Set expectations for what's given in HTTP request
Usage
StubbedRequest$with( query = NULL, body = NULL, headers = NULL, basic_auth = NULL )
Arguments
- query
- (list) request query params, as a named list. optional 
- body
- (list) request body, as a named list. optional 
- headers
- (list) request headers as a named list. optional. 
- basic_auth
- (character) basic authentication. optional. 
Returns
nothing returned; sets only
Method to_return()
Set expectations for what's returned in HTTP response
Usage
StubbedRequest$to_return(status, body, headers)
Arguments
- status
- (numeric) an HTTP status code 
- body
- (list) response body, one of: - character,- json,- list,- raw,- numeric,- NULL,- FALSE, or a file connection (other connection types not supported)
- headers
- (list) named list, response headers. optional. 
Returns
nothing returned; sets whats to be returned
Method to_timeout()
Response should time out
Usage
StubbedRequest$to_timeout()
Returns
nothing returned
Method to_raise()
Response should raise an exception x
Usage
StubbedRequest$to_raise(x)
Arguments
- x
- (character) an exception message 
Returns
nothing returned
Method to_s()
Response as a character string
Usage
StubbedRequest$to_s()
Returns
(character) the response as a string
Method reset()
Reset the counter for the stub
Usage
StubbedRequest$reset()
Returns
nothing returned; resets stub counter to no requests
Method clone()
The objects of this class are cloneable with this method.
Usage
StubbedRequest$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
See Also
UriPattern
Description
uri matcher
Public fields
- pattern
- (character) pattern holder 
- regex
- a logical 
- query_params
- a list, or - NULLif empty
- partial
- bool, default: - FALSE
- partial_type
- a string, default: NULL 
Methods
Public methods
Method new()
Create a new UriPattern object
Usage
UriPattern$new(pattern = NULL, regex_pattern = NULL)
Arguments
- pattern
- (character) a uri, as a character string. if scheme is missing, it is added (we assume http) 
- regex_pattern
- (character) a uri as a regex character string, see base::regex. if scheme is missing, it is added (we assume http) 
Returns
A new UriPattern object
Method matches()
Match a uri against a pattern
Usage
UriPattern$matches(uri)
Arguments
- uri
- (character) a uri 
Returns
a boolean
Method pattern_matches()
Match a URI
Usage
UriPattern$pattern_matches(uri)
Arguments
- uri
- (character) a uri 
Returns
a boolean
Method query_params_matches()
Match query parameters of a URI
Usage
UriPattern$query_params_matches(uri)
Arguments
- uri
- (character) a uri 
Returns
a boolean
Method extract_query()
Extract query parameters as a named list
Usage
UriPattern$extract_query(uri)
Arguments
- uri
- (character) a uri 
Returns
named list, or NULL if no query parameters
Method add_query_params()
Add query parameters to the URI
Usage
UriPattern$add_query_params(query_params)
Arguments
- query_params
- (list|character) list or character 
Returns
nothing returned, updates uri pattern
Method to_s()
Print pattern for easy human consumption
Usage
UriPattern$to_s()
Returns
a string
Method clone()
The objects of this class are cloneable with this method.
Usage
UriPattern$clone(deep = FALSE)
Arguments
- deep
- Whether to make a deep clone. 
Build a crul request
Description
Build a crul request
Usage
build_crul_request(x)
Arguments
| x | an unexecuted crul request object | 
Value
a crul request
Build a crul response
Description
Build a crul response
Usage
build_crul_response(req, resp)
Arguments
| req | a request | 
| resp | a response | 
Value
a crul response
Build an httr2 request
Description
Build an httr2 request
Usage
build_httr2_request(x)
Arguments
| x | an unexecuted httr2 request object | 
Value
a httr2_request
Build a httr2 response (httr2_response)
Description
Build a httr2 response (httr2_response)
Usage
build_httr2_response(req, resp)
Arguments
| req | a request | 
| resp | a response | 
Value
an httr2 response (httr2_response)
Build a httr request
Description
Build a httr request
Usage
build_httr_request(x)
Arguments
| x | an unexecuted httr request object | 
Value
a httr request
Build a httr response
Description
Build a httr response
Usage
build_httr_response(req, resp)
Arguments
| req | a request | 
| resp | a response | 
Value
a httr response
Enable or disable webmockr
Description
Enable or disable webmockr
Usage
enable(adapter = NULL, options = list(), quiet = FALSE)
enabled(adapter = "crul")
disable(adapter = NULL, options = list(), quiet = FALSE)
Arguments
| adapter | (character) the adapter name, 'crul', 'httr', or 'httr2'. one or the other. if none given, we attempt to enable both adapters | 
| options | list of options - ignored for now. | 
| quiet | (logical) suppress messages? default:  | 
Details
-  enable()enables webmockr for all adapters
-  disable()disables webmockr for all adapters
-  enabled()answers whether webmockr is enabled for a given adapter
Value
enable() and disable() invisibly returns booleans for
each adapter, as a result of running enable or disable, respectively,
on each HttpLibAdapaterRegistry object. enabled returns a
single boolean
Handle stub removal
Description
Handle stub removal
Usage
handle_stub_removal(.data, code)
Arguments
| .data | an object of class  | 
| code | a code block. required | 
Value
if no error, the result of running code; if an error occurs
withCallingHandlers() throws a warning and then the stub is removed
Turn on httr2 mocking
Description
Sets a callback that routes httr2 requests through webmockr
Usage
httr2_mock(on = TRUE)
Arguments
| on | (logical)  | 
Value
Silently returns TRUE when enabled and FALSE when disabled.
Turn on httr mocking
Description
Sets a callback that routes httr requests through webmockr
Usage
httr_mock(on = TRUE)
Arguments
| on | (logical) set to  | 
Value
Silently returns TRUE when enabled and FALSE when disabled.
Partially match request query parameters or request bodies
Description
For use inside wi_th()
Usage
including(x)
excluding(x)
Arguments
| x | (list) a list; may support other classes in the future | 
Value
same as x, but with two attributes added:
- partial_match: always - TRUE
- partial_type: the type of match, one of - includeor- exclude
Headers
Matching on headers already handles partial matching. That is,
wi_th(headers = list(Fruit = "pear")) matches any request
that has any request header that matches - the request can have
other request headers, but those don't matter as long as there is
a match. These helpers (including/excluding) are needed
for query parameters and bodies because by default matching must be
exact for those.
Examples
including(list(foo = "bar"))
excluding(list(foo = "bar"))
# get just keys by setting values as NULL
including(list(foo = NULL, bar = NULL))
# in a stub
req <- stub_request("get", "https://httpbin.org/get")
req
## query
wi_th(req, query = list(foo = "bar"))
wi_th(req, query = including(list(foo = "bar")))
wi_th(req, query = excluding(list(foo = "bar")))
## body
wi_th(req, body = list(foo = "bar"))
wi_th(req, body = including(list(foo = "bar")))
wi_th(req, body = excluding(list(foo = "bar")))
# cleanup
stub_registry_clear()
Get the last HTTP request made
Description
Get the last HTTP request made
Usage
last_request()
Value
NULL if no requests registered; otherwise the last
registered request made as a RequestSignature class
Examples
# no requests
request_registry_clear()
last_request()
# a request is found
enable()
stub_request("head", "https://nytimes.com")
library(crul)
crul::ok("https://nytimes.com")
last_request()
# cleanup
request_registry_clear()
stub_registry_clear()
Get the last stub created
Description
Get the last stub created
Usage
last_stub()
Value
NULL if no stubs found; otherwise the last stub created
as a StubbedRequest class
Examples
# no requests
stub_registry_clear()
last_stub()
# a stub is found
stub_request("head", "https://nytimes.com")
last_stub()
stub_request("post", "https://nytimes.com/stories")
last_stub()
# cleanup
stub_registry_clear()
Mock file
Description
Mock file
Usage
mock_file(path, payload)
Arguments
| path | (character) a file path. required | 
| payload | (character) string to be written to the file given
at  | 
Value
a list with S3 class mock_file
Examples
mock_file(path = tempfile(), payload = "{\"foo\": \"bar\"}")
Mocking writing to disk
Description
Mocking writing to disk
Examples
# enable mocking
enable()
# Write to a file before mocked request -------------
# crul
library(crul)
## make a temp file
f <- tempfile(fileext = ".json")
## write something to the file
cat("{\"hello\":\"world\"}\n", file = f)
readLines(f)
## make the stub
stub_request("get", "https://httpbin.org/get") %>%
  to_return(body = file(f))
## make a request
(out <- HttpClient$new("https://httpbin.org/get")$get(disk = f))
out$content
readLines(out$content)
stub_registry_clear()
# httr
library(httr)
## make a temp file
f <- tempfile(fileext = ".json")
## write something to the file
cat("{\"hello\":\"world\"}\n", file = f)
readLines(f)
## make the stub
stub_request("get", "https://httpbin.org/get") %>%
  to_return(
    body = file(f),
    headers = list("content-type" = "application/json")
  )
## make a request
## with httr, you must set overwrite=TRUE or you'll get an errror
out <- GET("https://httpbin.org/get", write_disk(f, overwrite = TRUE))
out
out$content
content(out, "text", encoding = "UTF-8")
stub_registry_clear()
# httr2
library(httr2)
## make a temp file
f <- tempfile(fileext = ".json")
## write something to the file
cat("{\"hello\":\"world\"}\n", file = f)
readLines(f)
## make the stub
stub_request("get", "https://httpbin.org/get") %>%
  to_return(
    body = file(f),
    headers = list("content-type" = "application/json")
  )
## make a request
req <- request("https://httpbin.org/get")
out <- req_perform(req, path = f)
out
out$body
out$headers
readLines(out$body)
stub_registry_clear()
# Use mock_file to have webmockr handle file and contents -------------
# crul
library(crul)
f <- tempfile(fileext = ".json")
## make the stub
stub_request("get", "https://httpbin.org/get") %>%
  to_return(body = mock_file(f, "{\"hello\":\"mars\"}\n"))
## make a request
(out <- crul::HttpClient$new("https://httpbin.org/get")$get(disk = f))
out$content
readLines(out$content)
stub_registry_clear()
# httr
library(httr)
## make a temp file
f <- tempfile(fileext = ".json")
## make the stub
stub_request("get", "https://httpbin.org/get") %>%
  to_return(
    body = mock_file(path = f, payload = "{\"foo\": \"bar\"}"),
    headers = list("content-type" = "application/json")
  )
## make a request
out <- GET("https://httpbin.org/get", write_disk(f))
out
## view stubbed file content
out$content
readLines(out$content)
content(out, "text", encoding = "UTF-8")
stub_registry_clear()
# httr2
library(httr2)
## make a temp file
f <- tempfile(fileext = ".json")
## make the stub
stub_request("get", "https://httpbin.org/get") %>%
  to_return(
    body = mock_file(path = f, payload = "{\"foo\": \"bar\"}"),
    headers = list("content-type" = "application/json")
  )
## make a request
req <- request("https://httpbin.org/get")
out <- req_perform(req, path = f)
out
## view stubbed file content
out$body
readLines(out$body)
stub_registry_clear()
# disable mocking
disable()
Extract the body from an HTTP request
Description
Returns an appropriate representation of the data contained within a request body based on its encoding.
Usage
pluck_body(x)
Arguments
| x | an unexecuted crul, httr or httr2 request object | 
Value
one of the following:
-  NULLif the request is not associated with a body
-  NULLif an upload is used not in a list
- list containing the multipart-encoded body 
- character vector with the JSON- or raw-encoded body, or upload form file 
Remove a request stub
Description
Remove a request stub
Usage
remove_request_stub(stub)
Arguments
| stub | a request stub, of class  | 
Value
logical, TRUE if removed, FALSE if not removed
See Also
Other stub-registry: 
StubRegistry,
stub_registry(),
stub_registry_clear()
Examples
(x <- stub_request("get", "https://httpbin.org/get"))
stub_registry()
remove_request_stub(x)
stub_registry()
List or clear requests in the request registry
Description
List or clear requests in the request registry
Usage
request_registry()
request_registry_clear()
Details
request_registry() lists the requests that have been made
that webmockr knows about; request_registry_clear() resets the
request registry (removes all recorded requests)
Value
an object of class RequestRegistry, print method gives the
requests in the registry and the number of times each one has been
performed
See Also
Other request-registry: 
HashCounter,
RequestRegistry
Examples
webmockr::enable()
stub_request("get", "https://httpbin.org/get") %>%
  to_return(body = "success!", status = 200)
# nothing in the request registry
request_registry()
# make the request
z <- crul::HttpClient$new(url = "https://httpbin.org")$get("get")
# check the request registry - the request was made 1 time
request_registry()
# do the request again
z <- crul::HttpClient$new(url = "https://httpbin.org")$get("get")
# check the request registry - now it's been made 2 times, yay!
request_registry()
# clear the request registry
request_registry_clear()
webmockr::disable()
Get a diff of a stub request body and a request body from an http request
Description
Requires the Suggested package diffobj
Usage
stub_body_diff(stub = last_stub(), request = last_request())
Arguments
| stub | object of class  | 
| request | object of class  | 
Details
Returns error message if either stub or request are NULL.
Even though you may not intentionally pass in a NULL, the return values
of last_stub() and last_request() when there's nothing found is NULL.
Under the hood the Suggested package diffobj is used to do the comparison.
Value
object of class Diff from the diffobj package
See Also
webmockr_configure() to toggle webmockr showing request body
diffs when there's not a match. stub_body_diff() is offered as a manual
way to compare requests and stubs - whereas turning on with
webmockr_configure() will do the diff for you.
Examples
# stops with error if no stub and request
request_registry_clear()
stub_registry_clear()
stub_body_diff()
# Gives diff when there's a stub and request found - however, no request body
stub_request("get", "https://hb.opencpu.org/get")
enable()
library(crul)
HttpClient$new("https://hb.opencpu.org")$get(path = "get")
stub_body_diff()
# Gives diff when there's a stub and request found - with request body
stub_request("post", "https://hb.opencpu.org/post") %>%
  wi_th(body = list(apple = "green"))
enable()
library(crul)
HttpClient$new("https://hb.opencpu.org")$post(
  path = "post", body = list(apple = "red")
)
stub_body_diff()
# Gives diff when there's a stub and request found - with request body
stub_request("post", "https://hb.opencpu.org/post") %>%
  wi_th(body = "the quick brown fox")
HttpClient$new("https://hb.opencpu.org")$post(
  path = "post", body = "the quick black fox"
)
stub_body_diff()
List stubs in the stub registry
Description
List stubs in the stub registry
Usage
stub_registry()
Value
an object of class StubRegistry, print method gives the
stubs in the registry
See Also
Other stub-registry: 
StubRegistry,
remove_request_stub(),
stub_registry_clear()
Examples
# make a stub
stub_request("get", "https://httpbin.org/get") %>%
  to_return(body = "success!", status = 200)
# check the stub registry, there should be one in there
stub_registry()
# make another stub
stub_request("get", "https://httpbin.org/get") %>%
  to_return(body = "woopsy", status = 404)
# check the stub registry, now there are two there
stub_registry()
# to clear the stub registry
stub_registry_clear()
stub_registry_clear
Description
Clear all stubs in the stub registry
Usage
stub_registry_clear()
Value
an empty list invisibly
See Also
Other stub-registry: 
StubRegistry,
remove_request_stub(),
stub_registry()
Examples
(x <- stub_request("get", "https://httpbin.org/get"))
stub_registry()
stub_registry_clear()
stub_registry()
Stub an http request
Description
Stub an http request
Usage
stub_request(method = "get", uri = NULL, uri_regex = NULL)
Arguments
| method | (character) HTTP method, one of "get", "post", "put", "patch", "head", "delete", "options" - or the special "any" (for any method) | 
| uri | (character) The request uri. Can be a full or partial uri.
webmockr can match uri's without the "http" scheme, but does
not match if the scheme is "https". required, unless  | 
| uri_regex | (character) A URI represented as regex. required, if  | 
Details
Internally, this calls StubbedRequest which handles the logic
See stub_registry() for listing stubs, stub_registry_clear()
for removing all stubs and remove_request_stub() for removing specific
stubs
If multiple stubs match the same request, we use the first stub. So if you want to use a stub that was created after an earlier one that matches, remove the earlier one(s).
Note on wi_th(): If you pass query, values are coerced to character
class in the recorded stub. You can pass numeric, integer, etc., but
all will be coerced to character.
See wi_th() for details on request body/query/headers and
to_return() for details on how response status/body/headers
are handled
Value
an object of class StubbedRequest, with print method describing
the stub.
uri vs. uri_regex
When you use uri, we compare the URIs without query params AND
also the query params themselves without the URIs.
When you use uri_regex we don't compare URIs and query params;
we just use your regex string defined in uri_regex as the pattern
for a call to grepl
Mocking writing to disk
Error handling
To construct stubs, one uses stub_request() first - which registers
the stub in the stub registry. Any additional calls to modify the stub
with for example wi_th() or to_return() can error. In those error
cases we ideally want to remove (unregister) the stub because you
certainly don't want a registered stub that is not exactly what you
intended.
When you encounter an error creating a stub you should see a warning message that the stub has been removed, for example:
stub_request("get", "https://httpbin.org/get") %>%
  wi_th(query = mtcars)
#> Error in `wi_th()`:
#> ! z$query must be of class list or partial
#> Run `rlang::last_trace()` to see where the error occurred.
#> Warning message:
#> Encountered an error constructing stub
#> • Removed stub
#> • To see a list of stubs run stub_registry()
Note
Trailing slashes are dropped from stub URIs before matching
See Also
wi_th(), to_return(), to_timeout(), to_raise(),
mock_file()
Examples
# basic stubbing
stub_request("get", "https://httpbin.org/get")
stub_request("post", "https://httpbin.org/post")
# any method, use "any"
stub_request("any", "https://httpbin.org/get")
# list stubs
stub_registry()
# clear all stubs
stub_registry()
stub_registry_clear()
Set raise error condition
Description
Set raise error condition
Usage
to_raise(.data, ...)
Arguments
| .data | input. Anything that can be coerced to a  | 
| ... | One or more HTTP exceptions from the fauxpas package. Run
 | 
Details
The behavior in the future will be:
When multiple exceptions are passed, the first is used on the first mock, the second on the second mock, and so on. Subsequent mocks use the last exception
But for now, only the first exception is used until we get that fixed
Value
an object of class StubbedRequest, with print method describing
the stub
Raise vs. Return
to_raise() always raises a stop condition, while to_return(status=xyz)
only sets the status code on the returned HTTP response object. So if you
want to raise a stop condition then to_raise() is what you want. But if
you don't want to raise a stop condition use to_return(). Use cases for
each vary. For example, in a unit test you may have a test expecting a 503
error; in this case to_raise() makes sense. In another case, if a unit
test expects to test some aspect of an HTTP response object that httr,
httr2, or crul typically returns, then you'll want to_return().
Note
see examples in stub_request()
Expectation for what's returned from a stubbed request
Description
Set response status code, response body, and/or response headers
Usage
to_return(.data, ..., .list = list(), times = 1)
Arguments
| .data | input. Anything that can be coerced to a  | 
| ... | Comma separated list of named variables. accepts the following:
 | 
| .list | named list, has to be one of 'status', 'body',
and/or 'headers'. An alternative to passing in via  | 
| times | (integer) number of times the given response should be returned; default: 1. value must be greater than or equal to 1. Very large values probably don't make sense, but there's no maximum value. See Details. | 
Details
Values for status, body, and headers:
- status: (numeric/integer) three digit status code 
- body: various: - character,- json,- list,- raw,- numeric,- NULL,- FALSE, a file connection (other connetion types not supported), or a- mock_filefunction call (see- mock_file())
- headers: (list) a named list, must be named 
response headers are returned with all lowercase names and the values
are all of type character. if numeric/integer values are given
(e.g., to_return(headers = list(a = 10))), we'll coerce any
numeric/integer values to character.
Value
an object of class StubbedRequest, with print method describing
the stub
multiple to_return()
You can add more than one to_return() to a webmockr stub (including
to_raise(), to_timeout()). Each one is a HTTP response returned.
That is, you'll match to an HTTP request based on stub_request() and
wi_th(); the first time the request is made, the first response
is returned; the second time the request is made, the second response
is returned; and so on.
Be aware that webmockr has to track number of requests
(see request_registry()), and so if you use multiple to_return()
or the times parameter, you must clear the request registry
in order to go back to mocking responses from the start again.
webmockr_reset() clears the stub registry and  the request registry,
after which you can use multiple responses again (after creating
your stub(s) again of course)
Raise vs. Return
to_raise() always raises a stop condition, while to_return(status=xyz)
only sets the status code on the returned HTTP response object. So if you
want to raise a stop condition then to_raise() is what you want. But if
you don't want to raise a stop condition use to_return(). Use cases for
each vary. For example, in a unit test you may have a test expecting a 503
error; in this case to_raise() makes sense. In another case, if a unit
test expects to test some aspect of an HTTP response object that httr,
httr2, or crul typically returns, then you'll want to_return().
Note
see more examples in stub_request()
Examples
# first, make a stub object
foo <- function() {
  stub_request("post", "https://httpbin.org/post")
}
# add status, body and/or headers
foo() %>% to_return(status = 200)
foo() %>% to_return(body = "stuff")
foo() %>% to_return(body = list(a = list(b = "world")))
foo() %>% to_return(headers = list(a = 5))
foo() %>%
  to_return(status = 200, body = "stuff", headers = list(a = 5))
# .list - pass in a named list instead
foo() %>% to_return(.list = list(body = list(foo = "bar")))
# multiple responses using chained `to_return()`
foo() %>%
  to_return(body = "stuff") %>%
  to_return(body = "things")
# many of the same response using the times parameter
foo() %>% to_return(body = "stuff", times = 3)
This function is defunct.
Description
This function is defunct.
Usage
to_return_(...)
Set timeout as an expected return on a match
Description
Set timeout as an expected return on a match
Usage
to_timeout(.data)
Arguments
| .data | input. Anything that can be coerced to a  | 
Value
an object of class StubbedRequest, with print method describing
the stub
Note
see examples in stub_request()
Defunct functions in webmockr
Description
-  webmockr_enable(): Function removed, seeenable()
-  webmockr_disable(): Function removed, seedisable()
-  to_return_: Only to_return()is available now
webmockr configuration
Description
webmockr configuration
Usage
webmockr_configure(
  allow_net_connect = FALSE,
  allow_localhost = FALSE,
  allow = NULL,
  show_stubbing_instructions = TRUE,
  show_body_diff = FALSE
)
webmockr_configure_reset()
webmockr_configuration()
webmockr_allow_net_connect()
webmockr_disable_net_connect(allow = NULL)
webmockr_net_connect_allowed(uri = NULL)
Arguments
| allow_net_connect | (logical) Default:  | 
| allow_localhost | (logical) Default:  | 
| allow | (character) one or more URI/URL to allow (and by extension all others are not allowed) | 
| show_stubbing_instructions | (logical) Default:  | 
| show_body_diff | (logical) Default:  | 
| uri | (character) a URI/URL as a character string - to determine whether or not it is allowed | 
webmockr_allow_net_connect
If there are stubs found for a request, even if net connections are
allowed (by running webmockr_allow_net_connect()) the stubbed
response will be returned. If no stub is found, and net connections
are allowed, then a real HTTP request can be made.
Examples
webmockr_configure()
webmockr_configure(
  allow_localhost = TRUE
)
webmockr_configuration()
webmockr_configure_reset()
webmockr_allow_net_connect()
webmockr_net_connect_allowed()
# disable net connect for any URIs
webmockr_disable_net_connect()
### gives NULL with no URI passed
webmockr_net_connect_allowed()
# disable net connect EXCEPT FOR given URIs
webmockr_disable_net_connect(allow = "google.com")
### is a specific URI allowed?
webmockr_net_connect_allowed("google.com")
# show body diff
webmockr_configure(show_body_diff = TRUE)
# cleanup
webmockr_configure_reset()
execute a curl request
Description
execute a curl request
Usage
webmockr_crul_fetch(x)
Arguments
| x | an object | 
Value
a curl response
This function is defunct.
Description
This function is defunct.
Usage
webmockr_disable(...)
This function is defunct.
Description
This function is defunct.
Usage
webmockr_enable(...)
webmockr_reset
Description
Clear all stubs and the request counter
Usage
webmockr_reset()
Details
this function runs stub_registry_clear() and
request_registry_clear() - so you can run those two yourself
to achieve the same thing
Value
nothing
See Also
stub_registry_clear() request_registry_clear()
Examples
# webmockr_reset()
Set additional parts of a stubbed request
Description
Set query params, request body, request headers and/or basic_auth
Usage
wi_th(.data, ..., .list = list())
Arguments
| .data | input. Anything that can be coerced to a  | 
| ... | Comma separated list of named variables. accepts the following:
 | 
| .list | named list, has to be one of  | 
Details
with is a function in the base package, so we went with
wi_th
Values for query, body, headers, and basic_auth:
- query: (list) a named list. values are coerced to character class in the recorded stub. You can pass numeric, integer, etc., but all will be coerced to character. 
- body: various, including character string, list, raw, numeric, upload ( - crul::upload(),- httr::upload_file(),- curl::form_file(), or- curl::form_data()they both create the same object in the end). for the special case of an empty request body use- NAinstead of- NULLbecause with- NULLwe can't determine if the user did not supply a body or they supplied- NULLto indicate an empty body.
- headers: (list) a named list 
- basic_auth: (character) a length two vector, username and password. We don't do any checking of the username/password except to detect edge cases where for example, the username/password were probably not set by the user on purpose (e.g., a URL is picked up by an environment variable). Only basic authentication supported https://en.wikipedia.org/wiki/Basic_access_authentication. 
Note that there is no regex matching on query, body, or headers. They are tested for matches in the following ways:
- query: compare stubs and requests with - identical(). this compares named lists, so both list names and values are compared
- body: varies depending on the body format (list vs. character, etc.) 
- headers: compare stub and request values with - ==. list names are compared with- %in%.- basic_authis included in headers (with the name Authorization)
Value
an object of class StubbedRequest, with print method describing
the stub
Note
see more examples in stub_request()
See Also
Examples
# first, make a stub object
req <- stub_request("post", "https://httpbin.org/post")
# add body
# list
wi_th(req, body = list(foo = "bar"))
# string
wi_th(req, body = '{"foo": "bar"}')
# raw
wi_th(req, body = charToRaw('{"foo": "bar"}'))
# numeric
wi_th(req, body = 5)
# an upload
wi_th(req, body = crul::upload(system.file("CITATION")))
# wi_th(req, body = httr::upload_file(system.file("CITATION")))
# add query - has to be a named list
wi_th(req, query = list(foo = "bar"))
# add headers - has to be a named list
wi_th(req, headers = list(foo = "bar"))
wi_th(req, headers = list(`User-Agent` = "webmockr/v1", hello = "world"))
# .list - pass in a named list instead
wi_th(req, .list = list(body = list(foo = "bar")))
# basic authentication
wi_th(req, basic_auth = c("user", "pass"))
wi_th(req, basic_auth = c("user", "pass"), headers = list(foo = "bar"))
# partial matching, query params
## including
wi_th(req, query = including(list(foo = "bar")))
## excluding
wi_th(req, query = excluding(list(foo = "bar")))
# partial matching, body
## including
wi_th(req, body = including(list(foo = "bar")))
## excluding
wi_th(req, body = excluding(list(foo = "bar")))
# basic auth
## including
wi_th(req, body = including(list(foo = "bar")))
## excluding
wi_th(req, body = excluding(list(foo = "bar")))
This function is defunct.
Description
This function is defunct.
Usage
wi_th_(...)