manifoldco / promptui

Interactive prompt for command-line applications
https://www.manifold.co
BSD 3-Clause "New" or "Revised" License
6.03k stars 333 forks source link

About the unit test of the Select #228

Closed wlsyne closed 9 months ago

wlsyne commented 9 months ago

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
wlsyne commented 9 months ago

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

wlsyne commented 9 months ago

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
}