github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/util/test_helper.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  	"time"
    19  
    20  	"golang.org/x/sync/errgroup"
    21  )
    22  
    23  // WaitSomething waits for something done with `true`, it retrys for nRetry times at most
    24  func WaitSomething(nRetry int, waitTime time.Duration, fn func() bool) bool {
    25  	for i := 0; i < nRetry-1; i++ {
    26  		if fn() {
    27  			return true
    28  		}
    29  
    30  		time.Sleep(waitTime)
    31  	}
    32  	return fn()
    33  }
    34  
    35  // HandleErr receives error from an error channel, until the context is Done
    36  func HandleErr(ctx context.Context, errCh <-chan error, errFn func(error)) {
    37  	for {
    38  		select {
    39  		case <-ctx.Done():
    40  			return
    41  		case err := <-errCh:
    42  			errFn(err)
    43  		}
    44  	}
    45  }
    46  
    47  // HandleErrWithErrGroup creates a `errgroup.Group` and calls `HandleErr` within the error group
    48  func HandleErrWithErrGroup(ctx context.Context, errCh <-chan error, errFn func(error)) *errgroup.Group {
    49  	errg, cctx := errgroup.WithContext(ctx)
    50  	errg.Go(func() error {
    51  		HandleErr(cctx, errCh, errFn)
    52  		return nil
    53  	})
    54  	return errg
    55  }
    56  
    57  // Must panics if err is not nil.
    58  func Must[T any](v T, err error) T {
    59  	if err != nil {
    60  		panic(err)
    61  	}
    62  	return v
    63  }