|
| 1 | +package edu.luc.cs.consoleapp; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.*; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.LinkedList; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Queue; |
| 9 | + |
| 10 | +import org.apache.commons.collections4.queue.CircularFifoQueue; |
| 11 | + |
| 12 | +import org.junit.jupiter.api.Test; |
| 13 | + |
| 14 | +public class TestMainNotDRY { |
| 15 | + |
| 16 | + @Test |
| 17 | + public void testSlidingWindowEmpty() { |
| 18 | + final var input = List.<String>of().iterator(); |
| 19 | + final var output = new OutputToList(); |
| 20 | + final var queue = new CircularFifoQueue<String>(3); |
| 21 | + input.forEachRemaining( |
| 22 | + word -> { |
| 23 | + queue.add(word); // the oldest item automatically gets evicted |
| 24 | + output.accept(queue); // send updated queue to output handler |
| 25 | + }); |
| 26 | + final var result = output.result; |
| 27 | + assertTrue(result.isEmpty()); |
| 28 | + } |
| 29 | + |
| 30 | + @Test |
| 31 | + public void testSlidingWindowNonempty() { |
| 32 | + final var input = List.of("asdf", "qwer", "oiui", "zxcv").iterator(); |
| 33 | + final var output = new OutputToList(); |
| 34 | + final var queue = new CircularFifoQueue<String>(3); |
| 35 | + input.forEachRemaining( |
| 36 | + word -> { |
| 37 | + queue.add(word); // the oldest item automatically gets evicted |
| 38 | + output.accept(queue); // send updated queue to output handler |
| 39 | + }); |
| 40 | + final var result = output.result; |
| 41 | + assertEquals(4, result.size()); |
| 42 | + assertEquals(List.of("asdf"), result.get(0)); |
| 43 | + assertEquals(List.of("asdf", "qwer"), result.get(1)); |
| 44 | + assertEquals(List.of("asdf", "qwer", "oiui"), result.get(2)); |
| 45 | + assertEquals(List.of("qwer", "oiui", "zxcv"), result.get(3)); |
| 46 | + } |
| 47 | + |
| 48 | + private static class OutputToList implements OutputHandler { |
| 49 | + |
| 50 | + final List<Queue<String>> result = new ArrayList<>(); |
| 51 | + |
| 52 | + @Override |
| 53 | + public void accept(final Queue<String> value) { |
| 54 | + final var snapshot = new LinkedList<>(value); |
| 55 | + result.add(snapshot); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments