github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/kv/kvserver/replica_init_test.go (about)

     1  // Copyright 2019 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 kvserver
    12  
    13  import (
    14  	"context"
    15  	"testing"
    16  
    17  	"github.com/cockroachdb/cockroach/pkg/roachpb"
    18  	"github.com/cockroachdb/cockroach/pkg/util/leaktest"
    19  	"github.com/cockroachdb/cockroach/pkg/util/stop"
    20  )
    21  
    22  func TestReplicaUpdateLastReplicaAdded(t *testing.T) {
    23  	defer leaktest.AfterTest(t)()
    24  
    25  	desc := func(replicaIDs ...roachpb.ReplicaID) roachpb.RangeDescriptor {
    26  		d := roachpb.RangeDescriptor{
    27  			StartKey:         roachpb.RKey("a"),
    28  			EndKey:           roachpb.RKey("b"),
    29  			InternalReplicas: make([]roachpb.ReplicaDescriptor, len(replicaIDs)),
    30  		}
    31  		for i, id := range replicaIDs {
    32  			d.InternalReplicas[i].ReplicaID = id
    33  		}
    34  		return d
    35  	}
    36  
    37  	testCases := []struct {
    38  		oldDesc                  roachpb.RangeDescriptor
    39  		newDesc                  roachpb.RangeDescriptor
    40  		lastReplicaAdded         roachpb.ReplicaID
    41  		expectedLastReplicaAdded roachpb.ReplicaID
    42  	}{
    43  		// Adding a replica. In normal operation, Replica IDs always increase.
    44  		{desc(), desc(1), 0, 1},
    45  		{desc(1), desc(1, 2), 0, 2},
    46  		{desc(1, 2), desc(1, 2, 3), 0, 3},
    47  		// Add a replica with an out-of-order ID (this shouldn't happen in practice).
    48  		{desc(2, 3), desc(1, 2, 3), 0, 0},
    49  		// Removing a replica has no-effect.
    50  		{desc(1, 2, 3), desc(2, 3), 3, 3},
    51  		{desc(1, 2, 3), desc(1, 3), 3, 3},
    52  		{desc(1, 2, 3), desc(1, 2), 3, 0},
    53  	}
    54  
    55  	tc := testContext{}
    56  	stopper := stop.NewStopper()
    57  	ctx := context.Background()
    58  	defer stopper.Stop(ctx)
    59  	tc.Start(t, stopper)
    60  	for _, c := range testCases {
    61  		t.Run("", func(t *testing.T) {
    62  			var r Replica
    63  			r.mu.state.Desc = &c.oldDesc
    64  			r.mu.lastReplicaAdded = c.lastReplicaAdded
    65  			r.store = tc.store
    66  			r.concMgr = tc.repl.concMgr
    67  			r.setDescRaftMuLocked(context.Background(), &c.newDesc)
    68  			if c.expectedLastReplicaAdded != r.mu.lastReplicaAdded {
    69  				t.Fatalf("expected %d, but found %d",
    70  					c.expectedLastReplicaAdded, r.mu.lastReplicaAdded)
    71  			}
    72  		})
    73  	}
    74  }