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
29 public class SnapshotTest {
32 public void testBackwardsCompatibleDeserializationFromLithium() throws Exception {
33 Snapshot expSnapshot = newLithiumSnapshot();
34 try (FileInputStream fis = new FileInputStream("src/test/resources/lithium-serialized-Snapshot")) {
35 ObjectInputStream ois = new ObjectInputStream(fis);
37 Snapshot snapshot = (Snapshot) ois.readObject();
40 assertEquals("lastIndex", expSnapshot.getLastIndex(), snapshot.getLastIndex());
41 assertEquals("lastTerm", expSnapshot.getLastTerm(), snapshot.getLastTerm());
42 assertEquals("lastAppliedIndex", expSnapshot.getLastAppliedIndex(), snapshot.getLastAppliedIndex());
43 assertEquals("lastAppliedTerm", expSnapshot.getLastAppliedTerm(), snapshot.getLastAppliedTerm());
44 assertEquals("unAppliedEntries size", expSnapshot.getUnAppliedEntries().size(),
45 snapshot.getUnAppliedEntries().size());
46 assertArrayEquals("state", expSnapshot.getState(), snapshot.getState());
47 assertEquals("electionTerm", 0, snapshot.getElectionTerm());
48 assertEquals("electionVotedFor", null, snapshot.getElectionVotedFor());
52 private static Snapshot newLithiumSnapshot() {
53 byte[] state = {1, 2, 3, 4, 5};
54 List<ReplicatedLogEntry> entries = new ArrayList<>();
55 entries.add(new org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry(
56 6, 2, new MockPayload("payload")));
59 long lastAppliedIndex = 5;
60 long lastAppliedTerm = 1;
62 return Snapshot.create(state, entries, lastIndex, lastTerm, lastAppliedIndex, lastAppliedTerm);
66 * Use this method to generate a file with a serialized Snapshot instance to be
67 * used in tests that verify backwards compatible de-serialization.
69 @SuppressWarnings("unused")
70 private static void generateSerializedFile(Snapshot snapshot, String fileName) throws IOException {
71 FileOutputStream fos = new FileOutputStream("src/test/resources/" + fileName);
72 ObjectOutputStream oos = new ObjectOutputStream(fos);
73 oos.writeObject(snapshot);