Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: cover cli utils and prompts utils with tests #20674

Merged
merged 2 commits into from
Nov 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}