Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: Add a App.Reader that defaults to os.Stdin #1191

Merged
merged 1 commit into from Oct 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions app.go
Expand Up @@ -72,6 +72,8 @@ type App struct {
Authors []*Author
// Copyright of the binary if any
Copyright string
// Reader reader to write input to (useful for tests)
Reader io.Reader
// Writer writer to write output to
Writer io.Writer
// ErrWriter writes error output
Expand Down Expand Up @@ -117,6 +119,7 @@ func NewApp() *App {
BashComplete: DefaultAppComplete,
Action: helpCommand.Action,
Compiled: compileTime(),
Reader: os.Stdin,
Writer: os.Stdout,
ErrWriter: os.Stderr,
}
Expand Down Expand Up @@ -160,6 +163,10 @@ func (a *App) Setup() {
a.Compiled = compileTime()
}

if a.Reader == nil {
a.Reader = os.Stdin
}

if a.Writer == nil {
a.Writer = os.Stdout
}
Expand Down
38 changes: 38 additions & 0 deletions app_test.go
Expand Up @@ -433,6 +433,12 @@ func TestApp_Command(t *testing.T) {
}
}

func TestApp_Setup_defaultsReader(t *testing.T) {
app := &App{}
app.Setup()
expect(t, app.Reader, os.Stdin)
}

func TestApp_Setup_defaultsWriter(t *testing.T) {
app := &App{}
app.Setup()
Expand Down Expand Up @@ -850,6 +856,15 @@ func TestApp_ParseSliceFlagsWithMissingValue(t *testing.T) {
}
}

func TestApp_DefaultStdin(t *testing.T) {
app := &App{}
app.Setup()

if app.Reader != os.Stdin {
t.Error("Default input reader not set.")
}
}

func TestApp_DefaultStdout(t *testing.T) {
app := &App{}
app.Setup()
Expand All @@ -859,6 +874,29 @@ func TestApp_DefaultStdout(t *testing.T) {
}
}

func TestApp_SetStdin(t *testing.T) {
buf := make([]byte, 12)

app := &App{
Name: "test",
Reader: strings.NewReader("Hello World!"),
Action: func(c *Context) error {
_, err := c.App.Reader.Read(buf)
return err
},
}

err := app.Run([]string{"help"})

if err != nil {
t.Fatalf("Run error: %s", err)
}

if string(buf) != "Hello World!" {
t.Error("App did not read input from desired reader.")
}
}

func TestApp_SetStdout(t *testing.T) {
var w bytes.Buffer

Expand Down