private RateLimiter createRateLimiter() { Map<String, Integer> tagToTargetRateMap = new HashMap<>(); tagToTargetRateMap.put("red", TARGET_RATE_RED); tagToTargetRateMap.put("green", TARGET_RATE_GREEN); RateLimiter rateLimiter = new EmbeddedTaggedRateLimiter(tagToTargetRateMap); initRateLimiter(rateLimiter); return rateLimiter; }
@Test(expected = IllegalArgumentException.class) public void testFailsWhenNotUsingTags() { Map<String, Integer> tagToCredits = new HashMap<>(); tagToCredits.put("red", 1); tagToCredits.put("green", 1); RateLimiter rateLimiter = new EmbeddedTaggedRateLimiter(tagToCredits); initRateLimiter(rateLimiter); rateLimiter.acquire(1); }
@Test(expected = IllegalArgumentException.class) public void testFailsWhenUsingTags() { RateLimiter rateLimiter = new EmbeddedTaggedRateLimiter(10); initRateLimiter(rateLimiter); Map<String, Integer> tagToCredits = new HashMap<>(); tagToCredits.put("red", 1); tagToCredits.put("green", 1); rateLimiter.acquire(tagToCredits); }
@Test @Ignore("Flaky Test.") public void testAcquireWithTimeout() { RateLimiter rateLimiter = new EmbeddedTaggedRateLimiter(TARGET_RATE); initRateLimiter(rateLimiter); boolean hasSeenZeros = false; int count = 0; int callCount = 0; long start = System.currentTimeMillis(); while (System.currentTimeMillis() - start < TEST_INTERVAL) { ++callCount; int availableCredits = rateLimiter.acquire(INCREMENT, 20, MILLISECONDS); if (availableCredits <= 0) { hasSeenZeros = true; } else { count += INCREMENT; } } long rate = count * 1000 / TEST_INTERVAL; verifyRate(rate); junit.framework.Assert.assertTrue(Math.abs(callCount - TARGET_RATE_PER_TASK * TEST_INTERVAL / 1000 / INCREMENT) <= 2); junit.framework.Assert.assertFalse(hasSeenZeros); }
@Test @Ignore("Flaky Test: Test fails in travis.") public void testAcquire() { RateLimiter rateLimiter = new EmbeddedTaggedRateLimiter(TARGET_RATE); initRateLimiter(rateLimiter); int count = 0; long start = System.currentTimeMillis(); while (System.currentTimeMillis() - start < TEST_INTERVAL) { rateLimiter.acquire(INCREMENT); count += INCREMENT; } long rate = count * 1000 / TEST_INTERVAL; verifyRate(rate); }