Your own web server for happy HTTP testing
Lightweight fake web apps for testing. Built using the civetweb embedded web server.
mw_json()
middleware, the response$send_json()
method and the
httpbin_app()
app.tmpl_glue()
template
engine.new_app_process()
and
local_app_process
to work.Install the release version from CRAN:
install.packages("webfakes")
Start a web app at the beginning of your tests or test file, and stop
it after. Here is an example with the testthat package. Suppose you want
to test that your get_hello()
function can query an
API:
local_app_process()
helps you clean up the web server
process after the test block, or test file. It is similar to the
withr::local_*
functions.
<- webfakes::new_app()
app $get("/hello/:user", function(req, res) {
app$send(paste0("Hello ", req$params$user, "!"))
res
})<- webfakes::local_app_process(app)
web
test_that("can use hello API", {
<- web$url("/hello/Gabor")
url expect_equal(get_hello(url), "Hello Gabor!")
})
When testing HTTP clients you can often use the built in
httpbin_app()
:
<- webfakes::local_app_process(webfakes::httpbin_app()) httpbin
test_that("HTTP errors are caught", {
<- httpbin$url("/status/404")
url <- httr::GET(url)
resp expect_error(httr::stop_for_status(resp), class = "http_404")
})
#> Test passed 🎉
See https://webfakes.r-lib.org
webfakes focuses on testing, these packages are for writing real web apps:
MIT © RStudio