manifoldco / promptui

Interactive prompt for command-line applications

Home Page:https://www.manifold.co

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

About the unit test of the Select

wlsyne opened this issue · comments

I tried to write a unit test of Select but encounterd an error

The function

func UserSelect() (string, error) {
	prompt := promptui.Select{
		Label: "Select Day",
		Items: []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
			"Saturday", "Sunday"},
	}

	_, result, err := prompt.Run()

	if err != nil {
		fmt.Printf("Prompt failed %v\n", err)
		return "", err
	}

	fmt.Printf("You choose %q\n", result)
	return result, nil
}

The test

func TestUserSelect(t *testing.T) {
	// Create a pipe to simulate user input
	r, w, err := os.Pipe()
	if err != nil {
		t.Fatalf("Error creating pipe: %v", err)
	}

	// Redirect stdin to the read end of the pipe
	oldStdin := os.Stdin
	defer func() {
		r.Close()
		w.Close()
		os.Stdin = oldStdin
	}()

	os.Stdin = r

	// Write user input to the write end of the pipe
	input := "\033[B\n" // Press down arrow key and then enter key
	if _, err := w.WriteString(input); err != nil {
		t.Fatalf("Error writing to pipe: %v", err)
	}

	// Call the function that reads from stdin
	result, err := UserSelect()
	if err != nil {
		t.Fatalf("Error selecting from prompt: %v", err)
	}

	// Verify the output
	expected := "Tuesday"
	if result != expected {
		t.Fatalf("Unexpected result: %q, expected: %q", result, expected)
	}
}

The error

=== RUN   TestUserSelect
Use the arrow keys to navigate: ↓ ↑ → ← 
? Select Day: 
  ▸ Monday
    Tuesday
    Wednesday
    Thursday
↓   Friday

Prompt failed ^D
    test_test.go:58: Error selecting from prompt: ^D
--- FAIL: TestUserSelect (0.00s)

FAIL

Is there any method to simulate user pressing down arrow key an enter key

I solved this issue with specifying the Stdio to the Select

func UserSelect() (string, error) {
	prompt := promptui.Select{
		Label: "Select Day",
		Items: []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
			"Saturday", "Sunday"},
		Stdin: os.Stdin,
	}

	_, result, err := prompt.Run()

	if err != nil {
		fmt.Printf("Prompt failed %v\n", err)
		return "", err
	}

	fmt.Printf("You choose %q\n", result)
	return result, nil
}