2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.raft;
10 import static org.junit.Assert.assertArrayEquals;
11 import static org.junit.Assert.assertEquals;
12 import java.io.FileInputStream;
13 import java.io.FileOutputStream;
14 import java.io.IOException;
15 import java.io.ObjectInputStream;
16 import java.io.ObjectOutputStream;
17 import java.util.ArrayList;
18 import java.util.List;
19 import org.junit.Test;
20 import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
23 * Unit tests for Snapshot.
25 * @author Thomas Pantelis
27 public class SnapshotTest {
30 public void testBackwardsCompatibleDeserializationFromLithium() throws Exception {
31 Snapshot expSnapshot = newLithiumSnapshot();
32 try(FileInputStream fis = new FileInputStream("src/test/resources/lithium-serialized-Snapshot")) {
33 ObjectInputStream ois = new ObjectInputStream(fis);
35 Snapshot snapshot = (Snapshot) ois.readObject();
38 assertEquals("lastIndex", expSnapshot.getLastIndex(), snapshot.getLastIndex());
39 assertEquals("lastTerm", expSnapshot.getLastTerm(), snapshot.getLastTerm());
40 assertEquals("lastAppliedIndex", expSnapshot.getLastAppliedIndex(), snapshot.getLastAppliedIndex());
41 assertEquals("lastAppliedTerm", expSnapshot.getLastAppliedTerm(), snapshot.getLastAppliedTerm());
42 assertEquals("unAppliedEntries size", expSnapshot.getUnAppliedEntries().size(), snapshot.getUnAppliedEntries().size());
43 assertArrayEquals("state", expSnapshot.getState(), snapshot.getState());
44 assertEquals("electionTerm", 0, snapshot.getElectionTerm());
45 assertEquals("electionVotedFor", null, snapshot.getElectionVotedFor());
49 private static Snapshot newLithiumSnapshot() {
50 byte[] state = {1, 2, 3, 4, 5};
51 List<ReplicatedLogEntry> entries = new ArrayList<>();
52 entries.add(new ReplicatedLogImplEntry(6, 2, new MockPayload("payload")));
55 long lastAppliedIndex = 5;
56 long lastAppliedTerm = 1;
58 return Snapshot.create(state, entries, lastIndex, lastTerm, lastAppliedIndex, lastAppliedTerm);
62 * Use this method to generate a file with a serialized Snapshot instance to be
63 * used in tests that verify backwards compatible de-serialization.
65 private static void generateSerializedFile(Snapshot snapshot, String fileName) throws IOException {
66 FileOutputStream fos = new FileOutputStream("src/test/resources/" + fileName);
67 ObjectOutputStream oos = new ObjectOutputStream(fos);
68 oos.writeObject(snapshot);