예제 #1
0
def test_headers_generator():
    """
    From a Counter and a RateLimiter (rather, the number of maximum hits per
    bucket would be enough...) we need to be able to calculate a dictionary of
    HTTP headers related to the rate limiting to attach to an HTTP response.
    """
    with mock.patch("time.time") as fake_time:
        # Base values
        fake_time.return_value = 0.0
        limiter = limiters.RateLimiter(mock.Mock())
        limiter.set_max_hits(0)
        counter = rediscounters.Counter(0, 3600000)
        headers = limiters.get_headers(limiter, counter)
        assert_that(headers["X-RateLimit-Limit"], equal_to(0))
        assert_that(headers["X-RateLimit-Remaining"], equal_to(0))
        assert_that(headers["X-RateLimit-Reset"], equal_to(3600))

        # Test values - to force using variables rather than constants
        fake_time.return_value = 3600.25
        limiter.set_max_hits(100)
        counter = rediscounters.Counter(50, 7200000)
        headers = limiters.get_headers(limiter, counter)
        assert_that(headers["X-RateLimit-Limit"], equal_to(100))
        assert_that(headers["X-RateLimit-Remaining"], equal_to(50))
        assert_that(headers["X-RateLimit-Reset"], equal_to(10800))

        # To ensure no negative values appear in X-RateLimite-Remaning.
        counter = rediscounters.Counter(200, 7200000)
        headers = limiters.get_headers(limiter, counter)
        assert_that(headers["X-RateLimit-Remaining"], equal_to(0))
예제 #2
0
def test_no_headers_if_no_counter():
    headers = limiters.get_headers(mock.Mock(), None)
    assert_that(headers, equal_to({}))
예제 #3
0
def test_no_headers_if_limiter_off():
    limiter = limiters.RateLimiter(mock.Mock())
    limiter.switch_off()
    counter = rediscounters.Counter(0, 0)
    headers = limiters.get_headers(limiter, counter)
    assert_that(headers, equal_to({}))