Add terminal history class

This commit is contained in:
Mike Cifelli 2017-04-04 07:56:35 -04:00
parent 2de2e3947a
commit 243f8a83ac
2 changed files with 145 additions and 0 deletions

View File

@ -0,0 +1,42 @@
package terminal;
import java.util.*;
public class TerminalHistory {
private List<String> history;
private int currentLineIndex;
public TerminalHistory() {
this.history = new ArrayList<>();
this.currentLineIndex = 0;
}
public void addLine(String line) {
history.add(line);
currentLineIndex = history.size();
}
public String getPreviousLine() {
if (isBeginning())
return null;
return history.get(--currentLineIndex);
}
private boolean isBeginning() {
return currentLineIndex == 0;
}
public String getNextLine() {
if (isEnd())
return null;
return history.get(++currentLineIndex);
}
private boolean isEnd() {
return currentLineIndex >= history.size() - 1;
}
}

View File

@ -0,0 +1,103 @@
package terminal;
import static org.junit.Assert.*;
import org.junit.*;
public class TerminalHistoryTest {
private TerminalHistory history;
private void assertAtBeginning() {
assertNull(history.getPreviousLine());
}
private void assertAtEnd() {
assertNull(history.getNextLine());
}
private void assertPrevious(String expected) {
assertEquals(expected, history.getPreviousLine());
}
private void assertNext(String expected) {
assertEquals(expected, history.getNextLine());
}
@Before
public void setUp() {
history = new TerminalHistory();
}
@After
public void tearDown() {}
@Test
public void historyStartsWithNoLines() {
assertAtBeginning();
assertAtEnd();
}
@Test
public void addOneLineToHistory() {
history.addLine("test line");
assertPrevious("test line");
assertAtBeginning();
assertAtEnd();
}
@Test
public void moveBackwards() {
history.addLine("one");
history.addLine("two");
assertPrevious("two");
assertPrevious("one");
assertAtBeginning();
}
@Test
public void moveForwards() {
history.addLine("one");
history.addLine("two");
history.getPreviousLine();
history.getPreviousLine();
assertNext("two");
assertAtEnd();
}
@Test
public void moveBackAndForth() {
history.addLine("one");
history.addLine("two");
assertAtEnd();
assertPrevious("two");
assertAtEnd();
assertPrevious("one");
assertAtBeginning();
assertNext("two");
assertAtEnd();
assertPrevious("one");
assertAtBeginning();
assertNext("two");
assertAtEnd();
}
@Test
public void addedLineGoesAtEndOfHistory() {
history.addLine("one");
history.addLine("two");
history.getPreviousLine();
history.getPreviousLine();
history.addLine("three");
assertPrevious("three");
assertPrevious("two");
assertPrevious("one");
assertAtBeginning();
}
}