Skip to content

Commit 9af55eb

Browse files
committed
Fix bug in the ratelimit helper & add a few more tests
1 parent c3b283e commit 9af55eb

2 files changed

Lines changed: 14 additions & 5 deletions

File tree

mrq/helpers.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
def ratelimit(key, limit, per=1, redis=None):
77
""" Returns an integer with the number of available actions for the
8-
current period. If zero, rate was already reached. """
8+
current period in seconds. If zero, rate was already reached. """
99

1010
if redis is None:
1111
redis = connections.redis
@@ -17,10 +17,10 @@ def ratelimit(key, limit, per=1, redis=None):
1717

1818
with redis.pipeline(transaction=True) as pipeline:
1919
pipeline.incr(k, 1)
20-
pipeline.expire(k, 10)
20+
pipeline.expire(k, per + 10)
2121
value = pipeline.execute()
2222

23-
current = int(value[0])
23+
current = int(value[0]) - 1
2424

2525
if current >= limit:
2626
return 0

tests/test_ratelimit.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,16 @@ def test_helpers_ratelimit(worker):
66

77
worker.start_deps()
88

9-
for i in range(1, 10):
9+
assert ratelimit("k3", 1, per=1) == 1
10+
assert ratelimit("k3", 1, per=1) == 0
11+
assert ratelimit("k3", 1, per=1) == 0
12+
13+
for i in range(0, 10):
1014
r = ratelimit("k", 10, per=1)
1115
assert r == 10 - i
1216

1317
assert ratelimit("k", 10, per=1) == 0
14-
assert ratelimit("k2", 5, per=1) == 4
18+
assert ratelimit("k2", 5, per=1) == 5
1519

1620
# We *could* have failures there if we go over a second but we've not seen
1721
# it much so far.
@@ -21,4 +25,9 @@ def test_helpers_ratelimit(worker):
2125
# TODO: test the "per" argument a bit better.
2226
time.sleep(1)
2327

28+
assert ratelimit("k", 10, per=1) == 10
2429
assert ratelimit("k", 10, per=1) == 9
30+
31+
# This is actually another counter.
32+
assert ratelimit("k", 10, per=10) == 10
33+
assert ratelimit("k", 10, per=10) == 9

0 commit comments

Comments
 (0)