github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/cdc/owner/barrier_test.go (about)

     1  // Copyright 2021 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package owner
    15  
    16  import (
    17  	"math"
    18  	"math/rand"
    19  	"testing"
    20  
    21  	"github.com/pingcap/tiflow/cdc/model"
    22  	"github.com/stretchr/testify/require"
    23  )
    24  
    25  func TestBarrier(t *testing.T) {
    26  	b := newBarriers()
    27  	b.Update(syncPointBarrier, 3)
    28  	b.Update(finishBarrier, 1)
    29  	tp, ts := b.Min()
    30  	require.Equal(t, tp, finishBarrier)
    31  	require.Equal(t, ts, uint64(1))
    32  
    33  	b.Update(finishBarrier, 4)
    34  
    35  	tp, ts = b.Min()
    36  	require.Equal(t, tp, syncPointBarrier)
    37  	require.Equal(t, ts, uint64(3))
    38  
    39  	b.Update(finishBarrier, 1)
    40  	tp, ts = b.Min()
    41  	require.Equal(t, tp, finishBarrier)
    42  	require.Equal(t, ts, uint64(1))
    43  
    44  	tp, ts = b.Min()
    45  	require.Equal(t, tp, finishBarrier)
    46  	require.Equal(t, ts, uint64(1))
    47  }
    48  
    49  func TestBarrierRandom(t *testing.T) {
    50  	maxBarrierType := 50
    51  	maxBarrierTs := 1000000
    52  	b := newBarriers()
    53  	expectedBarriers := make(map[barrierType]model.Ts)
    54  
    55  	// set a barrier which can not be removed to avoid the barrier map is empty
    56  	b.Update(barrierType(maxBarrierType), model.Ts(maxBarrierTs))
    57  	expectedBarriers[barrierType(maxBarrierType)] = model.Ts(maxBarrierTs)
    58  
    59  	for i := 0; i < 100000; i++ {
    60  		switch rand.Intn(2) {
    61  		case 0:
    62  			tp := barrierType(rand.Intn(maxBarrierType))
    63  			ts := model.Ts(rand.Intn(maxBarrierTs))
    64  			b.Update(tp, ts)
    65  			expectedBarriers[tp] = ts
    66  		case 1:
    67  			tp := barrierType(rand.Intn(maxBarrierType))
    68  			b.Remove(tp)
    69  			delete(expectedBarriers, tp)
    70  		}
    71  		expectedMinTs := uint64(math.MaxUint64)
    72  		for _, ts := range expectedBarriers {
    73  			if ts < expectedMinTs {
    74  				expectedMinTs = ts
    75  			}
    76  		}
    77  		tp, ts := b.Min()
    78  		require.Equal(t, ts, expectedMinTs)
    79  		require.Equal(t, expectedBarriers[tp], expectedMinTs)
    80  	}
    81  }