Skip to content

Commit

Permalink
more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
abersheeran committed Jun 23, 2021
1 parent 074a576 commit eb7c551
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 6 deletions.
11 changes: 6 additions & 5 deletions ratelimit/backends/slidingredis.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __init__(
)
self.sliding_function = self._redis.register_script(SLIDING_WINDOW_SCRIPT)

async def get_limits(self, path: str, user: str, rule: Rule) -> bool:
async def get_limits(self, path: str, user: str, rule: Rule) -> dict:
epoch = time.time()
ruleset = rule.ruleset(path, user)
r = await self.sliding_function.execute(
Expand All @@ -69,10 +69,10 @@ async def get_limits(self, path: str, user: str, rule: Rule) -> bool:
async def set_block_time(self, user: str, block_time: int) -> None:
await self._redis.set(f"blocking:{user}", True, block_time)

async def is_blocking(self, user: str) -> bool:
return bool(await self._redis.get(f"blocking:{user}"))
async def is_blocking(self, user: str) -> int:
return int(await self._redis.ttl(f"blocking:{user}"))

async def retry_after(self, path: str, user: str, rule: Rule) -> bool:
async def retry_after(self, path: str, user: str, rule: Rule) -> int:
block_time = await self.is_blocking(user)
if block_time > 0:
return block_time
Expand All @@ -82,5 +82,6 @@ async def retry_after(self, path: str, user: str, rule: Rule) -> bool:

if retry_after > 0 and rule.block_time:
await self.set_block_time(user, rule.block_time)
retry_after = rule.block_time

return retry_after
return round(retry_after)
2 changes: 1 addition & 1 deletion ratelimit/rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@ def ruleset(self, path: str, user: str) -> Dict[str, Tuple[int, int]]:
"month": 31 * 24 * 60 * 60,
}

RULENAMES: Tuple[str] = ("second", "minute", "hour", "day", "month")
RULENAMES: Tuple[str, ...] = ("second", "minute", "hour", "day", "month")
2 changes: 2 additions & 0 deletions tests/backends/test_redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ async def test_redis(redisbackend):
"/second_limit", headers={"user": "user", "group": "default"}
)
assert response.status_code == 429
assert response.headers["retry-after"] == "1"

response = await client.get(
"/second_limit", headers={"user": "admin-user", "group": "admin"}
Expand Down Expand Up @@ -132,6 +133,7 @@ async def test_redis(redisbackend):
"/block", headers={"user": "user", "group": "default"}
)
assert response.status_code == 429
assert response.headers["retry-after"] == "5"

await asyncio.sleep(1)

Expand Down

0 comments on commit eb7c551

Please sign in to comment.