tests/testthat/helper-ports.R

# Ports for the tests that need a real TCP socket. The scan starts at a point
# set by the process id and walks forward, so it never calls the random number
# generator: sample() would move .Random.seed for every later test, and under a
# fixed seed it would try the same ports on every run. The process id is
# multiplied by 97, so two R processes with adjacent ids start 97 ports apart.
# A port that another socket holds on all addresses makes serverSocket() raise,
# so the scan moves on to the next one. On macOS a port that a program holds on
# 127.0.0.1 alone does not make it raise (see free_port() below).

# Bind the first free port in `ports` and return the open connection with its
# port. After 50 tries, stop with the range and the number of ports tried.
bind_free_port <- function(ports) {
  start <- (Sys.getpid() * 97) %% length(ports)
  tries <- min(50, length(ports))
  for (i in seq_len(tries)) {
    port <- ports[(start + i - 1) %% length(ports) + 1]
    con <- tryCatch(serverSocket(port), error = function(e) NULL)
    if (!is.null(con)) {
      return(list(con = con, port = port))
    }
  }
  stop(
    "No free port in ", min(ports), "-", max(ports), " (", tries, " tried).",
    call. = FALSE
  )
}

# Open a listening socket and return its port. The socket closes when `env`
# exits, by default the calling test.
local_listener <- function(ports = 20000:40000, env = parent.frame()) {
  bound <- bind_free_port(ports)
  withr::defer(close(bound$con), envir = env)
  bound$port
}

# Return a port that the helper could bind on all addresses a moment ago. The
# helper binds it and gives it back. On macOS that bind also succeeds over a
# port that another program holds on 127.0.0.1 alone, so the returned port can
# be one that such a program listens on.
free_port <- function(ports = 20000:40000) {
  bound <- bind_free_port(ports)
  close(bound$con)
  bound$port
}

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.