Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added unit tests and updated documentation #94

Merged
merged 2 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ The simplest option is
which can be used as a drop-in replacement for
[`requests.Session`](https://requests.readthedocs.io/en/latest/api/#requests.Session).

Note: By default, each session will perform rate limiting independently. If you are using a multi-threaded environment
or multiple processes, you should use a persistent backend like SQLite or Redis which can persist the rate limit across
threads, processes, and/or application restarts. When using `requests-ratelimiter` as part of a web application, it is
recommended to use a persistent backend to ensure that the rate limit is shared across all requests.

Example:
```python
from requests_ratelimiter import LimiterSession
Expand Down Expand Up @@ -236,22 +241,22 @@ For example, to combine with [requests-cache](https://github.com/requests-cache/
also includes a separate mixin class:
```python
from requests import Session
from requests_cache import CacheMixin, RedisCache
from requests_ratelimiter import LimiterMixin, RedisBucket
from requests_cache import CacheMixin
from requests_ratelimiter import LimiterMixin, SQLiteBucket


class CachedLimiterSession(CacheMixin, LimiterMixin, Session):
"""Session class with caching and rate-limiting behavior. Accepts arguments for both
"""
Session class with caching and rate-limiting behavior. Accepts arguments for both
LimiterSession and CachedSession.
"""


# Optionally use Redis as both the bucket backend and the cache backend
session = CachedLimiterSession(
per_second=5,
bucket_class=RedisBucket,
backend=RedisCache(),
)
# Optionally use SQLite as both the bucket backend and the cache backend
session = CachedLimiterSession(per_second=5,
cache_name='cache.db',
bucket_class=SQLiteBucket,
bucket_kwargs={"path": "cache.db", 'isolation_level': "EXCLUSIVE", 'check_same_thread': False})
```

This example has an extra benefit: cache hits won't count against your rate limit!
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pytest = "^7.2"
pytest-cov = ">=4.0"
pytest-xdist = ">=3.1"
requests-mock = ">=1.11"
requests_cache = ">=1.2"

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand Down
83 changes: 65 additions & 18 deletions test/test_requests_ratelimiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
General rate-limiting behavior is covered by pyrate-limiter unit tests. These tests should cover
additional behavior specific to requests-ratelimiter.
"""
import os

from test.conftest import (
MOCKED_URL,
Expand All @@ -15,10 +16,10 @@
from unittest.mock import patch

import pytest
from pyrate_limiter import Duration, Limiter, RequestRate
from pyrate_limiter import Duration, Limiter, RequestRate, SQLiteBucket
from requests import Response, Session
from requests.adapters import HTTPAdapter

from requests_cache import CacheMixin, SQLiteCache
from requests_ratelimiter import LimiterAdapter, LimiterMixin, LimiterSession
from requests_ratelimiter.requests_ratelimiter import _convert_rate

Expand Down Expand Up @@ -95,22 +96,6 @@ def test_custom_session(mock_sleep):
session.get(MOCKED_URL)
assert mock_sleep.called is True


@patch_sleep
def test_custom_bucket(mock_sleep):
"""With custom buckets, each session can be called independently without triggering rate limiting"""
session_a = get_mock_session(per_second=5, bucket_name="a")
session_b = get_mock_session(per_second=5, bucket_name="b")

for _ in range(5):
session_a.get(MOCKED_URL)
session_b.get(MOCKED_URL)
assert mock_sleep.called is False

session_a.get(MOCKED_URL)
assert mock_sleep.called is True


@patch_sleep
def test_429(mock_sleep):
"""After receiving a 429 response, the bucket should be filled, allowing no more requests"""
Expand Down Expand Up @@ -170,3 +155,65 @@ def test_convert_rate(limit, interval, expected_limit, expected_interval):
rate = _convert_rate(limit, interval)
assert rate.limit == expected_limit
assert rate.interval == expected_interval


@patch_sleep
def test_sqlite_backend(mock_sleep):
"""Check that the SQLite backend works as expected"""
session = get_mock_session(per_second=5, bucket_class=SQLiteBucket, bucket_kwargs={"path": "rate_limit.db", 'isolation_level': "EXCLUSIVE", 'check_same_thread': False})

for _ in range(5):
session.get(MOCKED_URL)
assert mock_sleep.called is False

session.get(MOCKED_URL)
assert mock_sleep.called is True

# force the database to close & clean up
del session
os.remove("rate_limit.db")


@patch_sleep
def test_custom_bucket(mock_sleep):
"""With custom buckets, each session can be called independently without triggering rate limiting but requires a common backend such as sqlite"""
session_a = get_mock_session(per_second=5, bucket_name="a", bucket_class=SQLiteBucket, bucket_kwargs={"path": "rate_limit.db", 'isolation_level': "EXCLUSIVE", 'check_same_thread': False})
session_b = get_mock_session(per_second=5, bucket_name="b", bucket_class=SQLiteBucket, bucket_kwargs={"path": "rate_limit.db", 'isolation_level': "EXCLUSIVE", 'check_same_thread': False})

for _ in range(5):
session_a.get(MOCKED_URL)
session_b.get(MOCKED_URL)
assert mock_sleep.called is False

session_a.get(MOCKED_URL)
assert mock_sleep.called is True

# force the database to close & clean up
del session_a
del session_b
os.remove("rate_limit.db")


@patch_sleep
def test_caching(mock_sleep):
"""Check that caching integration works as expected"""

class CachedLimiterSession(CacheMixin, LimiterMixin, Session):
"""
Session class with caching and rate-limiting behavior. Accepts arguments for both
LimiterSession and CachedSession.
"""

session = CachedLimiterSession(per_second=5, cache_name='cache.db', bucket_class=SQLiteBucket, bucket_kwargs={"path": "cache.db", 'isolation_level': "EXCLUSIVE", 'check_same_thread': False})
session = mount_mock_adapter(session)

for _ in range(10):
session.get(MOCKED_URL)
assert mock_sleep.called is False


# force the database to close & clean up
del session
os.remove("cache.db")


Loading