@Test public void testTimerWithDifferentWindowSize() { Timer timer = new Timer("test", 300, clock); timer.update(1L); timer.update(2L); timer.update(3L); Snapshot snapshot = timer.getSnapshot(); assertTrue(snapshot.getValues().containsAll(Arrays.asList(1L, 2L, 3L))); assertEquals(3, snapshot.getValues().size()); // The time is 500 for update(4L) because getSnapshot calls clock once + 3 // updates that call clock 3 times timer.update(4L); Snapshot snapshot2 = timer.getSnapshot(); assertTrue(snapshot2.getValues().containsAll(Arrays.asList(3L, 4L))); assertEquals(2, snapshot2.getValues().size()); } }
@Test public void testRemoveExpiredValues() { SlidingTimeWindowReservoir slidingTimeWindowReservoir = new SlidingTimeWindowReservoir(300, 8, clock); when(clock.currentTimeMillis()).thenReturn(0L); slidingTimeWindowReservoir.update(1L); when(clock.currentTimeMillis()).thenReturn(100L); slidingTimeWindowReservoir.update(2L); when(clock.currentTimeMillis()).thenReturn(301L); slidingTimeWindowReservoir.update(3L); when(clock.currentTimeMillis()).thenReturn(500L); slidingTimeWindowReservoir.update(4L); Snapshot snapshot = slidingTimeWindowReservoir.getSnapshot(); assertTrue(snapshot.getValues().containsAll(Arrays.asList(3L, 4L))); assertEquals(2, snapshot.getSize()); }
@Test public void testUpdateSizeSnapshot() { SlidingTimeWindowReservoir slidingTimeWindowReservoir = new SlidingTimeWindowReservoir(300, 8, clock); when(clock.currentTimeMillis()).thenReturn(0L); slidingTimeWindowReservoir.update(1L); when(clock.currentTimeMillis()).thenReturn(1L); slidingTimeWindowReservoir.update(2L); when(clock.currentTimeMillis()).thenReturn(2L); slidingTimeWindowReservoir.update(3L); assertEquals(3, slidingTimeWindowReservoir.size()); Snapshot snapshot = slidingTimeWindowReservoir.getSnapshot(); assertTrue(snapshot.getValues().containsAll(Arrays.asList(1L, 2L, 3L))); assertEquals(3, snapshot.getSize()); }
@Test public void testDuplicateTime() { SlidingTimeWindowReservoir slidingTimeWindowReservoir = new SlidingTimeWindowReservoir(300, 2, clock); when(clock.currentTimeMillis()).thenReturn(1L); slidingTimeWindowReservoir.update(1L); slidingTimeWindowReservoir.update(2L); Snapshot snapshot = slidingTimeWindowReservoir.getSnapshot(); assertTrue(snapshot.getValues().containsAll(Arrays.asList(1L, 2L))); assertEquals(2, snapshot.getSize()); // update causes collision, will override the last update slidingTimeWindowReservoir.update(3L); snapshot = slidingTimeWindowReservoir.getSnapshot(); assertTrue(snapshot.getValues().containsAll(Arrays.asList(1L, 3L))); assertEquals(2, snapshot.getSize()); }