#2622: Let ThrottleTest work independently of real time

This commit is contained in:
killme 2019-04-13 13:18:19 +02:00 committed by md_5
parent 191afb6a6c
commit 9bce83704a
2 changed files with 26 additions and 2 deletions

View File

@ -1,5 +1,7 @@
package net.md_5.bungee; package net.md_5.bungee;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Ticker;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache; import com.google.common.cache.LoadingCache;
@ -13,8 +15,15 @@ public class ConnectionThrottle
private final int throttleLimit; private final int throttleLimit;
public ConnectionThrottle(int throttleTime, int throttleLimit) public ConnectionThrottle(int throttleTime, int throttleLimit)
{
this(Ticker.systemTicker(), throttleTime, throttleLimit);
}
@VisibleForTesting
ConnectionThrottle(Ticker ticker, int throttleTime, int throttleLimit)
{ {
this.throttle = CacheBuilder.newBuilder() this.throttle = CacheBuilder.newBuilder()
.ticker(ticker)
.concurrencyLevel( Runtime.getRuntime().availableProcessors() ) .concurrencyLevel( Runtime.getRuntime().availableProcessors() )
.initialCapacity( 100 ) .initialCapacity( 100 )
.expireAfterWrite( throttleTime, TimeUnit.MILLISECONDS ) .expireAfterWrite( throttleTime, TimeUnit.MILLISECONDS )

View File

@ -1,17 +1,32 @@
package net.md_5.bungee; package net.md_5.bungee;
import com.google.common.base.Ticker;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
public class ThrottleTest public class ThrottleTest
{ {
private class FixedTicker extends Ticker
{
private long value;
@Override
public long read()
{
return value;
}
}
@Test @Test
public void testThrottle() throws InterruptedException, UnknownHostException public void testThrottle() throws InterruptedException, UnknownHostException
{ {
ConnectionThrottle throttle = new ConnectionThrottle( 10, 3 ); FixedTicker ticker = new FixedTicker();
ConnectionThrottle throttle = new ConnectionThrottle( ticker, 10, 3 );
InetAddress address; InetAddress address;
try try
@ -33,7 +48,7 @@ public class ThrottleTest
Assert.assertTrue( "Address should be throttled", throttle.throttle( address ) ); // 4 Assert.assertTrue( "Address should be throttled", throttle.throttle( address ) ); // 4
// Now test expiration // Now test expiration
Thread.sleep( 50 ); ticker.value += TimeUnit.MILLISECONDS.toNanos( 50 );
Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) );
} }
} }