Skip to content

Commit

Permalink
Fix unstable HistoryPersistenceTest
Browse files Browse the repository at this point in the history
  • Loading branch information
gnodet committed Nov 17, 2016
1 parent fe83731 commit dbf7363
Showing 1 changed file with 42 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.stream.IntStream;

import org.jline.reader.LineReader;
Expand Down Expand Up @@ -41,26 +43,58 @@ public void tearDown() throws IOException {
Files.deleteIfExists(Paths.get("test"));
}

private void doTestFileHistory(int count) {
reader.setVariable(LineReader.HISTORY_FILE, Paths.get("test"));


private void doTestFileHistory(int count, CyclicBarrier barrier) {
DefaultHistory history = new DefaultHistory(reader);
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
assertEquals(count, history.size());
IntStream.range(0, count)
.forEach(i -> history.add("cmd" + i));
history.save();
// we need to synchronize here
// if we don't, multiple writes can occur at the same time and some
// history items may be lost, we'd have to use a file lock to fix that
// but that's not testable
// what we're testing here is the fact that only *new* items are
// written to the file incrementally and that we're not rewriting the
// whole file
synchronized (reader) {
history.save();
}
}

@Test
public void testFileHistory() throws Exception {
doTestFileHistory(3);
List<Thread> ts = IntStream.range(0, 3)
.mapToObj(i -> new Thread(() -> doTestFileHistory(3)))
reader.setVariable(LineReader.HISTORY_FILE, Paths.get("test"));
reader.unsetOpt(LineReader.Option.HISTORY_INCREMENTAL);

int cmdsPerThread = 3;
int nbThreads = 3;

DefaultHistory history = new DefaultHistory(reader);
IntStream.range(0, cmdsPerThread)
.forEach(i -> history.add("cmd" + i));
history.save();

List<String> lines = Files.readAllLines(Paths.get("test"));
assertEquals(cmdsPerThread, lines.size());

final CyclicBarrier barrier = new CyclicBarrier(nbThreads);
List<Thread> ts = IntStream.range(0, nbThreads)
.mapToObj(i -> new Thread(() -> {
doTestFileHistory(cmdsPerThread, barrier);
}))
.collect(toList());
ts.forEach(Thread::start);
for (Thread t : ts) {
t.join();
}

List<String> lines = Files.readAllLines(Paths.get("test"));
assertEquals(3 * 4, lines.size());
lines = Files.readAllLines(Paths.get("test"));
assertEquals(cmdsPerThread * (nbThreads + 1), lines.size());
}
}

0 comments on commit dbf7363

Please sign in to comment.