github.com/pingcap/ticdc@v0.0.0-20220526033649-485a10ef2652/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/pingcap/check"
    24  	"github.com/pingcap/ticdc/pkg/util/testleak"
    25  )
    26  
    27  func Test(t *testing.T) {
    28  	check.TestingT(t)
    29  }
    30  
    31  type testHelperSuite struct{}
    32  
    33  var _ = check.Suite(&testHelperSuite{})
    34  
    35  func (s *testHelperSuite) TestWaitSomething(c *check.C) {
    36  	defer testleak.AfterTest(c)()
    37  	var (
    38  		backoff  = 10
    39  		waitTime = 10 * time.Millisecond
    40  		count    = 0
    41  	)
    42  
    43  	// wait fail
    44  	f1 := func() bool {
    45  		count++
    46  		return false
    47  	}
    48  	c.Assert(WaitSomething(backoff, waitTime, f1), check.IsFalse)
    49  	c.Assert(count, check.Equals, backoff)
    50  
    51  	count = 0 // reset
    52  	// wait success
    53  	f2 := func() bool {
    54  		count++
    55  		return count >= 5
    56  	}
    57  
    58  	c.Assert(WaitSomething(backoff, waitTime, f2), check.IsTrue)
    59  	c.Assert(count, check.Equals, 5)
    60  }
    61  
    62  func (s *testHelperSuite) TestHandleErr(c *check.C) {
    63  	defer testleak.AfterTest(c)()
    64  	var (
    65  		ctx, cancel = context.WithCancel(context.Background())
    66  		errCh       = make(chan error)
    67  		count       int32
    68  	)
    69  	errg := HandleErrWithErrGroup(ctx, errCh, func(e error) { atomic.AddInt32(&count, 1) })
    70  	for i := 0; i < 5; i++ {
    71  		errCh <- errors.New("test error")
    72  	}
    73  	c.Assert(WaitSomething(5, time.Millisecond*10, func() bool { return atomic.LoadInt32(&count) == int32(5) }), check.IsTrue)
    74  	cancel()
    75  	c.Assert(errg.Wait(), check.IsNil)
    76  }