Skip to content

Commit

Permalink
Make throttle testing more reliable with mocking (#538)
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley authored Sep 4, 2024
1 parent 5b456c8 commit 33635e6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
2 changes: 1 addition & 1 deletion R/req-throttle.R
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ req_throttle <- function(req, rate, realm = NULL) {
if (is.null(last)) {
wait <- 0
} else {
wait <- delay - (unix_time() - last)
wait <- max(delay - (unix_time() - last), 0)
}

sys_sleep(wait, "for throttling delay")
Expand Down
19 changes: 16 additions & 3 deletions tests/testthat/test-req-throttle.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,31 @@ test_that("first request isn't throttled", {
skip_on_cran()
throttle_reset()

req <- request_test() %>% req_throttle(50 / 1)
local_mocked_bindings(sys_sleep = function(...) {})
req <- request_test() %>% req_throttle(1)

local_mocked_bindings(unix_time = function() 0)
expect_equal(throttle_delay(req), 0)

local_mocked_bindings(unix_time = function() 0.1)
expect_equal(throttle_delay(req), 0.9)

local_mocked_bindings(unix_time = function() 1.5)
expect_equal(throttle_delay(req), 0)
expect_true(throttle_delay(req) > 0)
})

test_that("throttling causes expected average request rate", {
skip_on_cran()
skip_on_ci()
throttle_reset()

wait <- 0
local_mocked_bindings(sys_sleep = function(seconds, ...) {
wait <<- 0
})

nps <- 20
req <- request_test() %>% req_throttle(nps)
req <- request_test() %>% req_throttle(20)
times <- replicate(20, bench::system_time(req_perform(req)))["real", ]
trimmed <- mean(times, trim = 0.2)

Expand Down

0 comments on commit 33635e6

Please sign in to comment.