github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/causality/txn_cache_test.go (about)

     1  // Copyright 2024 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 causality
    15  
    16  import (
    17  	"testing"
    18  
    19  	"github.com/stretchr/testify/require"
    20  )
    21  
    22  type mockTxnEvent struct{}
    23  
    24  func (m mockTxnEvent) OnConflictResolved() {
    25  }
    26  
    27  func (m mockTxnEvent) ConflictKeys() []uint64 {
    28  	return nil
    29  }
    30  
    31  func TestBoundedWorker(t *testing.T) {
    32  	t.Parallel()
    33  
    34  	size := 100
    35  	// Create a worker with 1 worker and 1 cache size.
    36  	worker := newTxnCache[txnEvent](TxnCacheOption{
    37  		Count:         1,
    38  		Size:          size,
    39  		BlockStrategy: BlockStrategyWaitAvailable,
    40  	})
    41  	for i := 0; i < size; i++ {
    42  		// Add 10 events to the worker.
    43  		ok := worker.add(TxnWithNotifier[txnEvent]{
    44  			TxnEvent:        mockTxnEvent{},
    45  			PostTxnExecuted: func() {},
    46  		})
    47  		require.True(t, ok)
    48  	}
    49  	e := TxnWithNotifier[txnEvent]{
    50  		TxnEvent:        mockTxnEvent{},
    51  		PostTxnExecuted: func() {},
    52  	}
    53  	require.False(t, worker.add(e))
    54  	e = <-worker.out()
    55  	require.NotNil(t, e)
    56  	require.True(t, worker.add(e))
    57  }
    58  
    59  func TestBoundedWorkerWithBlock(t *testing.T) {
    60  	t.Parallel()
    61  
    62  	size := 100
    63  	// Create a worker with 1 worker and 1 cache size.
    64  	worker := newTxnCache[txnEvent](TxnCacheOption{
    65  		Count:         1,
    66  		Size:          size,
    67  		BlockStrategy: BlockStrategyWaitEmpty,
    68  	})
    69  	for i := 0; i < size; i++ {
    70  		// Add 10 events to the worker.
    71  		ok := worker.add(TxnWithNotifier[txnEvent]{
    72  			TxnEvent:        mockTxnEvent{},
    73  			PostTxnExecuted: func() {},
    74  		})
    75  		require.True(t, ok)
    76  	}
    77  	e := TxnWithNotifier[txnEvent]{
    78  		TxnEvent:        mockTxnEvent{},
    79  		PostTxnExecuted: func() {},
    80  	}
    81  	require.False(t, worker.add(e))
    82  	e = <-worker.out()
    83  	require.NotNil(t, e)
    84  	require.False(t, worker.add(e))
    85  }