Spaces:
Running
Running
File size: 2,959 Bytes
1419a33 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | package com.resumeparser.config;
import com.resumeparser.service.FirestoreRateLimiterService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class RateLimitInterceptorTest {
private FirestoreRateLimiterService rateLimiterService;
private RateLimitInterceptor interceptor;
@BeforeEach
void setUp() {
rateLimiterService = mock(FirestoreRateLimiterService.class);
interceptor = new RateLimitInterceptor(rateLimiterService);
}
@Test
void shouldAllowOptionsRequestsWithoutRateLimiting() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("OPTIONS");
MockHttpServletResponse response = new MockHttpServletResponse();
boolean result = interceptor.preHandle(request, response, new Object());
assertTrue(result);
verifyNoInteractions(rateLimiterService);
}
@Test
void shouldAllowRequestWhenUnderLimit() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
request.setRemoteAddr("192.168.1.50");
MockHttpServletResponse response = new MockHttpServletResponse();
when(rateLimiterService.isAllowed("192.168.1.50")).thenReturn(true);
boolean result = interceptor.preHandle(request, response, new Object());
assertTrue(result);
assertEquals(200, response.getStatus());
}
@Test
void shouldBlockRequestWith429WhenLimitExceeded() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
request.setRemoteAddr("192.168.1.50");
MockHttpServletResponse response = new MockHttpServletResponse();
when(rateLimiterService.isAllowed("192.168.1.50")).thenReturn(false);
boolean result = interceptor.preHandle(request, response, new Object());
assertFalse(result);
assertEquals(429, response.getStatus());
assertTrue(response.getContentAsString().contains("Too many requests"));
}
@Test
void shouldExtractIpFromXForwardedForHeader() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
request.addHeader("X-Forwarded-For", "203.0.113.195, 10.0.0.1");
request.setRemoteAddr("127.0.0.1");
MockHttpServletResponse response = new MockHttpServletResponse();
when(rateLimiterService.isAllowed("203.0.113.195")).thenReturn(true);
boolean result = interceptor.preHandle(request, response, new Object());
assertTrue(result);
verify(rateLimiterService).isAllowed("203.0.113.195");
}
}
|