github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/sink/mysql/mock_db.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 mysql
    15  
    16  import (
    17  	"database/sql"
    18  
    19  	"github.com/DATA-DOG/go-sqlmock"
    20  )
    21  
    22  // MockTestDB creates a mock mysql database connection.
    23  func MockTestDB() (*sql.DB, error) {
    24  	// mock for test db, which is used querying TiDB session variable
    25  	db, mock, err := sqlmock.New()
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  
    30  	columns := []string{"Variable_name", "Value"}
    31  	mock.ExpectQuery("show session variables like 'allow_auto_random_explicit_insert';").WillReturnRows(
    32  		sqlmock.NewRows(columns).AddRow("allow_auto_random_explicit_insert", "0"),
    33  	)
    34  	mock.ExpectQuery("show session variables like 'tidb_txn_mode';").WillReturnRows(
    35  		sqlmock.NewRows(columns).AddRow("tidb_txn_mode", "pessimistic"),
    36  	)
    37  	mock.ExpectQuery("show session variables like 'transaction_isolation';").WillReturnRows(
    38  		sqlmock.NewRows(columns).AddRow("transaction_isolation", "REPEATED-READ"),
    39  	)
    40  	mock.ExpectQuery("show session variables like 'tidb_placement_mode';").
    41  		WillReturnRows(
    42  			sqlmock.NewRows(columns).
    43  				AddRow("tidb_placement_mode", "IGNORE"),
    44  		)
    45  	mock.ExpectQuery("show session variables like 'tidb_enable_external_ts_read';").
    46  		WillReturnRows(
    47  			sqlmock.NewRows(columns).
    48  				AddRow("tidb_enable_external_ts_read", "OFF"),
    49  		)
    50  	mock.ExpectQuery("select character_set_name from information_schema.character_sets " +
    51  		"where character_set_name = 'gbk';").WillReturnRows(
    52  		sqlmock.NewRows([]string{"character_set_name"}).AddRow("gbk"),
    53  	)
    54  	mock.ExpectQuery("select tidb_version()").
    55  		WillReturnRows(sqlmock.NewRows([]string{"tidb_version()"}).AddRow("5.7.25-TiDB-v4.0.0-beta-191-ga1b3e3b"))
    56  	mock.ExpectQuery("select tidb_version()").
    57  		WillReturnRows(sqlmock.NewRows([]string{"tidb_version()"}).AddRow("5.7.25-TiDB-v4.0.0-beta-191-ga1b3e3b"))
    58  	mock.ExpectClose()
    59  	return db, nil
    60  }