Add tests for help topics

This commit is contained in:
Sam Coe 2020-09-14 22:21:05 +02:00
parent 21449213e5
commit 7ecb6a413f
No known key found for this signature in database
GPG key ID: 8E322C20F811D086
3 changed files with 83 additions and 22 deletions

View file

@ -1,8 +1,6 @@
package root
import (
"fmt"
"github.com/MakeNowJust/heredoc"
"github.com/spf13/cobra"
)
@ -41,6 +39,7 @@ func NewHelpTopic(topic string) *cobra.Command {
Long: topicContent[topic],
Hidden: true,
Args: cobra.NoArgs,
Run: helpTopicHelpFunc,
}
cmd.SetHelpFunc(helpTopicHelpFunc)
@ -50,27 +49,10 @@ func NewHelpTopic(topic string) *cobra.Command {
}
func helpTopicHelpFunc(command *cobra.Command, args []string) {
if len(args) >= 2 && args[1] != "--help" && args[1] != "-h" {
command.Printf("unknown command %q for %q\n", args[1], command.CommandPath())
if args[1] == "help" {
command.Print("\nDid you mean this?\n")
command.Printf("\t%s\n\n", "--help")
} else {
command.Printf("\n")
}
helpTopicUsageFunc(command)
command.Printf("\n")
hasFailed = true
return
}
fmt.Fprint(command.OutOrStdout(), command.Long)
command.Print(command.Long)
}
func helpTopicUsageFunc(command *cobra.Command) error {
command.Printf("Usage: gh help %s", command.Use)
command.Printf("Usage: gh help %s", command.Use)
return nil
}

View file

@ -0,0 +1,79 @@
package root
import (
"testing"
"github.com/cli/cli/pkg/iostreams"
"github.com/stretchr/testify/assert"
)
func TestNewHelpTopic(t *testing.T) {
tests := []struct {
name string
topic string
args []string
flags []string
wantsErr bool
}{
{
name: "valid topic",
topic: "environment",
args: []string{},
flags: []string{},
wantsErr: false,
},
{
name: "invalid topic",
topic: "invalid",
args: []string{},
flags: []string{},
wantsErr: false,
},
{
name: "more than zero args",
topic: "environment",
args: []string{"invalid"},
flags: []string{},
wantsErr: true,
},
{
name: "more than zero flags",
topic: "environment",
args: []string{},
flags: []string{"--invalid"},
wantsErr: true,
},
{
name: "help arg",
topic: "environment",
args: []string{"help"},
flags: []string{},
wantsErr: true,
},
{
name: "help flag",
topic: "environment",
args: []string{},
flags: []string{"--help"},
wantsErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, _, stdout, stderr := iostreams.Test()
cmd := NewHelpTopic(tt.topic)
cmd.SetArgs(append(tt.args, tt.flags...))
cmd.SetOut(stdout)
cmd.SetErr(stderr)
_, err := cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
})
}
}

View file

@ -90,7 +90,7 @@ func NewCmdRoot(f *cmdutil.Factory, version, buildDate string) *cobra.Command {
cmd.AddCommand(gistCmd.NewCmdGist(f))
cmd.AddCommand(NewCmdCompletion(f.IOStreams))
// Help Topics
// Help topics
cmd.AddCommand(NewHelpTopic("environment"))
// the `api` command should not inherit any extra HTTP headers