github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/kv/kvserver/stateloader/initial_test.go (about) 1 // Copyright 2016 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package stateloader 12 13 import ( 14 "context" 15 "reflect" 16 "testing" 17 18 "github.com/cockroachdb/cockroach/pkg/roachpb" 19 "github.com/cockroachdb/cockroach/pkg/storage" 20 "github.com/cockroachdb/cockroach/pkg/testutils" 21 "github.com/cockroachdb/cockroach/pkg/util/leaktest" 22 "github.com/cockroachdb/cockroach/pkg/util/stop" 23 "go.etcd.io/etcd/raft/raftpb" 24 ) 25 26 func TestSynthesizeHardState(t *testing.T) { 27 defer leaktest.AfterTest(t)() 28 stopper := stop.NewStopper() 29 defer stopper.Stop(context.Background()) 30 eng := storage.NewDefaultInMem() 31 stopper.AddCloser(eng) 32 33 tHS := raftpb.HardState{Term: 2, Vote: 3, Commit: 4} 34 35 testCases := []struct { 36 TruncTerm, RaftAppliedIndex uint64 37 OldHS *raftpb.HardState 38 NewHS raftpb.HardState 39 Err string 40 }{ 41 {OldHS: nil, TruncTerm: 42, RaftAppliedIndex: 24, NewHS: raftpb.HardState{Term: 42, Vote: 0, Commit: 24}}, 42 // Can't wind back the committed index of the new HardState. 43 {OldHS: &tHS, RaftAppliedIndex: tHS.Commit - 1, Err: "can't decrease HardState.Commit"}, 44 {OldHS: &tHS, RaftAppliedIndex: tHS.Commit, NewHS: tHS}, 45 {OldHS: &tHS, RaftAppliedIndex: tHS.Commit + 1, NewHS: raftpb.HardState{Term: tHS.Term, Vote: 3, Commit: tHS.Commit + 1}}, 46 // Higher Term is picked up, but vote isn't carried over when the term 47 // changes. 48 {OldHS: &tHS, RaftAppliedIndex: tHS.Commit, TruncTerm: 11, NewHS: raftpb.HardState{Term: 11, Vote: 0, Commit: tHS.Commit}}, 49 } 50 51 for i, test := range testCases { 52 func() { 53 batch := eng.NewBatch() 54 defer batch.Close() 55 rsl := Make(roachpb.RangeID(1)) 56 57 if test.OldHS != nil { 58 if err := rsl.SetHardState(context.Background(), batch, *test.OldHS); err != nil { 59 t.Fatal(err) 60 } 61 } 62 63 oldHS, err := rsl.LoadHardState(context.Background(), batch) 64 if err != nil { 65 t.Fatal(err) 66 } 67 68 err = rsl.SynthesizeHardState( 69 context.Background(), batch, oldHS, roachpb.RaftTruncatedState{Term: test.TruncTerm}, test.RaftAppliedIndex, 70 ) 71 if !testutils.IsError(err, test.Err) { 72 t.Fatalf("%d: expected %q got %v", i, test.Err, err) 73 } else if err != nil { 74 // No further checking if we expected an error and got it. 75 return 76 } 77 78 hs, err := rsl.LoadHardState(context.Background(), batch) 79 if err != nil { 80 t.Fatal(err) 81 } 82 if !reflect.DeepEqual(hs, test.NewHS) { 83 t.Fatalf("%d: expected %+v, got %+v", i, &test.NewHS, &hs) 84 } 85 }() 86 } 87 }