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

     1  // Copyright 2022 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 chdelay
    15  
    16  import (
    17  	"sync"
    18  	"testing"
    19  	"time"
    20  
    21  	"github.com/stretchr/testify/require"
    22  )
    23  
    24  func TestChannelDelayerShortDelay(t *testing.T) {
    25  	t.Parallel()
    26  
    27  	testChannelDelayer(t, time.Millisecond*100, 10000)
    28  }
    29  
    30  func TestChannelDelayerLongDelay(t *testing.T) {
    31  	t.Parallel()
    32  
    33  	testChannelDelayer(t, time.Second*2, 100)
    34  }
    35  
    36  func testChannelDelayer(t *testing.T, delayBy time.Duration, count int) {
    37  	inCh := make(chan time.Time, 16)
    38  	delayer := NewChannelDelayer(delayBy, inCh, 1024, 16)
    39  
    40  	var wg sync.WaitGroup
    41  	wg.Add(1)
    42  	go func() {
    43  		defer wg.Done()
    44  		defer close(inCh)
    45  
    46  		for i := 0; i < count; i++ {
    47  			inCh <- time.Now()
    48  		}
    49  	}()
    50  
    51  	wg.Add(1)
    52  	go func() {
    53  		defer wg.Done()
    54  
    55  		counter := 0
    56  		for ts := range delayer.Out() {
    57  			require.Greater(t, time.Since(ts), delayBy)
    58  			counter++
    59  		}
    60  
    61  		require.Equal(t, count, counter)
    62  	}()
    63  
    64  	wg.Wait()
    65  	delayer.Close()
    66  }