diff --git a/version.go b/version.go index 1102cc7..1db770e 100644 --- a/version.go +++ b/version.go @@ -46,7 +46,7 @@ func VersionCommand(id Identification, additions ...versionAddition) *cobra.Comm value, err := versionInfo(info, format, additions...) if err == nil { - cmd.Print(value) + fmt.Print(value) } return err }, diff --git a/version_test.go b/version_test.go index 4b96eb2..7c5b2b0 100644 --- a/version_test.go +++ b/version_test.go @@ -1,11 +1,39 @@ package clio import ( + "bytes" + "io" + "os" + "sync" "testing" "github.com/stretchr/testify/require" ) +func Test_versionOutputToStdout(t *testing.T) { + c := VersionCommand(Identification{ + Name: "test", + Version: "version", + }) + + stdout := &bytes.Buffer{} + restoreStdout := capture(&os.Stdout, stdout, 1024) + defer restoreStdout() + + stderr := &bytes.Buffer{} + restoreStderr := capture(&os.Stderr, stderr, 1024) + defer restoreStderr() + + _ = c.RunE(c, nil) + + // close and flush the buffers, wait until complete + restoreStdout() + restoreStderr() + + require.NotEmpty(t, stdout.String()) + require.Empty(t, stderr.String()) +} + func Test_versionInfoText(t *testing.T) { expected := `Application: the-name Version: the-version @@ -67,3 +95,37 @@ func Test_versionInfoJSON(t *testing.T) { require.NoError(t, err) require.JSONEq(t, expected, got) } + +func capture(target **os.File, writer io.Writer, bufSize int) (close func()) { + original := *target + + r, w, _ := os.Pipe() + + wg := sync.WaitGroup{} + wg.Add(1) + + go func() { + defer wg.Done() + buf := make([]byte, bufSize) + for { + n, err := r.Read(buf) + if n > 0 { + _, _ = writer.Write(buf[0:n]) + } + if err != nil { + break + } + } + }() + + *target = w + + return func() { + if original != nil { + _ = w.Close() + wg.Wait() + *target = original + original = nil + } + } +}