webfakes

Your own web server for happy HTTP testing

R build status

Lightweight fake web apps for testing. Built using the civetweb embedded web server.

Features

Optional dependencies

Installation

Once on CRAN, install the package as usual:

install.packages("webfakes")

Usage

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.

app <- webfakes::new_app()
app$get("/hello/:user", function(req, res) {
  res$send(paste0("Hello ", req$params$user, "!"))
})
web <- webfakes::local_app_process(app)

test_that("can use hello API", {
  url <- web$url("/hello/Gabor")
  expect_equal(get_hello(url), "Hello Gabor!")
})

When testing HTTP clients you can often use the built in httpbin_app():

httpbin <- webfakes::local_app_process(webfakes::httpbin_app())
test_that("HTTP errors are caught", {
  url <- httpbin$url("/status/404")
  resp <- httr::GET(url)
  expect_error(httr::stop_for_status(resp), class = "http_404")
})
#> Test passed 😸

Documentation

See https://webfakes.r-lib.org

Other solutions for HTTP testing in R:

R web application frameworks

webfakes focuses on testing, these packages are for writing real web apps:

License

MIT © RStudio