Files
FitTrack_GarminSync/backend/tests/unit/test_rate_limiter.py
sstent ca9d7d9e90 Complete spec: Code alignment and documentation cleanup
- Ensure code aligns with CentralDB models
- Document code alignment with CentralDB models
- Remove informal reference documents (data-model.md, DB_API_SPEC.json, GARMINSYNC_SPEC.md)
- Run linters and formatters (black, isort, mypy)
- Update project configuration files
- Add .dockerignore for Docker builds
- Perform code formatting and import sorting
- Fix type checking issues
- Update documentation files
- Complete implementation tasks as per spec
2025-12-18 13:21:54 -08:00

46 lines
1.5 KiB
Python

from unittest.mock import MagicMock, patch
import pytest
from fastapi import HTTPException
from backend.src.services.rate_limiter import RateLimiter
@pytest.mark.asyncio
async def test_rate_limiter_allows_requests_within_limit():
"""Test that the rate limiter allows requests that are within the limit."""
rate_limiter = RateLimiter(rate_limit="2/second")
mock_request = MagicMock()
try:
await rate_limiter(mock_request)
await rate_limiter(mock_request)
except HTTPException:
pytest.fail("HTTPException raised unexpectedly.")
@pytest.mark.asyncio
async def test_rate_limiter_raises_exception_when_exceeded():
"""Test that the rate limiter raises an HTTPException when the rate limit is exceeded."""
rate_limiter = RateLimiter(rate_limit="1/second")
mock_request = MagicMock()
# Mock the limiter.test method
with patch.object(rate_limiter.limiter, "test") as mock_limiter_test:
mock_limiter_test.side_effect = [
True,
False,
] # First call returns True, second returns False
await rate_limiter(mock_request) # First call, should pass
with pytest.raises(HTTPException) as exc_info:
await rate_limiter(mock_request) # Second call, should fail
assert exc_info.value.status_code == 429
mock_limiter_test.assert_called_with(
rate_limiter.rate_limit_item, "single_user_system"
)
assert exc_info.value.status_code == 429