AlecAivazis / survey

A golang library for building interactive and accessible prompts with full support for windows and posix terminals.
MIT License
4.07k stars 350 forks source link

Testing survey.AskOne method with custom input #448

Closed denizgursoy closed 1 year ago

denizgursoy commented 1 year ago

How can I provide input from byte array or text file for survey? I want to use it for test purposes.When I ask for input, I want to send mock value. Example code:

result := ""

input := survey.Input{
    Message: direction,
}
err := survey.AskOne(&input, &result, survey.WithValidator(survey.Validator(validator)))
return result, err
mislav commented 1 year ago

Hi, mocking Survey responses currently isn't straightforward and will only become easier after https://github.com/AlecAivazis/survey/issues/428.

In the meantime, you can set up a virtual terminal in your tests to simulate user input to your prompt: https://github.com/AlecAivazis/survey#testing. Note that this also isn't straightforward.

My personal choice would be to declare a Prompter type in your code that has a method like PromptInput that uses Survey under the hood:

func (p Prompter) PromptInput(message string, validator func(string) bool) (string, error) {
    var result string
    err := survey.AskOne(&survey.Input{
        Message: direction,
    }, &result, survey.WithValidator(survey.Validator(validator)))
    return result, err
}

Then, in test mode, pass a mock object to your app that responds to PromptInput() but returns pre-defined fake responses. That way, Survey never gets actually invoked in tests, and you avoid a whole lot of trouble.