github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/etcd/testing.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 etcd
    15  
    16  import (
    17  	"context"
    18  	"net/url"
    19  	"testing"
    20  	"time"
    21  
    22  	"github.com/pingcap/tiflow/pkg/util"
    23  	"github.com/stretchr/testify/require"
    24  	"go.etcd.io/etcd/client/pkg/v3/logutil"
    25  	clientv3 "go.etcd.io/etcd/client/v3"
    26  	"go.etcd.io/etcd/server/v3/embed"
    27  	"go.uber.org/zap"
    28  	"go.uber.org/zap/zapcore"
    29  	"golang.org/x/sync/errgroup"
    30  )
    31  
    32  // Tester is for ut tests
    33  type Tester struct {
    34  	dir       string
    35  	etcd      *embed.Etcd
    36  	ClientURL *url.URL
    37  	client    *CDCEtcdClientImpl
    38  	ctx       context.Context
    39  	cancel    context.CancelFunc
    40  	errg      *errgroup.Group
    41  }
    42  
    43  // SetUpTest setup etcd tester
    44  func (s *Tester) SetUpTest(t *testing.T) {
    45  	var err error
    46  	s.dir = t.TempDir()
    47  	s.ClientURL, s.etcd, err = SetupEmbedEtcd(s.dir)
    48  	require.Nil(t, err)
    49  	logConfig := logutil.DefaultZapLoggerConfig
    50  	logConfig.Level = zap.NewAtomicLevelAt(zapcore.ErrorLevel)
    51  	client, err := clientv3.New(clientv3.Config{
    52  		Endpoints:   []string{s.ClientURL.String()},
    53  		DialTimeout: 3 * time.Second,
    54  		LogConfig:   &logConfig,
    55  	})
    56  	require.NoError(t, err)
    57  
    58  	s.client, err = NewCDCEtcdClient(context.TODO(), client, DefaultCDCClusterID)
    59  	require.Nil(t, err)
    60  	s.ctx, s.cancel = context.WithCancel(context.Background())
    61  	s.errg = util.HandleErrWithErrGroup(s.ctx, s.etcd.Err(), func(e error) { t.Log(e) })
    62  }
    63  
    64  // TearDownTest teardown etcd
    65  func (s *Tester) TearDownTest(t *testing.T) {
    66  	s.etcd.Close()
    67  	s.cancel()
    68  logEtcdError:
    69  	for {
    70  		select {
    71  		case err, ok := <-s.etcd.Err():
    72  			if !ok {
    73  				break logEtcdError
    74  			}
    75  			t.Logf("etcd server error: %v", err)
    76  		default:
    77  			break logEtcdError
    78  		}
    79  	}
    80  	_ = s.client.Close() //nolint:errcheck
    81  }