Import atomix/{storage,utils}
[controller.git] / third-party / atomix / storage / src / test / java / io / atomix / storage / journal / PersistentJournalTest.java
1 /*
2  * Copyright 2017-present Open Networking Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package io.atomix.storage.journal;
17
18 import org.junit.Test;
19
20 import static org.junit.Assert.assertEquals;
21 import static org.junit.Assert.assertTrue;
22
23 /**
24  * Persistent journal test base.
25  */
26 public abstract class PersistentJournalTest extends AbstractJournalTest {
27   protected PersistentJournalTest(int maxSegmentSize, int cacheSize) {
28     super(maxSegmentSize, cacheSize);
29   }
30
31   /**
32    * Tests reading from a compacted journal.
33    */
34   @Test
35   public void testCompactAndRecover() throws Exception {
36     SegmentedJournal<TestEntry> journal = createJournal();
37
38     // Write three segments to the journal.
39     JournalWriter<TestEntry> writer = journal.writer();
40     for (int i = 0; i < entriesPerSegment * 3; i++) {
41       writer.append(ENTRY);
42     }
43
44     // Commit the entries and compact the first segment.
45     writer.commit(entriesPerSegment * 3);
46     journal.compact(entriesPerSegment + 1);
47
48     // Close the journal.
49     journal.close();
50
51     // Reopen the journal and create a reader.
52     journal = createJournal();
53     writer = journal.writer();
54     JournalReader<TestEntry> reader = journal.openReader(1, JournalReader.Mode.COMMITS);
55     writer.append(ENTRY);
56     writer.append(ENTRY);
57     writer.commit(entriesPerSegment * 3);
58
59     // Ensure the reader starts at the first physical index in the journal.
60     assertEquals(entriesPerSegment + 1, reader.getNextIndex());
61     assertEquals(reader.getFirstIndex(), reader.getNextIndex());
62     assertTrue(reader.hasNext());
63     assertEquals(entriesPerSegment + 1, reader.getNextIndex());
64     assertEquals(reader.getFirstIndex(), reader.getNextIndex());
65     assertEquals(entriesPerSegment + 1, reader.next().index());
66   }
67 }