tests/testthat/test-mock-http-helper.R

# The request-reading helpers in helper-mock-http.R carry logic of their own.
# Every header assertion in this suite reads a request through them, so a
# helper that silently skips would let those assertions pass by not running.

test_that("httpuv_absence_action() runs when httpuv is installed", {
  expect_identical(httpuv_absence_action(installed = TRUE, ci = ""), "run")
  expect_identical(httpuv_absence_action(installed = TRUE, ci = "true"), "run")
})

test_that("httpuv_absence_action() fails when httpuv is missing under CI", {
  expect_identical(httpuv_absence_action(installed = FALSE, ci = "true"), "fail")
})

test_that("httpuv_absence_action() skips when httpuv is missing off CI", {
  expect_identical(httpuv_absence_action(installed = FALSE, ci = ""), "skip")
})

test_that("require_httpuv() raises on the fail branch", {
  expect_error(require_httpuv("fail"), "CI is set")
})

test_that("require_httpuv() returns on the run branch", {
  expect_true(require_httpuv("run"))
})

test_that("request_target() reports the Authorization header unredacted on opt-in", {
  req <- lms_client("http://localhost:1234", token = "helper-token")

  target <- request_target(req, redact_headers = FALSE)

  expect_identical(target$headers$authorization, "Bearer helper-token")
})

test_that("request_target() redacts the Authorization header by default", {
  req <- lms_client("http://localhost:1234", token = "helper-token")

  value <- request_target(req)$headers$authorization

  expect_s3_class(value, "httr2_redacted_sentinel")
  expect_false(any(grepl("helper-token", format(value), fixed = TRUE)))
})

test_that("request_target() reports no Authorization header when none is set", {
  withr::local_envvar(RLMSTUDIO_API_TOKEN = "")
  withr::local_options(rlmstudio.token = NULL)

  target <- request_target(
    lms_client("http://localhost:1234"),
    redact_headers = FALSE
  )

  expect_null(target$headers$authorization)
})

test_that("request_target() parses a JSON body", {
  req <- httr2::request("http://localhost:1234") |>
    httr2::req_body_raw('{"model": "m", "n": 2}', type = "application/json")

  expect_identical(request_target(req)$body, list(model = "m", n = 2L))
})

test_that("request_target() returns a body that is not JSON as its text", {
  # A text that names a URL is the case jsonlite::fromJSON() would fetch.
  for (text in c("not json {", "http://localhost:1/never")) {
    req <- httr2::request("http://localhost:1234") |>
      httr2::req_body_raw(text, type = "text/plain")

    expect_identical(request_target(req)$body, text, info = text)
  }
})

# Hold `port` on 127.0.0.1 alone, as another program can, until `env` exits.
# The listener answers every request with an empty 200.
local_loopback_listener <- function(port, env = parent.frame()) {
  id <- httpuv::startServer(
    "127.0.0.1",
    port,
    list(call = function(req) list(status = 200L, headers = list(), body = ""))
  )
  withr::defer(httpuv::stopServer(id), envir = env)
  invisible(port)
}

# Mock the port picker that curl_echo() calls for each dry run. `pick` takes
# the try number, counted from 1, and returns the port for that try. Read the
# number of tries from `tries$n`.
local_dry_run_ports <- function(pick, env = parent.frame()) {
  tries <- new.env(parent = emptyenv())
  tries$n <- 0L
  testthat::local_mocked_bindings(
    find_port = function(...) {
      tries$n <- tries$n + 1L
      pick(tries$n)
    },
    .package = "curl",
    .env = env
  )
  tries
}

test_that("request_target() reads a request when another program holds the first dry-run port", {
  require_httpuv()
  held <- free_port()
  local_loopback_listener(held)
  # free_port() binds all addresses, which a macOS host allows over a port
  # that 127.0.0.1 alone holds, so the held port is left out of the scan.
  spare <- free_port(setdiff(20000:40000, held))
  tries <- local_dry_run_ports(function(n) if (n == 1L) held else spare)
  req <- httr2::request("http://localhost:1234/v1/models/load") |>
    httr2::req_body_raw('{"model": "m"}', type = "application/json")

  target <- request_target(req)

  expect_identical(target$method, "POST")
  expect_identical(target$path, "/v1/models/load")
  expect_identical(target$body, list(model = "m"))
  expect_identical(tries$n, 2L)
})

# A port held on all addresses can make the echo server's own bind fail, which
# is another outcome the dry-run helper tries again on. With curl 8.2.0 on
# macOS and Windows, the echo server binds 127.0.0.1 over such a port and gets
# the request, so there the test is skipped.
test_that("request_target() reads a request when the echo server cannot bind the first port", {
  require_httpuv()
  held <- local_listener()
  if (!identical(echo_outcome(held), "no-bind")) {
    skip("The echo server binds over a port held on all addresses here.")
  }
  spare <- free_port(setdiff(20000:40000, held))
  tries <- local_dry_run_ports(function(n) if (n == 1L) held else spare)
  req <- httr2::request("http://localhost:1234/v1/models/load") |>
    httr2::req_body_raw('{"model": "m"}', type = "application/json")

  target <- request_target(req)

  expect_identical(target$method, "POST")
  expect_identical(target$body, list(model = "m"))
  expect_identical(tries$n, 2L)
})

# An httpuv handler that returns NULL sends no reply, as a program that does
# not speak HTTP can do. On macOS with curl 8.1.0 or earlier, the echo server
# binds 0.0.0.0 over the held port, so the request reaches that program and
# the first try ends with curl's timeout error. On Linux, and from curl 8.2.0
# on every OS, the echo server cannot bind the held port, so the first try
# ends with httpuv's "Failed to create server". The dry-run helper tries again
# after either one.
test_that("request_target() reads a request when the program on the first dry-run port never replies", {
  testthat::skip_on_cran()
  require_httpuv()
  held <- free_port()
  id <- httpuv::startServer("127.0.0.1", held, list(call = function(req) NULL))
  withr::defer(httpuv::stopServer(id))
  spare <- free_port(setdiff(20000:40000, held))
  tries <- local_dry_run_ports(function(n) if (n == 1L) held else spare)
  req <- httr2::request("http://localhost:1234/v1/models/load") |>
    httr2::req_body_raw('{"model": "m"}', type = "application/json")

  target <- request_target(req)

  expect_identical(target$method, "POST")
  expect_identical(target$body, list(model = "m"))
  expect_identical(tries$n, 2L)
})

# On Ubuntu 24.04 with libcurl 8.5.0, the echo server cannot bind a port that
# another program holds. There each held-port test in this file either
# retries on "Failed to create server" and not on a curl error, or skips.
# Here the first dry run instead gets port 0. The echo server starts with no
# error when it is given port 0, yet curl sends the request to 127.0.0.1 port
# 0, where no program can listen, so curl raises its own error. So with httpuv
# installed, this test runs the retry after a curl error on Linux too.
test_that("request_target() reads a request when the first dry run ends with a curl error", {
  require_httpuv()
  spare <- free_port()
  tries <- local_dry_run_ports(function(n) if (n == 1L) 0L else spare)
  # Keep the first error that a dry run raises, to assert which error it was.
  real_dry_run <- httr2::req_dry_run
  seen <- new.env(parent = emptyenv())
  testthat::local_mocked_bindings(
    req_dry_run = function(...) {
      tryCatch(real_dry_run(...), error = function(cnd) {
        if (is.null(seen$first)) seen$first <- cnd
        stop(cnd)
      })
    },
    .package = "httr2"
  )
  req <- httr2::request("http://localhost:1234/v1/models/load") |>
    httr2::req_body_raw('{"model": "m"}', type = "application/json")

  target <- request_target(req)

  expect_s3_class(seen$first, "curl_error")
  expect_identical(target$method, "POST")
  expect_identical(target$path, "/v1/models/load")
  expect_identical(target$body, list(model = "m"))
  expect_identical(tries$n, 2L)
})

# libcurl reads the proxy variables, and with no_proxy empty it sends even a
# request for 127.0.0.1 to the proxy. Here the proxy port comes from
# free_port(), so in a clean run no program listens there. The control dry run
# below, sent without curl's noproxy option, shows that the proxy is in use:
# it fails to connect, and the same dry run with the noproxy option reaches
# the echo server. A dry run of the helper that went to the proxy would fail
# the same way on every try.
test_that("request_target() reads a request when a proxy is set", {
  require_httpuv()
  proxy_port <- free_port()
  proxy <- paste0("http://127.0.0.1:", proxy_port)
  withr::local_envvar(
    http_proxy = proxy, all_proxy = proxy, no_proxy = "", NO_PROXY = ""
  )
  req <- httr2::request("http://localhost:1234/v1/models/load") |>
    httr2::req_body_raw('{"model": "m"}', type = "application/json")
  control <- tryCatch(
    httr2::req_dry_run(httr2::req_timeout(req, 5), quiet = TRUE),
    curl_error = identity
  )
  # macOS and Linux refuse the connection at once. On the Windows CI runner the
  # connect to the closed port times out at the 2 seconds that curl_echo()
  # allows. The message names the proxy port or the echo port, by the libcurl
  # version, so the test reads only the class.
  connect_classes <- c(
    "curl_error_couldnt_connect", "curl_error_operation_timedout"
  )
  expect_true(inherits(control, connect_classes), info = class(control)[1])
  direct <- httr2::req_dry_run(
    httr2::req_options(httr2::req_timeout(req, 5), noproxy = "*"),
    quiet = TRUE
  )
  expect_identical(direct$method, "POST")
  # free_port() scans from the same start each time, so the echo port must
  # leave the proxy port out, or the echo server would act as the proxy.
  spare <- free_port(setdiff(20000:40000, proxy_port))
  tries <- local_dry_run_ports(function(n) spare)

  target <- request_target(req)

  expect_identical(target$method, "POST")
  expect_identical(target$path, "/v1/models/load")
  expect_identical(target$body, list(model = "m"))
  expect_identical(tries$n, 1L)
})

test_that("the dry-run helper names the cause when every try lands on a held port", {
  require_httpuv()
  held <- free_port()
  local_loopback_listener(held)
  tries <- local_dry_run_ports(function(n) held)
  req <- httr2::request("http://localhost:1234/v1/chat") |>
    httr2::req_body_raw('{"model": "m"}', type = "application/json")

  cnd <- expect_error(request_body_text(req))

  message <- conditionMessage(cnd)
  expect_match(message, "received no request", fixed = TRUE)
  expect_match(tolower(message), "another program", fixed = TRUE)
  expect_no_match(message, "must be a raw vector", fixed = TRUE)
  expect_identical(tries$n, 5L)
})

# curl rejects a path with a space before it connects, so every try fails the
# same way. The stop message must keep curl's own error. The text of that error
# depends on the libcurl build: macOS gives "Malformed input to a URL
# function", and the libcurl 8.5.0 of Ubuntu 24.04 gives "Out of memory". So
# the test reads curl's error for the same dry run first, with the noproxy
# option that the helper sets.
test_that("the dry-run helper keeps curl's error when the request itself is at fault", {
  require_httpuv()
  req <- httr2::request("http://localhost:1234/v1/a b")
  curl_cnd <- tryCatch(
    httr2::req_dry_run(
      httr2::req_options(httr2::req_timeout(req, 5), noproxy = "*"),
      quiet = TRUE
    ),
    curl_error = identity
  )
  expect_s3_class(curl_cnd, "curl_error")

  cnd <- expect_error(request_target(req))

  message <- conditionMessage(cnd)
  expect_match(message, "received no request", fixed = TRUE)
  expect_match(message, conditionMessage(curl_cnd), fixed = TRUE)
})

# Each try must end before the time limit of request_body_text() does. A limit
# that fires inside the dry run can halt R, so here every try lands on a
# program that never replies, under a limit of 3 seconds. Linux refuses the
# echo server's bind over the held port, and so does every OS from curl 8.2.0,
# whose echo server binds 127.0.0.1 itself. There no try reaches the program
# and the test is skipped.
test_that("request_body_text() spreads its time limit over the dry-run tries", {
  testthat::skip_on_cran()
  require_httpuv()
  held <- free_port()
  id <- httpuv::startServer("127.0.0.1", held, list(call = function(req) NULL))
  withr::defer(httpuv::stopServer(id))
  if (!identical(echo_outcome(held), "other")) {
    skip("The echo server cannot bind a port that 127.0.0.1 holds here.")
  }
  tries <- local_dry_run_ports(function(n) held)
  req <- httr2::request("http://localhost:1234/v1/chat") |>
    httr2::req_body_raw('{"model": "m"}', type = "application/json")

  cnd <- expect_error(request_body_text(req, seconds = 3))

  message <- conditionMessage(cnd)
  expect_match(message, "received no request in 5 tries", fixed = TRUE)
  expect_match(message, "Timeout was reached", fixed = TRUE)
  expect_identical(tries$n, 5L)
})

test_that("local_request_sequence() serves its responses in order", {
  recorder <- local_request_sequence(list(
    mock_response(200L, '{"n": 1}'),
    mock_response(200L, '{"n": 2}')
  ))
  req <- httr2::request("http://localhost:1234")

  first <- httr2::req_perform(req)
  second <- httr2::req_perform(req)

  expect_identical(httr2::resp_body_json(first)$n, 1L)
  expect_identical(httr2::resp_body_json(second)$n, 2L)
  expect_length(recorder$requests, 2L)
})

test_that("local_request_sequence() raises on a request past its list", {
  local_request_sequence(list(mock_response(200L, '{"n": 1}')))
  req <- httr2::request("http://localhost:1234")
  httr2::req_perform(req)

  expect_error(httr2::req_perform(req), "request 2 arrived")
})

Try the rlmstudio package in your browser

Any scripts or data that you put into this service are public.

rlmstudio documentation built on Dec. 1, 2026, 9:07 a.m.