github.com/Redstoneguy129/cli@v0.0.0-20230211220159-15dca4e91917/internal/utils/misc_test.go (about)

     1  package utils
     2  
     3  import (
     4  	"io/fs"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  	"testing"
     9  
    10  	"github.com/spf13/afero"
    11  	"github.com/stretchr/testify/assert"
    12  	"github.com/stretchr/testify/require"
    13  )
    14  
    15  type MockFs struct {
    16  	afero.MemMapFs
    17  	DenyPath string
    18  }
    19  
    20  func (m *MockFs) Stat(name string) (fs.FileInfo, error) {
    21  	if strings.HasPrefix(name, m.DenyPath) {
    22  		return nil, fs.ErrPermission
    23  	}
    24  	return m.MemMapFs.Stat(name)
    25  }
    26  
    27  func TestProjectRoot(t *testing.T) {
    28  	t.Run("searches project root recursively", func(t *testing.T) {
    29  		// Setup in-memory fs
    30  		fsys := afero.NewMemMapFs()
    31  		_, err := fsys.Create(filepath.Join("/", ConfigPath))
    32  		require.NoError(t, err)
    33  		// Run test
    34  		path, err := GetProjectRoot(fsys)
    35  		// Check error
    36  		assert.NoError(t, err)
    37  		assert.Equal(t, "/", path)
    38  	})
    39  
    40  	t.Run("stops at root dir", func(t *testing.T) {
    41  		cwd, err := os.Getwd()
    42  		require.NoError(t, err)
    43  		// Setup in-memory fs
    44  		fsys := afero.NewMemMapFs()
    45  		// Run test
    46  		path, err := GetProjectRoot(fsys)
    47  		// Check error
    48  		assert.NoError(t, err)
    49  		assert.Equal(t, cwd, path)
    50  	})
    51  
    52  	t.Run("ignores error if path is not directory", func(t *testing.T) {
    53  		cwd, err := os.Getwd()
    54  		require.NoError(t, err)
    55  		// Setup in-memory fs
    56  		fsys := &MockFs{DenyPath: filepath.Join(cwd, "supabase")}
    57  		// Run test
    58  		path, err := GetProjectRoot(fsys)
    59  		// Check error
    60  		assert.NoError(t, err)
    61  		assert.Equal(t, cwd, path)
    62  	})
    63  }