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;
13 import java.io.FileInputStream;
14 import java.io.FileOutputStream;
15 import java.io.IOException;
16 import java.io.ObjectInputStream;
17 import java.io.ObjectOutputStream;
18 import java.util.ArrayList;
19 import java.util.List;
20 import org.junit.Test;
21 import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
24 * Unit tests for Snapshot.
26 * @author Thomas Pantelis
28 public class SnapshotTest {
31 public void testBackwardsCompatibleDeserializationFromLithium() throws Exception {
32 Snapshot expSnapshot = newLithiumSnapshot();
33 try (FileInputStream fis = new FileInputStream("src/test/resources/lithium-serialized-Snapshot")) {
34 ObjectInputStream ois = new ObjectInputStream(fis);
36 Snapshot snapshot = (Snapshot) ois.readObject();
39 assertEquals("lastIndex", expSnapshot.getLastIndex(), snapshot.getLastIndex());
40 assertEquals("lastTerm", expSnapshot.getLastTerm(), snapshot.getLastTerm());
41 assertEquals("lastAppliedIndex", expSnapshot.getLastAppliedIndex(), snapshot.getLastAppliedIndex());
42 assertEquals("lastAppliedTerm", expSnapshot.getLastAppliedTerm(), snapshot.getLastAppliedTerm());
43 assertEquals("unAppliedEntries size", expSnapshot.getUnAppliedEntries().size(),
44 snapshot.getUnAppliedEntries().size());
45 assertArrayEquals("state", expSnapshot.getState(), snapshot.getState());
46 assertEquals("electionTerm", 0, snapshot.getElectionTerm());
47 assertEquals("electionVotedFor", null, snapshot.getElectionVotedFor());
51 private static Snapshot newLithiumSnapshot() {
52 byte[] state = {1, 2, 3, 4, 5};
53 List<ReplicatedLogEntry> entries = new ArrayList<>();
54 entries.add(new ReplicatedLogImplEntry(6, 2, new MockPayload("payload")));
57 long lastAppliedIndex = 5;
58 long lastAppliedTerm = 1;
60 return Snapshot.create(state, entries, lastIndex, lastTerm, lastAppliedIndex, lastAppliedTerm);
64 * Use this method to generate a file with a serialized Snapshot instance to be
65 * used in tests that verify backwards compatible de-serialization.
67 @SuppressWarnings("unused")
68 private static void generateSerializedFile(Snapshot snapshot, String fileName) throws IOException {
69 FileOutputStream fos = new FileOutputStream("src/test/resources/" + fileName);
70 ObjectOutputStream oos = new ObjectOutputStream(fos);
71 oos.writeObject(snapshot);