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

     1  // Copyright 2020 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 util
    15  
    16  import (
    17  	"context"
    18  	"errors"
    19  	"sync/atomic"
    20  	"testing"
    21  	"time"
    22  
    23  	"github.com/stretchr/testify/require"
    24  )
    25  
    26  func TestWaitSomething(t *testing.T) {
    27  	var (
    28  		backoff  = 10
    29  		waitTime = 10 * time.Millisecond
    30  		count    = 0
    31  	)
    32  
    33  	// wait fail
    34  	f1 := func() bool {
    35  		count++
    36  		return false
    37  	}
    38  	require.False(t, WaitSomething(backoff, waitTime, f1))
    39  	require.Equal(t, backoff, count)
    40  
    41  	count = 0 // reset
    42  	// wait success
    43  	f2 := func() bool {
    44  		count++
    45  		return count >= 5
    46  	}
    47  	require.True(t, WaitSomething(backoff, waitTime, f2))
    48  	require.Equal(t, 5, count)
    49  }
    50  
    51  func TestHandleErr(t *testing.T) {
    52  	var (
    53  		ctx, cancel = context.WithCancel(context.Background())
    54  		errCh       = make(chan error)
    55  		count       int32
    56  	)
    57  	errg := HandleErrWithErrGroup(ctx, errCh, func(e error) { atomic.AddInt32(&count, 1) })
    58  	for i := 0; i < 5; i++ {
    59  		errCh <- errors.New("test error")
    60  	}
    61  	require.True(t, WaitSomething(5, time.Millisecond*10, func() bool { return atomic.LoadInt32(&count) == int32(5) }))
    62  	cancel()
    63  	require.Nil(t, errg.Wait())
    64  }