github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/fsutil/fileutil_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 fsutil
    15  
    16  import (
    17  	"os"
    18  	"os/user"
    19  	"path/filepath"
    20  	"runtime"
    21  	"testing"
    22  
    23  	"github.com/stretchr/testify/require"
    24  )
    25  
    26  func TestIsDirWritable(t *testing.T) {
    27  	t.Parallel()
    28  	dir := t.TempDir()
    29  	err := IsDirWritable(dir)
    30  	require.Nil(t, err)
    31  
    32  	err = os.Chmod(dir, 0o400)
    33  	require.Nil(t, err)
    34  	me, err := user.Current()
    35  	require.Nil(t, err)
    36  	if me.Name == "root" || runtime.GOOS == "windows" {
    37  		// chmod is not supported under windows.
    38  		t.Skip("test case is running as a superuser or in windows")
    39  	}
    40  	err = IsDirWritable(dir)
    41  	require.Regexp(t, ".*permission denied", err)
    42  }
    43  
    44  func TestIsDirAndWritable(t *testing.T) {
    45  	t.Parallel()
    46  	dir := t.TempDir()
    47  	path := filepath.Join(dir, "file.test")
    48  
    49  	err := IsDirAndWritable(path)
    50  	require.Regexp(t, ".*no such file or directory", err)
    51  
    52  	err = os.WriteFile(path, nil, 0o600)
    53  	require.Nil(t, err)
    54  	err = IsDirAndWritable(path)
    55  	require.Regexp(t, ".*is not a directory", err)
    56  
    57  	err = IsDirAndWritable(dir)
    58  	require.Nil(t, err)
    59  }
    60  
    61  func TestIsDirReadWritable(t *testing.T) {
    62  	t.Parallel()
    63  
    64  	dir := t.TempDir()
    65  	err := IsDirReadWritable(dir)
    66  	require.Nil(t, err)
    67  
    68  	path := filepath.Join(dir, "/foo")
    69  	err = IsDirReadWritable(path)
    70  	require.Regexp(t, ".*no such file or directory", err)
    71  }
    72  
    73  func TestGetDiskInfo(t *testing.T) {
    74  	t.Parallel()
    75  
    76  	dir := t.TempDir()
    77  	info, err := GetDiskInfo(dir)
    78  	require.Nil(t, err)
    79  	require.NotNil(t, info)
    80  
    81  	dir = filepath.Join(dir, "/tmp/sorter")
    82  	info, err = GetDiskInfo(dir)
    83  	require.Nil(t, info)
    84  	require.Regexp(t, ".*no such file or directory", err)
    85  }