github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/cli/command/utils_test.go (about) 1 package command 2 3 import ( 4 "os" 5 "path/filepath" 6 "testing" 7 8 "github.com/pkg/errors" 9 "gotest.tools/v3/assert" 10 ) 11 12 func TestStringSliceReplaceAt(t *testing.T) { 13 out, ok := StringSliceReplaceAt([]string{"abc", "foo", "bar", "bax"}, []string{"foo", "bar"}, []string{"baz"}, -1) 14 assert.Assert(t, ok) 15 assert.DeepEqual(t, []string{"abc", "baz", "bax"}, out) 16 17 out, ok = StringSliceReplaceAt([]string{"foo"}, []string{"foo", "bar"}, []string{"baz"}, -1) 18 assert.Assert(t, !ok) 19 assert.DeepEqual(t, []string{"foo"}, out) 20 21 out, ok = StringSliceReplaceAt([]string{"abc", "foo", "bar", "bax"}, []string{"foo", "bar"}, []string{"baz"}, 0) 22 assert.Assert(t, !ok) 23 assert.DeepEqual(t, []string{"abc", "foo", "bar", "bax"}, out) 24 25 out, ok = StringSliceReplaceAt([]string{"foo", "bar", "bax"}, []string{"foo", "bar"}, []string{"baz"}, 0) 26 assert.Assert(t, ok) 27 assert.DeepEqual(t, []string{"baz", "bax"}, out) 28 29 out, ok = StringSliceReplaceAt([]string{"abc", "foo", "bar", "baz"}, []string{"foo", "bar"}, nil, -1) 30 assert.Assert(t, ok) 31 assert.DeepEqual(t, []string{"abc", "baz"}, out) 32 33 out, ok = StringSliceReplaceAt([]string{"foo"}, nil, []string{"baz"}, -1) 34 assert.Assert(t, !ok) 35 assert.DeepEqual(t, []string{"foo"}, out) 36 } 37 38 func TestValidateOutputPath(t *testing.T) { 39 basedir := t.TempDir() 40 dir := filepath.Join(basedir, "dir") 41 notexist := filepath.Join(basedir, "notexist") 42 err := os.MkdirAll(dir, 0o755) 43 assert.NilError(t, err) 44 file := filepath.Join(dir, "file") 45 err = os.WriteFile(file, []byte("hi"), 0o644) 46 assert.NilError(t, err) 47 testcases := []struct { 48 path string 49 err error 50 }{ 51 {basedir, nil}, 52 {file, nil}, 53 {dir, nil}, 54 {dir + string(os.PathSeparator), nil}, 55 {notexist, nil}, 56 {notexist + string(os.PathSeparator), nil}, 57 {filepath.Join(notexist, "file"), errors.New("does not exist")}, 58 } 59 60 for _, testcase := range testcases { 61 t.Run(testcase.path, func(t *testing.T) { 62 err := ValidateOutputPath(testcase.path) 63 if testcase.err == nil { 64 assert.NilError(t, err) 65 } else { 66 assert.ErrorContains(t, err, testcase.err.Error()) 67 } 68 }) 69 } 70 }