Skip to content
This repository has been archived by the owner on Jun 3, 2024. It is now read-only.

Commit

Permalink
Merge pull request #102 from QwantResearch/test-rate-limiter
Browse files Browse the repository at this point in the history
Add a test case about rate limited response
  • Loading branch information
amatissart authored Jan 3, 2020
2 parents 2fb4c74 + 8b50643 commit 1ff671e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
12 changes: 9 additions & 3 deletions idunn/utils/rate_limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ class HTTPTooManyRequests(HTTPException):

class IdunnRateLimiter:
def __init__(self, resource, max_requests, expire):
self.resource = resource
self.max_requests = max_requests
self.expire = expire
self._init_limiter()

def _init_limiter(self):
try:
redis_pool = get_redis_pool(db=settings['RATE_LIMITER_REDIS_DB'])
except RedisNotConfigured:
Expand All @@ -32,9 +38,9 @@ def __init__(self, resource, max_requests, expire):
service in the rate limiter.
"""
self._limiter = RateLimiter(
resource=resource,
max_requests=max_requests,
expire=expire,
resource=self.resource,
max_requests=self.max_requests,
expire=self.expire,
redis_pool=redis_pool
)

Expand Down
20 changes: 20 additions & 0 deletions tests/test_directions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import pytest
from apistar.test import TestClient
from app import app
from idunn.api.directions import rate_limiter

from .utils import override_settings

Expand All @@ -29,6 +30,14 @@ def mock_directions_car():
)
yield

@pytest.fixture
def mock_directions_car_with_rate_limiter(redis, mock_directions_car):
with override_settings({"REDIS_URL": redis}):
rate_limiter._init_limiter()
yield
# reset rate_limiter to default redis connection url
rate_limiter._init_limiter()


@pytest.fixture
def mock_directions_public_transport():
Expand Down Expand Up @@ -124,3 +133,14 @@ def test_directions_not_configured():
params={"language": "fr", "type": "driving"},
)
assert response.status_code == 501

def test_directions_rate_limiter(mock_directions_car_with_rate_limiter):
client = TestClient(app)
# rate limiter is triggered after 30 req/min by default
for i in range(40):
response = client.get(
"http://localhost/v1/directions/"
"2.3402355%2C48.8900732%3B2.3688579%2C48.8529869",
params={"language": "fr", "type": "driving"},
)
assert response.status_code == 429

0 comments on commit 1ff671e

Please sign in to comment.