surveymock

package module
v0.3.15 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 13, 2021 License: MIT Imports: 14 Imported by: 0

README

Mock for AlecAivazis/survey

Build Status codecov Go Report Card GoDevDoc Donate

surveymock is a mock library for AlecAivazis/survey/v2

Prerequisites

  • Go >= 1.14

Install

go get github.com/nhatthm/surveymock

Usage

Supported Types

For now, it only supports Confirm and Password

Mock

There are 2 steps:

Step 1: Create an expectation for the survey.

Call surveymock.Mock()

s := surveymock.Mock(func(s *surveymock.Survey) {
    s.ExpectPassword("Enter a password:").
        Answer("secret")
})(t) // t is *testing.T

Step 2: Run it.

Important: Use the stdio arg and inject it into the survey.Prompt otherwise it won't work.

s.Start(func(stdio terminal.Stdio)) {
    // For example
    p := &survey.Password{Message: "Enter a password:"}
    var answer string
    err := survey.AskOne(p, &answer, surveymock.WithStdio(stdio))

    // Asserts.
    assert.Equal(t, "123456", answer)
    assert.NoError(t, err)
})

Examples

package mypackage_test

import (
	"testing"

	"github.com/AlecAivazis/survey/v2"
	"github.com/AlecAivazis/survey/v2/terminal"
	"github.com/nhatthm/surveymock"
	"github.com/stretchr/testify/assert"
)

func TestMyPackage(t *testing.T) {
	t.Parallel()

	testCases := []struct {
		scenario       string
		mockSurvey     surveymock.Mocker
		expectedAnswer string
		expectedError  string
	}{
		{
			scenario: "empty answer",
			mockSurvey: surveymock.Mock(func(s *surveymock.Survey) {
				s.ExpectPassword("Enter a password:").
					Answer("")
			}),
		},
		{
			scenario: "password without help",
			mockSurvey: surveymock.Mock(func(s *surveymock.Survey) {
				s.ExpectPassword("Enter a password:").
					Answer("secret")
			}),
			expectedAnswer: "secret",
		},

		{
			scenario: "input is interrupted",
			mockSurvey: surveymock.Mock(func(s *surveymock.Survey) {
				s.ExpectPassword("Enter a password:").
					Interrupt()
			}),
			expectedError: "interrupt",
		},
	}

	for _, tc := range testCases {
		tc := tc
		t.Run(tc.scenario, func(t *testing.T) {
			t.Parallel()

			p := &survey.Password{Message: "Enter a password:"}

			// Start the survey.
			tc.mockSurvey(t).Start(func(stdio terminal.Stdio) {
				// Run your logic here.
				// For example.
				var answer string
				err := survey.AskOne(p, &answer, surveymock.WithStdio(stdio))

				assert.Equal(t, tc.expectedAnswer, answer)

				if tc.expectedError == "" {
					assert.NoError(t, err)
				} else {
					assert.EqualError(t, err, tc.expectedError)
				}
			})
		})
	}
}

You can find more examples in the tests of this library. For example: https://github.com/nhatthm/surveymock/blob/master/confirm_test.go or https://github.com/nhatthm/surveymock/blob/master/confirm_test.go

Donation

If this project help you reduce time to develop, you can give me a cup of coffee :)

Paypal donation

paypal

       or scan this

Documentation

Overview

Package surveymock provides mock for github.com/AlecAivazis/survey.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoExpectation = errors.New("no expectation")

ErrNoExpectation indicates that there is no expectation.

View Source
var ReactionTime = 3 * time.Millisecond

ReactionTime is to create a small delay to simulate human reaction.

Functions

This section is empty.

Types

type Answer added in v0.2.0

type Answer interface {
	// Expect runs the expectation.
	Expect(c Console) error

	// String represents the answer as a string.
	String() string
}

Answer is an expectation for answering a question.

type Buffer added in v0.3.6

type Buffer struct {
	// contains filtered or unexported fields
}

Buffer is a goroutine safe bytes.Buffer.

func (*Buffer) Reset added in v0.3.7

func (b *Buffer) Reset()

Reset resets the buffer to be empty, but it retains the underlying storage for use by future writes. Reset is the same as Truncate(0).

func (*Buffer) String added in v0.3.6

func (b *Buffer) String() string

String returns the contents of the unread portion of the buffer as a string. If the Buffer is a nil pointer, it returns "<nil>".

To build strings more efficiently, see the strings.Builder type.

func (*Buffer) Write added in v0.3.6

func (b *Buffer) Write(p []byte) (n int, err error)

Write appends the contents of p to the buffer, growing the buffer as needed. The return value n is the length of p; err is always nil. If the buffer becomes too large, Write will panic with ErrTooLarge.

type Confirm added in v0.3.2

type Confirm struct {
	// contains filtered or unexported fields
}

Confirm is an expectation of survey.Confirm.

func (*Confirm) Answer added in v0.3.2

func (c *Confirm) Answer(answer string) *ConfirmAnswer

Answer sets a custom answer to the prompt.

If the answer is not not empty, the mock expects to have a feedback from the survey:

`Sorry, your reply was invalid: "hello world!" is not a valid answer, please try again.`

Survey.ExpectConfirm("Are you sure to delete this file?").
	Answer("hello world!").

func (*Confirm) Expect added in v0.3.2

func (c *Confirm) Expect(console Console) error

Expect runs the expectation.

func (*Confirm) Interrupt added in v0.3.2

func (c *Confirm) Interrupt()

Interrupt marks the answer is interrupted.

Survey.ExpectConfirm("Are you sure to delete this file?").
	Interrupt().

func (*Confirm) No added in v0.3.2

func (c *Confirm) No()

No sets "no" as the answer to the prompt.

Survey.ExpectConfirm("Are you sure to delete this file?").
	No().

func (Confirm) Repeat added in v0.3.2

func (b Confirm) Repeat() bool

func (*Confirm) ShowHelp added in v0.3.2

func (c *Confirm) ShowHelp(help string)

ShowHelp sets help for the expectation.

Survey.ExpectConfirm("Are you sure to delete this file?").
	ShowHelp("The file will be permanently deleted").

func (*Confirm) String added in v0.3.2

func (c *Confirm) String() string

String represents the expectation as a string.

func (*Confirm) Yes added in v0.3.2

func (c *Confirm) Yes()

Yes sets "yes" as the answer to the prompt.

Survey.ExpectConfirm("Are you sure to delete this file?").
	Yes().

type ConfirmAnswer added in v0.3.2

type ConfirmAnswer struct {
	// contains filtered or unexported fields
}

ConfirmAnswer is an answer for confirm question.

func (*ConfirmAnswer) Expect added in v0.3.2

func (a *ConfirmAnswer) Expect(c Console) error

Expect runs the expectation. nolint: errcheck,gosec

func (*ConfirmAnswer) Interrupted added in v0.3.2

func (a *ConfirmAnswer) Interrupted()

Interrupted expects the answer will be interrupted.

func (*ConfirmAnswer) String added in v0.3.2

func (a *ConfirmAnswer) String() string

String represents the answer as a string.

type Console

type Console interface {
	// terminal device.
	Tty() *os.File

	// pty.
	Fd() uintptr

	// Close closes Console's tty. Calling Close will unblock Expect and ExpectEOF.
	Close() error

	// Send writes string s to Console's tty.
	Send(s string) (int, error)

	// SendLine writes string s to Console's tty with a trailing newline.
	SendLine(s string) (int, error)

	// Expectf reads from the Console's tty until the provided formatted string
	// is read or an error occurs, and returns the buffer read by Console.
	Expectf(format string, args ...interface{}) (string, error)

	// ExpectString reads from Console's tty until the provided string is read or
	// an error occurs, and returns the buffer read by Console.
	ExpectString(s string) (string, error)

	// ExpectEOF reads from Console's tty until EOF or an error occurs, and returns
	// the buffer read by Console.  We also treat the PTSClosed error as an EOF.
	ExpectEOF() (string, error)

	// Expect reads from Console's tty until a condition specified from opts is
	// encountered or an error occurs, and returns the buffer read by console.
	// No extra bytes are read once a condition is met, so if a program isn't
	// expecting input yet, it will be blocked. Sends are queued up in tty's
	// internal buffer so that the next Expect will read the remaining bytes (i.e.
	// rest of prompt) as well as its conditions.
	Expect(opts ...expect.ExpectOpt) (string, error)
}

Console is an interface wrapper around *expect.Console.

type Expectation

type Expectation interface {
	// Expect runs the expectation.
	Expect(c Console) error

	// Repeat tells survey to repeat the same expectation.
	Repeat() bool

	// String represents the expectation as a string.
	String() string
}

Expectation is an expectation for mocking survey.

type HelpAnswer added in v0.3.0

type HelpAnswer struct {
	// contains filtered or unexported fields
}

HelpAnswer sends a ? to show the help.

func (*HelpAnswer) Expect added in v0.3.0

func (a *HelpAnswer) Expect(c Console) error

Expect runs the expectation. nolint: errcheck,gosec

func (*HelpAnswer) String added in v0.3.0

func (a *HelpAnswer) String() string

String represents the answer as a string.

type InterruptAnswer added in v0.2.0

type InterruptAnswer struct{}

InterruptAnswer sends an interrupt sequence to terminate the survey.

func (*InterruptAnswer) Expect added in v0.2.0

func (a *InterruptAnswer) Expect(c Console) error

Expect runs the expectation. nolint: errcheck,gosec

func (*InterruptAnswer) String added in v0.2.0

func (a *InterruptAnswer) String() string

String represents the answer as a string.

type MockOption

type MockOption func(s *Survey)

MockOption is option for mocking survey.

type Mocker

type Mocker func(t TestingT) *Survey

Mocker mocks survey.

func Mock

func Mock(mocks ...MockOption) Mocker

Mock creates a mocked server with expectations and assures that ExpectationsWereMet() is called.

type NoAnswer added in v0.2.0

type NoAnswer struct{}

NoAnswer sends an empty line to answer the question.

func (*NoAnswer) Expect added in v0.2.0

func (a *NoAnswer) Expect(c Console) error

Expect runs the expectation. nolint: errcheck,gosec

func (*NoAnswer) String added in v0.2.0

func (a *NoAnswer) String() string

String represents the answer as a string.

type Password

type Password struct {
	// contains filtered or unexported fields
}

Password is an expectation of survey.Password.

func (*Password) Answer

func (p *Password) Answer(answer string) *PasswordAnswer

Answer sets the answer to the password prompt.

Survey.ExpectPassword("Enter password:").
	Answer("hello world!").

func (*Password) Expect added in v0.2.0

func (p *Password) Expect(c Console) error

Expect runs the expectation.

func (*Password) Interrupt

func (p *Password) Interrupt()

Interrupt marks the answer is interrupted.

Survey.ExpectPassword("Enter password:").
	Interrupt().

func (*Password) Once

func (p *Password) Once() *Password

Once indicates that the message should only be asked once.

Survey.ExpectPassword("Enter password:").
	Answer("hello world!").
	Once()

func (Password) Repeat added in v0.2.0

func (b Password) Repeat() bool

func (*Password) ShowHelp added in v0.3.0

func (p *Password) ShowHelp(help string)

ShowHelp sets help for the expectation.

Survey.ExpectPassword("Enter password:").
	ShowHelp("Your shiny password").

func (*Password) String

func (p *Password) String() string

String represents the expectation as a string.

func (*Password) Times

func (p *Password) Times(i int) *Password

Times indicates that the message should only be asked the indicated number of times.

Survey.ExpectPassword("Enter password:").
	Answer("hello world!").
	Times(5)

func (*Password) Twice

func (p *Password) Twice() *Password

Twice indicates that the message should only be asked twice.

Survey.ExpectPassword("Enter password:").
	Answer("hello world!").
	Twice()

type PasswordAnswer added in v0.2.0

type PasswordAnswer struct {
	// contains filtered or unexported fields
}

PasswordAnswer is an answer for password question.

func (*PasswordAnswer) Expect added in v0.2.0

func (a *PasswordAnswer) Expect(c Console) error

Expect runs the expectation. nolint: errcheck,gosec

func (*PasswordAnswer) Interrupted added in v0.2.0

func (a *PasswordAnswer) Interrupted()

Interrupted expects the answer will be interrupted.

func (*PasswordAnswer) String added in v0.2.0

func (a *PasswordAnswer) String() string

String represents the answer as a string.

type StringWriter

type StringWriter interface {
	io.Writer
	fmt.Stringer
}

StringWriter is a wrapper for bytes.Buffer.

type Survey

type Survey struct {
	// contains filtered or unexported fields
}

Survey is a mocked survey.

func New added in v0.3.15

func New(t TestingT, mocks ...MockOption) *Survey

New creates a new mocked survey.

func (*Survey) Expect added in v0.3.9

func (s *Survey) Expect(c Console) error

Expect runs an expectation against a given console.

func (*Survey) ExpectConfirm added in v0.3.2

func (s *Survey) ExpectConfirm(message string) *Confirm

ExpectConfirm expects a Confirm.

Survey.ExpectConfirm("Confirm?").
	Yes()

func (*Survey) ExpectPassword

func (s *Survey) ExpectPassword(message string) *Password

ExpectPassword expects a Password.

Survey.ExpectPassword("Enter password:").
	Answer("hello world!")

func (*Survey) ExpectationsWereMet

func (s *Survey) ExpectationsWereMet() error

ExpectationsWereMet checks whether all queued expectations were met in order. If any of them was not met - an error is returned.

func (*Survey) ResetExpectations added in v0.3.8

func (s *Survey) ResetExpectations()

ResetExpectations resets all the expectations.

func (*Survey) Start

func (s *Survey) Start(fn func(stdio terminal.Stdio))

Start starts the survey with a default timeout.

func (*Survey) WithTimeout

func (s *Survey) WithTimeout(t time.Duration) *Survey

WithTimeout sets the timeout of a survey.

type TestingT

type TestingT interface {
	Errorf(format string, args ...interface{})
	FailNow()
	Cleanup(func())
	Log(args ...interface{})
	Logf(format string, args ...interface{})
}

TestingT is an interface wrapper around *testing.T.

Directories

Path Synopsis
Package options provide options for configuring survey options.
Package options provide options for configuring survey options.
cobra
Package cobra provides support for stdio with cobra command.
Package cobra provides support for stdio with cobra command.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL