Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion R/req-throttle.R
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,6 @@ TokenBucket <- R6::R6Class(
if (self$tokens >= 1) {
0
} else {
self$refill()
(1 - self$tokens) / self$fill_rate
}
},
Expand All @@ -161,6 +160,7 @@ TokenBucket <- R6::R6Class(
# Might cause tokens to drop below 0 temporarily so if you don't end up
# waiting this long, you need to return the token
take_token = function() {
self$refill()
wait <- self$token_wait_time()
self$tokens <- self$tokens - 1
wait
Expand Down
21 changes: 21 additions & 0 deletions tests/testthat/test-req-throttle.R
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,24 @@ test_that("token bucket handles fractions correctly", {
mock_time <- mock_time + 0.1
expect_equal(bucket$refill(), 0)
})

test_that("never returns negative time", {
mock_time <- 0
local_mocked_bindings(unix_time = function() mock_time)

bucket <- TokenBucket$new(capacity = 5, fill_rate = 1)
mock_time <- 5

# first five are free
replicate(5, expect_equal(bucket$take_token(), 0))

# we get another 5 after 5 seconds
mock_time <- mock_time + 5
replicate(5, expect_equal(bucket$take_token(), 0))

# if we only wait a second, we only get one
mock_time <- mock_time + 1
expect_equal(bucket$take_token(), 0)
expect_equal(bucket$take_token(), 1)
expect_equal(bucket$take_token(), 2)
})
Loading