File: test-req-throttle.R

package info (click to toggle)
r-cran-httr2 1.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,604 kB
  • sloc: sh: 21; makefile: 2
file content (78 lines) | stat: -rw-r--r-- 2,210 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
test_that("throttling affects request performance", {
  skip_on_cran()
  on.exit(throttle_reset())
  local_mocked_bindings(unix_time = function() 0)

  req <- request_test() %>% req_throttle(capacity = 4, fill_time_s = 1)
  . <- replicate(4, req_perform(req))

  local_mocked_bindings(unix_time = function() 0.1)
  expect_snapshot(time <- system.time(req_perform(req))[[3]])
  expect_gte(time, 1/4 - 0.1)
})

test_that("first request isn't throttled", {
  on.exit(throttle_reset())

  mock_time <- 0
  local_mocked_bindings(unix_time = function() mock_time)

  req <- request_test() %>% req_throttle(rate = 1, fill_time_s = 1)
  expect_equal(throttle_delay(req), 0)

  mock_time <- 0.1
  expect_equal(throttle_delay(req), 0.9)

  mock_time <- 1.5
  expect_equal(throttle_delay(req), 0.5)
})

test_that("realm defaults to hostname but can be overridden", {
  on.exit(throttle_reset())

  expect_named(the$throttle, character())

  request_test() %>% req_throttle(100 / 1)
  expect_named(the$throttle, "127.0.0.1")

  throttle_reset()
  request_test() %>% req_throttle(100 / 1, realm = "custom")
  expect_named(the$throttle, "custom")
})

# token bucket ----------------------------------------------------------------

test_that("token bucket respects capacity limits", {
  mock_time <- 0
  local_mocked_bindings(unix_time = function() mock_time)

  bucket <- TokenBucket$new(capacity = 2, fill_time_s = 1)
  expect_equal(bucket$take_token(), 0)
  expect_equal(bucket$tokens, 1)
  expect_equal(bucket$take_token(), 0)
  expect_equal(bucket$tokens, 0)

  expect_equal(bucket$take_token(), 0.5)
  mock_time <- 0.5
  expect_equal(bucket$take_token(), 0.5)
})

test_that("token bucket handles fractions correctly", {
  mock_time <- 0
  local_mocked_bindings(unix_time = function() mock_time)

  bucket <- TokenBucket$new(capacity = 2, fill_time_s = 1)
  bucket$tokens <- 0
  expect_equal(bucket$take_token(), 0.5)
  expect_equal(bucket$tokens, -1)
  mock_time <- 0.5
  expect_equal(bucket$refill(), 0)

  bucket$last_fill <- 0
  bucket$tokens <- 0
  mock_time <- 0.4
  expect_equal(bucket$refill(), 0.80)
  expect_equal(bucket$take_token(), 0.1)
  mock_time <- mock_time + 0.1
  expect_equal(bucket$refill(), 0)
})