obm/internal/prompt/prompt_test.go

148 lines
2.5 KiB
Go

package prompt
import (
"bytes"
"io"
"os"
"strings"
"testing"
)
func TestField(t *testing.T) {
f := Field{Key: "test", Value: "value"}
if f.Key != "test" || f.Value != "value" {
t.Errorf("Field struct not working correctly")
}
}
func TestConfirm(t *testing.T) {
// Save original stdin
oldStdin := os.Stdin
defer func() { os.Stdin = oldStdin }()
tests := []struct {
input string
expected bool
}{
{"y\n", true},
{"Y\n", true},
{"yes\n", false}, // only 'y' is accepted
{"n\n", false},
{"N\n", false},
{"\n", false},
}
for _, tt := range tests {
r, w, _ := os.Pipe()
os.Stdin = r
go func() {
w.WriteString(tt.input)
w.Close()
}()
// Capture stdout
oldStdout := os.Stdout
rOut, wOut, _ := os.Pipe()
os.Stdout = wOut
result := Confirm("Test?")
wOut.Close()
os.Stdout = oldStdout
// Drain stdout
io.Copy(io.Discard, rOut)
if result != tt.expected {
t.Errorf("Confirm(%q) = %v, expected %v", strings.TrimSpace(tt.input), result, tt.expected)
}
r.Close()
}
}
func TestPromptString(t *testing.T) {
// Save original stdin
oldStdin := os.Stdin
defer func() { os.Stdin = oldStdin }()
tests := []struct {
input string
expected string
}{
{"hello\n", "hello"},
{" trimmed \n", "trimmed"},
{"\n", ""},
}
for _, tt := range tests {
r, w, _ := os.Pipe()
os.Stdin = r
go func() {
w.WriteString(tt.input)
w.Close()
}()
// Capture stdout
oldStdout := os.Stdout
rOut, wOut, _ := os.Pipe()
os.Stdout = wOut
result := PromptString("Enter value")
wOut.Close()
os.Stdout = oldStdout
// Drain stdout
io.Copy(io.Discard, rOut)
if result != tt.expected {
t.Errorf("PromptString(%q) = %q, expected %q", strings.TrimSpace(tt.input), result, tt.expected)
}
r.Close()
}
}
func TestSummaryLine(t *testing.T) {
// Capture stdout
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
SummaryLine("Key", "Value")
w.Close()
os.Stdout = oldStdout
var buf bytes.Buffer
io.Copy(&buf, r)
output := buf.String()
if !strings.Contains(output, "Key:") {
t.Error("SummaryLine missing key")
}
if !strings.Contains(output, "Value") {
t.Error("SummaryLine missing value")
}
}
func TestSummarySection(t *testing.T) {
// Capture stdout
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
SummarySection("TestSection")
w.Close()
os.Stdout = oldStdout
var buf bytes.Buffer
io.Copy(&buf, r)
output := buf.String()
if !strings.Contains(output, "[TestSection]") {
t.Errorf("SummarySection output %q missing [TestSection]", output)
}
}