MCPcopy Create free account
hub / github.com/InterviewReady/Low-Level-Design / RateLimitTest

Class RateLimitTest

rate-limiter/src/test/java/RateLimitTest.java:7–74  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5import java.util.concurrent.TimeUnit;
6
7public class RateLimitTest {
8
9 @Test
10 public void testDefaultBehaviour() throws Exception {
11 final TimeUnit timeUnit = TimeUnit.SECONDS;
12 final TestTimer timer = new TestTimer();
13 final TimerWheel timerWheel = new TimerWheel(timeUnit, 6, 3, timer);
14 timerWheel.addRequest(new Request("1", timer.getCurrentTime(timeUnit))).get();
15 timerWheel.addRequest(new Request("2", timer.getCurrentTime(timeUnit))).get();
16 timerWheel.addRequest(new Request("3", timer.getCurrentTime(timeUnit))).get();
17 Throwable exception = null;
18 try {
19 timerWheel.addRequest(new Request("4", timer.getCurrentTime(timeUnit))).get();
20 } catch (Exception e) {
21 exception = e.getCause();
22 }
23 Assert.assertNotNull(exception);
24 Assert.assertEquals("Rate limit exceeded", exception.getMessage());
25 tick(timeUnit, timer, timerWheel);
26 timerWheel.addRequest(new Request("4", timer.getCurrentTime(timeUnit))).get();
27 timerWheel.addRequest(new Request("5", timer.getCurrentTime(timeUnit))).get();
28 timerWheel.evict("1").get();
29 timerWheel.evict("4").get();
30 timerWheel.addRequest(new Request("6", timer.getCurrentTime(timeUnit))).get();
31 timerWheel.addRequest(new Request("7", timer.getCurrentTime(timeUnit))).get();
32 }
33
34 @Test
35 public void testClearing() throws Exception {
36 final TimeUnit timeUnit = TimeUnit.SECONDS;
37 final TestTimer timer = new TestTimer();
38 final int timeOutPeriod = 6;
39 final TimerWheel timerWheel = new TimerWheel(timeUnit, timeOutPeriod, 3, timer);
40 timerWheel.addRequest(new Request("0", timer.getCurrentTime(timeUnit))).get();
41 timerWheel.addRequest(new Request("1", timer.getCurrentTime(timeUnit))).get();
42 timerWheel.addRequest(new Request("2", timer.getCurrentTime(timeUnit))).get();
43
44 Throwable exception = null;
45 try {
46 timerWheel.addRequest(new Request("3", timer.getCurrentTime(timeUnit))).get();
47 } catch (Exception e) {
48 exception = e.getCause();
49 }
50 Assert.assertNotNull(exception);
51 Assert.assertEquals("Rate limit exceeded", exception.getMessage());
52
53 for (int i = 0; i < timeOutPeriod; i++) {
54 tick(timeUnit, timer, timerWheel);
55 }
56 timerWheel.addRequest(new Request("4", timer.getCurrentTime(timeUnit))).get();
57 timerWheel.addRequest(new Request("5", timer.getCurrentTime(timeUnit))).get();
58 timerWheel.addRequest(new Request("6", timer.getCurrentTime(timeUnit))).get();
59
60 exception = null;
61 try {
62 timerWheel.addRequest(new Request("7", timer.getCurrentTime(timeUnit))).get();
63 } catch (Exception e) {
64 exception = e.getCause();

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected