github.com/rliebz/tusk@v0.6.5-0.20240416035353-dd5a98e9a5fb/runner/file_test.go (about)

     1  package runner
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  	"testing"
     7  
     8  	"github.com/rliebz/ghost"
     9  	"github.com/rliebz/ghost/be"
    10  )
    11  
    12  func TestSearchForFile(t *testing.T) {
    13  	tmpdir := useTempDir(t)
    14  
    15  	emptyDir := mkDir(t, tmpdir, "empty")
    16  
    17  	topDir := mkDir(t, tmpdir, "top")
    18  	topConfig := mkConfigFile(t, topDir, "tusk.yml")
    19  
    20  	yamlDir := mkDir(t, tmpdir, "yaml")
    21  	yamlConfig := mkConfigFile(t, yamlDir, "tusk.yaml")
    22  
    23  	nestedDir := mkDir(t, topDir, "foo", "bar")
    24  	nestedConfig := mkConfigFile(t, nestedDir, "tusk.yml")
    25  
    26  	inheritedDir := mkDir(t, topDir, "baz", "empty")
    27  
    28  	tests := []struct {
    29  		wd       string
    30  		wantPath string
    31  	}{
    32  		{
    33  			wd:       emptyDir,
    34  			wantPath: "",
    35  		},
    36  		{
    37  			wd:       topDir,
    38  			wantPath: topConfig,
    39  		},
    40  		{
    41  			wd:       yamlDir,
    42  			wantPath: yamlConfig,
    43  		},
    44  		{
    45  			wd:       nestedDir,
    46  			wantPath: nestedConfig,
    47  		},
    48  		{
    49  			wd:       inheritedDir,
    50  			wantPath: topConfig,
    51  		},
    52  	}
    53  
    54  	for _, tt := range tests {
    55  		t.Run(tt.wd+"_"+tt.wantPath, func(t *testing.T) {
    56  			g := ghost.New(t)
    57  
    58  			err := os.Chdir(tt.wd)
    59  			g.NoError(err)
    60  
    61  			fullPath, err := searchForFile()
    62  			g.NoError(err)
    63  
    64  			g.Should(be.Equal(fullPath, tt.wantPath))
    65  		})
    66  	}
    67  }
    68  
    69  func useTempDir(t *testing.T) string {
    70  	t.Helper()
    71  
    72  	g := ghost.New(t)
    73  
    74  	// MacOS gets fancy with symlinks, so this gets us the real working path.
    75  	tmpdir, err := filepath.EvalSymlinks(t.TempDir())
    76  	g.NoError(err)
    77  
    78  	oldwd, err := os.Getwd()
    79  	g.NoError(err)
    80  
    81  	err = os.Chdir(tmpdir)
    82  	g.NoError(err)
    83  
    84  	t.Cleanup(func() {
    85  		err := os.Chdir(oldwd)
    86  		g.Should(be.Nil(err))
    87  	})
    88  
    89  	return tmpdir
    90  }
    91  
    92  func mkDir(t *testing.T, elem ...string) string {
    93  	t.Helper()
    94  
    95  	g := ghost.New(t)
    96  
    97  	fullPath := filepath.Join(elem...)
    98  	err := os.MkdirAll(fullPath, 0o700)
    99  	g.NoError(err)
   100  
   101  	return fullPath
   102  }
   103  
   104  func mkConfigFile(t *testing.T, dir, fileName string) string {
   105  	t.Helper()
   106  
   107  	g := ghost.New(t)
   108  
   109  	fullPath := filepath.Join(dir, fileName)
   110  	err := os.WriteFile(fullPath, []byte{}, 0o600)
   111  	g.NoError(err)
   112  
   113  	return fullPath
   114  }