1+ package io .github .gunkim .ratelimiter .window ;
2+
3+ import org .junit .jupiter .api .DisplayName ;
4+ import org .junit .jupiter .api .Test ;
5+
6+ import java .util .concurrent .CountDownLatch ;
7+ import java .util .concurrent .TimeUnit ;
8+ import java .util .concurrent .atomic .AtomicInteger ;
9+
10+ import static org .assertj .core .api .Assertions .assertThat ;
11+ import static org .mockito .Mockito .mock ;
12+ import static org .mockito .Mockito .times ;
13+ import static org .mockito .Mockito .verify ;
14+
15+ @ DisplayName ("FixedWindowRateLimiter는" )
16+ class FixedWindowRateLimiterTest {
17+ private static final int WINDOW_SIZE = 10_000 ;
18+ private static final int REQUESTS_LIMIT = 2 ;
19+
20+ @ Test
21+ void window_size_이내_요청은_처리된다 () {
22+ Runnable runnable = mock (Runnable .class );
23+ FixedWindowRateLimiter rateLimiter = createRateLimiter (10 );
24+ rateLimiter .request (runnable );
25+ verify (runnable , times (1 )).run ();
26+ }
27+
28+ @ Test
29+ void window_size가_2이고_요청이_3회라면_2회만_처리된다 () throws InterruptedException {
30+ int requestCount = 3 ;
31+ AtomicInteger counter = new AtomicInteger (0 );
32+ CountDownLatch countDownLatch = new CountDownLatch (REQUESTS_LIMIT );
33+ Runnable request = createRunnable (counter , countDownLatch );
34+
35+ FixedWindowRateLimiter rateLimiter = createRateLimiter (REQUESTS_LIMIT );
36+ sendRequests (rateLimiter , request , requestCount );
37+
38+ countDownLatch .await (1 , TimeUnit .SECONDS );
39+ assertThat (counter .get ()).isEqualTo (REQUESTS_LIMIT );
40+ }
41+
42+ private FixedWindowRateLimiter createRateLimiter (int limit ) {
43+ return new FixedWindowRateLimiter (limit , WINDOW_SIZE );
44+ }
45+
46+ private Runnable createRunnable (AtomicInteger counter , CountDownLatch countDownLatch ) {
47+ return () -> {
48+ counter .incrementAndGet ();
49+ countDownLatch .countDown ();
50+ };
51+ }
52+
53+ private void sendRequests (FixedWindowRateLimiter rateLimiter , Runnable request , int requestCount ) {
54+ for (int i = 0 ; i < requestCount ; i ++) {
55+ rateLimiter .request (request );
56+ }
57+ }
58+ }
0 commit comments