vitess.io/vitess@v0.16.2/go/test/endtoend/onlineddl/exec_util.go (about)

     1  /*
     2  Copyright 2021 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package onlineddl
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"os/exec"
    23  	"path"
    24  	"path/filepath"
    25  	"testing"
    26  
    27  	"github.com/stretchr/testify/require"
    28  
    29  	"vitess.io/vitess/go/mysql"
    30  )
    31  
    32  // CreateTempScript creates a script in the temporary directory with given content
    33  func CreateTempScript(t *testing.T, content string) (fileName string) {
    34  	f, err := os.CreateTemp("", "onlineddl-test-")
    35  	require.NoError(t, err)
    36  
    37  	_, err = f.WriteString(content)
    38  	require.NoError(t, err)
    39  	err = f.Close()
    40  	require.NoError(t, err)
    41  
    42  	return f.Name()
    43  }
    44  
    45  // MysqlClientExecFile runs a file through the mysql client
    46  func MysqlClientExecFile(t *testing.T, mysqlParams *mysql.ConnParams, testDataPath, testName string, fileName string) (output string) {
    47  	t.Helper()
    48  
    49  	bashPath, err := exec.LookPath("bash")
    50  	require.NoError(t, err)
    51  	mysqlPath, err := exec.LookPath("mysql")
    52  	require.NoError(t, err)
    53  
    54  	filePath := fileName
    55  	if !filepath.IsAbs(fileName) {
    56  		filePath, _ = filepath.Abs(path.Join(testDataPath, testName, fileName))
    57  	}
    58  	bashCommand := fmt.Sprintf(`%s -u%s --socket=%s --database=%s -s -s < %s 2> /tmp/error.log`, mysqlPath, mysqlParams.Uname, mysqlParams.UnixSocket, mysqlParams.DbName, filePath)
    59  	cmd, err := exec.Command(
    60  		bashPath,
    61  		"-c",
    62  		bashCommand,
    63  	).Output()
    64  
    65  	require.NoError(t, err)
    66  	return string(cmd)
    67  }