From 881025b3cac51b9e47975a5551f2380600e2eff1 Mon Sep 17 00:00:00 2001 From: Pasha Kostohrys Date: Wed, 6 Nov 2024 00:28:23 +0200 Subject: [PATCH] chore: cover cli utils and prompts utils with tests (#20674) --- cmd/argocd/commands/utils/prompt_test.go | 77 ++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/cmd/argocd/commands/utils/prompt_test.go b/cmd/argocd/commands/utils/prompt_test.go index b758f2b2f1c9a..4acf96f743f0c 100644 --- a/cmd/argocd/commands/utils/prompt_test.go +++ b/cmd/argocd/commands/utils/prompt_test.go @@ -1,6 +1,7 @@ package utils import ( + "os" "testing" "github.com/stretchr/testify/assert" @@ -47,3 +48,79 @@ func TestConfirmBaseOnCountZeroApps(t *testing.T) { t.Errorf("Expected (true, true), got (%v, %v)", result1, result2) } } + +func TestConfirmPrompt(t *testing.T) { + cases := []struct { + input string + output bool + }{ + {"y\n", true}, + {"n\n", false}, + } + + origStdin := os.Stdin + + for _, c := range cases { + tmpFile, err := writeToStdin(c.input) + if err != nil { + t.Fatal(err) + } + p := &Prompt{enabled: true} + result := p.Confirm("Are you sure you want to run this command? (y/n) \n") + assert.Equal(t, c.output, result) + os.Remove(tmpFile.Name()) + _ = tmpFile.Close() + } + + os.Stdin = origStdin +} + +func TestConfirmAllPrompt(t *testing.T) { + cases := []struct { + input string + confirm bool + confirmAll bool + }{ + {"y\n", true, false}, + {"n\n", false, false}, + {"a\n", true, true}, + } + + origStdin := os.Stdin + + for _, c := range cases { + tmpFile, err := writeToStdin(c.input) + if err != nil { + t.Fatal(err) + } + p := &Prompt{enabled: true} + confirm, confirmAll := p.ConfirmAll("Are you sure you want to run this command? (y/n) \n") + assert.Equal(t, c.confirm, confirm) + assert.Equal(t, c.confirmAll, confirmAll) + os.Remove(tmpFile.Name()) + _ = tmpFile.Close() + } + + os.Stdin = origStdin +} + +func writeToStdin(msg string) (*os.File, error) { + tmpFile, err := os.CreateTemp("", "test-input") + if err != nil { + return nil, err + } + + // Write the input to the temporary file + if _, err := tmpFile.WriteString(msg); err != nil { + return nil, err + } + + // Seek to the beginning of the file so it can be read from the start + if _, err := tmpFile.Seek(0, 0); err != nil { + return nil, err + } + + os.Stdin = tmpFile + + return tmpFile, nil +}