import pytest from unittest.mock import MagicMock, patch from fastapi import HTTPException from src.services.rate_limiter import RateLimiter import asyncio @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