github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/sink/observer/observer_test.go (about)

     1  // Copyright 2023 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 observer
    15  
    16  import (
    17  	"database/sql"
    18  	"testing"
    19  
    20  	"github.com/DATA-DOG/go-sqlmock"
    21  	dmysql "github.com/go-sql-driver/mysql"
    22  	"github.com/pingcap/tiflow/cdc/model"
    23  	"github.com/pingcap/tiflow/pkg/config"
    24  	pmysql "github.com/pingcap/tiflow/pkg/sink/mysql"
    25  	"github.com/stretchr/testify/require"
    26  	"golang.org/x/net/context"
    27  )
    28  
    29  func newTestMockDB(t *testing.T) (db *sql.DB, mock sqlmock.Sqlmock) {
    30  	db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
    31  	mock.ExpectQuery("select tidb_version()").WillReturnError(&dmysql.MySQLError{
    32  		Number:  1305,
    33  		Message: "FUNCTION test.tidb_version does not exist",
    34  	})
    35  	require.Nil(t, err)
    36  	return
    37  }
    38  
    39  func TestNewObserver(t *testing.T) {
    40  	t.Parallel()
    41  
    42  	dbIndex := 0
    43  	mockGetDBConn := func(ctx context.Context, dsnStr string) (*sql.DB, error) {
    44  		defer func() { dbIndex++ }()
    45  
    46  		if dbIndex == 0 {
    47  			// test db
    48  			db, err := pmysql.MockTestDB()
    49  			require.Nil(t, err)
    50  			return db, nil
    51  		}
    52  
    53  		// normal db
    54  		db, mock := newTestMockDB(t)
    55  		mock.ExpectBegin()
    56  		mock.ExpectClose()
    57  		return db, nil
    58  	}
    59  
    60  	ctx := context.Background()
    61  	sinkURI := "mysql://127.0.0.1:21347/"
    62  	obs, err := NewObserver(ctx, model.DefaultChangeFeedID("test"),
    63  		sinkURI, config.GetDefaultReplicaConfig(),
    64  		WithDBConnFactory(mockGetDBConn))
    65  	require.NoError(t, err)
    66  	for i := 0; i < 10; i++ {
    67  		err = obs.Tick(ctx)
    68  		require.NoError(t, err)
    69  	}
    70  	err = obs.Close()
    71  	require.NoError(t, err)
    72  }