test: make fish_completions_test more robust (#1980)

Use temporary files instead of assuming the current directory is
writable. Also, if creating a temporary file still returns an error,
prevent the test from failing silently by replacing `log.Fatal` with
`t.Fatal`.
This commit is contained in:
Branch Vincent 2023-06-16 07:25:30 -07:00 committed by GitHub
parent 2246fa82e9
commit 988bd76139
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -16,9 +16,10 @@ package cobra
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"log"
"os" "os"
"path/filepath"
"testing" "testing"
) )
@ -98,12 +99,12 @@ func TestFishCompletionNoActiveHelp(t *testing.T) {
} }
func TestGenFishCompletionFile(t *testing.T) { func TestGenFishCompletionFile(t *testing.T) {
err := os.Mkdir("./tmp", 0755) tmpFile, err := os.CreateTemp("", "cobra-test")
if err != nil { if err != nil {
log.Fatal(err.Error()) t.Fatal(err.Error())
} }
defer os.RemoveAll("./tmp") defer os.Remove(tmpFile.Name())
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
child := &Command{ child := &Command{
@ -113,18 +114,18 @@ func TestGenFishCompletionFile(t *testing.T) {
} }
rootCmd.AddCommand(child) rootCmd.AddCommand(child)
assertNoErr(t, rootCmd.GenFishCompletionFile("./tmp/test", false)) assertNoErr(t, rootCmd.GenFishCompletionFile(tmpFile.Name(), false))
} }
func TestFailGenFishCompletionFile(t *testing.T) { func TestFailGenFishCompletionFile(t *testing.T) {
err := os.Mkdir("./tmp", 0755) tmpDir, err := os.MkdirTemp("", "cobra-test")
if err != nil { if err != nil {
log.Fatal(err.Error()) t.Fatal(err.Error())
} }
defer os.RemoveAll("./tmp") defer os.RemoveAll(tmpDir)
f, _ := os.OpenFile("./tmp/test", os.O_CREATE, 0400) f, _ := os.OpenFile(filepath.Join(tmpDir, "test"), os.O_CREATE, 0400)
defer f.Close() defer f.Close()
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
@ -135,18 +136,8 @@ func TestFailGenFishCompletionFile(t *testing.T) {
} }
rootCmd.AddCommand(child) rootCmd.AddCommand(child)
got := rootCmd.GenFishCompletionFile("./tmp/test", false) got := rootCmd.GenFishCompletionFile(f.Name(), false)
if got == nil { if !errors.Is(got, os.ErrPermission) {
t.Error("should raise permission denied error") t.Errorf("got: %s, want: %s", got.Error(), os.ErrPermission.Error())
}
if os.Getenv("MSYSTEM") == "MINGW64" {
if got.Error() != "open ./tmp/test: Access is denied." {
t.Errorf("got: %s, want: %s", got.Error(), "open ./tmp/test: Access is denied.")
}
} else {
if got.Error() != "open ./tmp/test: permission denied" {
t.Errorf("got: %s, want: %s", got.Error(), "open ./tmp/test: permission denied")
}
} }
} }