1 package ch.qos.logback.core.util; 2 3 import static ch.qos.logback.core.util.DefaultInvocationGate.DEFAULT_MASK; 4 import static ch.qos.logback.core.util.DefaultInvocationGate.MASK_DECREASE_RIGHT_SHIFT_COUNT; 5 import static org.junit.Assert.*; 6 7 import org.junit.Test; 8 9 public class DefaultInvocationGateTest { 10 11 @Test 12 public void smoke() { 13 long currentTime = 0; 14 long minDelayThreshold = 4; 15 long maxDelayThreshold = 8; 16 17 DefaultInvocationGate gate = new DefaultInvocationGate(minDelayThreshold, maxDelayThreshold, currentTime); 18 assertTrue(gate.isTooSoon(0)); 19 } 20 21 @Test 22 public void closelyRepeatedCallsShouldCauseMaskToIncrease() { 23 long currentTime = 0; 24 long minDelayThreshold = 4; 25 long maxDelayThreshold = 8; 26 27 DefaultInvocationGate gate = new DefaultInvocationGate(minDelayThreshold, maxDelayThreshold, currentTime); 28 for (int i = 0; i < DEFAULT_MASK; i++) { 29 assertTrue(gate.isTooSoon(0)); 30 } 31 assertFalse(gate.isTooSoon(0)); 32 assertTrue(gate.getMask() > DEFAULT_MASK); 33 } 34 35 @Test 36 public void stableAtSteadyRate() { 37 long currentTime = 0; 38 long minDelayThreshold = DEFAULT_MASK; 39 long maxDelayThreshold = DEFAULT_MASK * 2; 40 41 DefaultInvocationGate gate = new DefaultInvocationGate(minDelayThreshold, maxDelayThreshold, currentTime); 42 43 for (int t = 0; t < 4 * minDelayThreshold; t++) { 44 gate.isTooSoon(currentTime++); 45 assertEquals(DEFAULT_MASK, gate.getMask()); 46 } 47 } 48 49 @Test 50 public void intermittentCallsShouldCauseMaskToDecrease() { 51 long currentTime = 0; 52 long minDelayThreshold = 4; 53 long maxDelayThreshold = 8; 54 55 DefaultInvocationGate gate = new DefaultInvocationGate(minDelayThreshold, maxDelayThreshold, currentTime); 56 int currentMask = DEFAULT_MASK; 57 58 currentTime += maxDelayThreshold + 1; 59 assertFalse(gate.isTooSoon(currentTime)); 60 assertTrue(gate.getMask() < currentMask); 61 } 62 63 @Test 64 public void maskCanDropToZeroForInfrequentInvocations() { 65 long currentTime = 0; 66 long minDelayThreshold = 4; 67 long maxDelayThreshold = 8; 68 69 DefaultInvocationGate gate = new DefaultInvocationGate(minDelayThreshold, maxDelayThreshold, currentTime); 70 int currentMask = DEFAULT_MASK; 71 72 do { 73 currentTime += maxDelayThreshold + 1; 74 assertFalse(gate.isTooSoon(currentTime)); 75 assertTrue(gate.getMask() < currentMask); 76 currentMask = currentMask >> MASK_DECREASE_RIGHT_SHIFT_COUNT; 77 } while (currentMask > 0); 78 79 assertEquals(0, gate.getMask()); 80 assertFalse(gate.isTooSoon(currentTime)); 81 } 82 }