Skip to content

Commit

Permalink
chore: cover cli utils and prompts utils with tests (#20674)
Browse files Browse the repository at this point in the history
  • Loading branch information
pasha-codefresh authored Nov 5, 2024
1 parent b14f1d1 commit 881025b
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions cmd/argocd/commands/utils/prompt_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package utils

import (
"os"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -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
}

0 comments on commit 881025b

Please sign in to comment.