Improve tests in doc/

This commit is contained in:
Albert Nigmatzianov 2017-11-02 16:22:38 +01:00
parent d6a430541c
commit 2da4a54c5c
5 changed files with 163 additions and 410 deletions

View File

@ -1,145 +1,86 @@
package doc package doc
import ( import (
"bytes"
"fmt"
"runtime"
"strings" "strings"
"testing" "testing"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var flagb1, flagb2, flagb3, flagbr, flagbp bool func emptyRun(*cobra.Command, []string) {}
var flags1, flags2a, flags2b, flags3 string
var flagi1, flagi2, flagi3, flagir int
const strtwoParentHelp = "help message for parent flag strtwo" func init() {
const strtwoChildHelp = "help message for child flag strtwo" rootCmd.PersistentFlags().StringP("rootflag", "r", "two", "")
rootCmd.PersistentFlags().StringP("strtwo", "t", "two", "help message for parent flag strtwo")
var cmdEcho = &cobra.Command{ echoCmd.PersistentFlags().StringP("strone", "s", "one", "help message for flag strone")
echoCmd.PersistentFlags().BoolP("persistentbool", "p", false, "help message for flag persistentbool")
echoCmd.Flags().IntP("intone", "i", 123, "help message for flag intone")
echoCmd.Flags().BoolP("boolone", "b", true, "help message for flag boolone")
timesCmd.PersistentFlags().StringP("strtwo", "t", "2", "help message for child flag strtwo")
timesCmd.Flags().IntP("inttwo", "j", 234, "help message for flag inttwo")
timesCmd.Flags().BoolP("booltwo", "c", false, "help message for flag booltwo")
printCmd.PersistentFlags().StringP("strthree", "s", "three", "help message for flag strthree")
printCmd.Flags().IntP("intthree", "i", 345, "help message for flag intthree")
printCmd.Flags().BoolP("boolthree", "b", true, "help message for flag boolthree")
echoCmd.AddCommand(timesCmd, echoSubCmd, deprecatedCmd)
rootCmd.AddCommand(printCmd, echoCmd)
}
var rootCmd = &cobra.Command{
Use: "root",
Short: "Root short description",
Long: "Root long description",
Run: emptyRun,
}
var echoCmd = &cobra.Command{
Use: "echo [string to echo]", Use: "echo [string to echo]",
Aliases: []string{"say"}, Aliases: []string{"say"},
Short: "Echo anything to the screen", Short: "Echo anything to the screen",
Long: `an utterly useless command for testing.`, Long: "an utterly useless command for testing",
Example: "Just run cobra-test echo", Example: "Just run cobra-test echo",
} }
var cmdEchoSub = &cobra.Command{ var echoSubCmd = &cobra.Command{
Use: "echosub [string to print]", Use: "echosub [string to print]",
Short: "second sub command for echo", Short: "second sub command for echo",
Long: `an absolutely utterly useless command for testing gendocs!.`, Long: "an absolutely utterly useless command for testing gendocs!.",
Run: func(cmd *cobra.Command, args []string) {}, Run: emptyRun,
} }
var cmdDeprecated = &cobra.Command{ var timesCmd = &cobra.Command{
Use: "times [# times] [string to echo]",
SuggestFor: []string{"counts"},
Short: "Echo anything to the screen more times",
Long: `a slightly useless command for testing.`,
Run: emptyRun,
}
var deprecatedCmd = &cobra.Command{
Use: "deprecated [can't do anything here]", Use: "deprecated [can't do anything here]",
Short: "A command which is deprecated", Short: "A command which is deprecated",
Long: `an absolutely utterly useless command for testing deprecation!.`, Long: `an absolutely utterly useless command for testing deprecation!.`,
Deprecated: "Please use echo instead", Deprecated: "Please use echo instead",
} }
var cmdTimes = &cobra.Command{ var printCmd = &cobra.Command{
Use: "times [# times] [string to echo]",
SuggestFor: []string{"counts"},
Short: "Echo anything to the screen more times",
Long: `a slightly useless command for testing.`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {},
Run: func(cmd *cobra.Command, args []string) {},
}
var cmdPrint = &cobra.Command{
Use: "print [string to print]", Use: "print [string to print]",
Short: "Print anything to the screen", Short: "Print anything to the screen",
Long: `an absolutely utterly useless command for testing.`, Long: `an absolutely utterly useless command for testing.`,
} }
var cmdRootNoRun = &cobra.Command{ func checkStringContains(t *testing.T, got, expected string) {
Use: "cobra-test", if !strings.Contains(got, expected) {
Short: "The root can run its own function", t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got)
Long: "The root description for help",
}
var cmdRootSameName = &cobra.Command{
Use: "print",
Short: "Root with the same name as a subcommand",
Long: "The root description for help",
}
var cmdRootWithRun = &cobra.Command{
Use: "cobra-test",
Short: "The root can run its own function",
Long: "The root description for help",
}
var cmdSubNoRun = &cobra.Command{
Use: "subnorun",
Short: "A subcommand without a Run function",
Long: "A long output about a subcommand without a Run function",
}
var cmdVersion1 = &cobra.Command{
Use: "version",
Short: "Print the version number",
Long: `First version of the version command`,
}
var cmdVersion2 = &cobra.Command{
Use: "version",
Short: "Print the version number",
Long: `Second version of the version command`,
}
func flagInit() {
cmdEcho.ResetFlags()
cmdPrint.ResetFlags()
cmdTimes.ResetFlags()
cmdRootNoRun.ResetFlags()
cmdRootSameName.ResetFlags()
cmdRootWithRun.ResetFlags()
cmdSubNoRun.ResetFlags()
cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp)
cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")
cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")
cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")
cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")
cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")
cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)
cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")
cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone")
cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo")
cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree")
cmdVersion1.ResetFlags()
cmdVersion2.ResetFlags()
}
func initializeWithRootCmd() *cobra.Command {
cmdRootWithRun.ResetCommands()
flagInit()
cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot")
cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot")
return cmdRootWithRun
}
func checkStringContains(t *testing.T, found, expected string) {
if !strings.Contains(found, expected) {
logErr(t, found, expected)
} }
} }
func checkStringOmits(t *testing.T, found, expected string) { func checkStringOmits(t *testing.T, got, expected string) {
if strings.Contains(found, expected) { if strings.Contains(got, expected) {
logErr(t, found, expected) t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got)
} }
} }
func logErr(t *testing.T, found, expected string) {
out := new(bytes.Buffer)
_, _, line, ok := runtime.Caller(2)
if ok {
fmt.Fprintf(out, "Line: %d ", line)
}
fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
t.Errorf(out.String())
}

View File

@ -18,135 +18,97 @@ func translate(in string) string {
} }
func TestGenManDoc(t *testing.T) { func TestGenManDoc(t *testing.T) {
c := initializeWithRootCmd()
// Need two commands to run the command alphabetical sort
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
c.AddCommand(cmdPrint, cmdEcho)
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
out := new(bytes.Buffer)
header := &GenManHeader{ header := &GenManHeader{
Title: "Project", Title: "Project",
Section: "2", Section: "2",
} }
// We generate on a subcommand so we have both subcommands and parents // We generate on a subcommand so we have both subcommands and parents
if err := GenMan(cmdEcho, header, out); err != nil { buf := new(bytes.Buffer)
if err := GenMan(echoCmd, header, buf); err != nil {
t.Fatal(err) t.Fatal(err)
} }
found := out.String() output := buf.String()
// Make sure parent has - in CommandPath() in SEE ALSO: // Make sure parent has - in CommandPath() in SEE ALSO:
parentPath := cmdEcho.Parent().CommandPath() parentPath := echoCmd.Parent().CommandPath()
dashParentPath := strings.Replace(parentPath, " ", "-", -1) dashParentPath := strings.Replace(parentPath, " ", "-", -1)
expected := translate(dashParentPath) expected := translate(dashParentPath)
expected = expected + "(" + header.Section + ")" expected = expected + "(" + header.Section + ")"
checkStringContains(t, found, expected) checkStringContains(t, output, expected)
// Our description checkStringContains(t, output, translate(echoCmd.Name()))
expected = translate(cmdEcho.Name()) checkStringContains(t, output, translate(echoCmd.Name()))
checkStringContains(t, found, expected) checkStringContains(t, output, "boolone")
checkStringContains(t, output, "rootflag")
// Better have our example checkStringContains(t, output, translate(rootCmd.Name()))
expected = translate(cmdEcho.Name()) checkStringContains(t, output, translate(echoSubCmd.Name()))
checkStringContains(t, found, expected) checkStringOmits(t, output, translate(deprecatedCmd.Name()))
checkStringContains(t, output, translate("Auto generated"))
// A local flag
expected = "boolone"
checkStringContains(t, found, expected)
// persistent flag on parent
expected = "rootflag"
checkStringContains(t, found, expected)
// We better output info about our parent
expected = translate(cmdRootWithRun.Name())
checkStringContains(t, found, expected)
// And about subcommands
expected = translate(cmdEchoSub.Name())
checkStringContains(t, found, expected)
unexpected := translate(cmdDeprecated.Name())
checkStringOmits(t, found, unexpected)
// auto generated
expected = translate("Auto generated")
checkStringContains(t, found, expected)
} }
func TestGenManNoGenTag(t *testing.T) { func TestGenManNoGenTag(t *testing.T) {
c := initializeWithRootCmd() echoCmd.DisableAutoGenTag = true
// Need two commands to run the command alphabetical sort defer func() { echoCmd.DisableAutoGenTag = false }()
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
c.AddCommand(cmdPrint, cmdEcho)
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
cmdEcho.DisableAutoGenTag = true
out := new(bytes.Buffer)
header := &GenManHeader{ header := &GenManHeader{
Title: "Project", Title: "Project",
Section: "2", Section: "2",
} }
// We generate on a subcommand so we have both subcommands and parents // We generate on a subcommand so we have both subcommands and parents
if err := GenMan(cmdEcho, header, out); err != nil { buf := new(bytes.Buffer)
if err := GenMan(echoCmd, header, buf); err != nil {
t.Fatal(err) t.Fatal(err)
} }
found := out.String() output := buf.String()
unexpected := translate("#HISTORY") unexpected := translate("#HISTORY")
checkStringOmits(t, found, unexpected) checkStringOmits(t, output, unexpected)
} }
func TestGenManSeeAlso(t *testing.T) { func TestGenManSeeAlso(t *testing.T) {
noop := func(cmd *cobra.Command, args []string) {} rootCmd := &cobra.Command{Use: "root", Run: emptyRun}
aCmd := &cobra.Command{Use: "aaa", Run: emptyRun, Hidden: true} // #229
bCmd := &cobra.Command{Use: "bbb", Run: emptyRun}
cCmd := &cobra.Command{Use: "ccc", Run: emptyRun}
rootCmd.AddCommand(aCmd, bCmd, cCmd)
top := &cobra.Command{Use: "top", Run: noop} buf := new(bytes.Buffer)
aaa := &cobra.Command{Use: "aaa", Run: noop, Hidden: true} // #229
bbb := &cobra.Command{Use: "bbb", Run: noop}
ccc := &cobra.Command{Use: "ccc", Run: noop}
top.AddCommand(aaa, bbb, ccc)
out := new(bytes.Buffer)
header := &GenManHeader{} header := &GenManHeader{}
if err := GenMan(top, header, out); err != nil { if err := GenMan(rootCmd, header, buf); err != nil {
t.Fatal(err) t.Fatal(err)
} }
scanner := bufio.NewScanner(buf)
scanner := bufio.NewScanner(out) if err := assertLineFound(scanner, ".SH SEE ALSO"); err != nil {
t.Fatalf("Couldn't find SEE ALSO section header: %v", err)
if err := AssertLineFound(scanner, ".SH SEE ALSO"); err != nil {
t.Fatal(fmt.Errorf("Couldn't find SEE ALSO section header: %s", err.Error()))
} }
if err := assertNextLineEquals(scanner, ".PP"); err != nil {
if err := AssertNextLineEquals(scanner, ".PP"); err != nil { t.Fatalf("First line after SEE ALSO wasn't break-indent: %v", err)
t.Fatal(fmt.Errorf("First line after SEE ALSO wasn't break-indent: %s", err.Error()))
} }
if err := assertNextLineEquals(scanner, `\fBroot\-bbb(1)\fP, \fBroot\-ccc(1)\fP`); err != nil {
if err := AssertNextLineEquals(scanner, `\fBtop\-bbb(1)\fP, \fBtop\-ccc(1)\fP`); err != nil { t.Fatalf("Second line after SEE ALSO wasn't correct: %v", err)
t.Fatal(fmt.Errorf("Second line after SEE ALSO wasn't correct: %s", err.Error()))
} }
} }
func TestManPrintFlagsHidesShortDeperecated(t *testing.T) { func TestManPrintFlagsHidesShortDeperecated(t *testing.T) {
cmd := &cobra.Command{} c := &cobra.Command{}
flags := cmd.Flags() c.Flags().StringP("foo", "f", "default", "Foo flag")
flags.StringP("foo", "f", "default", "Foo flag") c.Flags().MarkShorthandDeprecated("foo", "don't use it no more")
flags.MarkShorthandDeprecated("foo", "don't use it no more")
out := new(bytes.Buffer) buf := new(bytes.Buffer)
manPrintFlags(out, flags) manPrintFlags(buf, c.Flags())
got := buf.String()
expected := "**--foo**=\"default\"\n\tFoo flag\n\n" expected := "**--foo**=\"default\"\n\tFoo flag\n\n"
if out.String() != expected { if got != expected {
t.Fatalf("Expected %s, but got %s", expected, out.String()) t.Errorf("Expected %v, got %v", expected, got)
} }
} }
func TestGenManTree(t *testing.T) { func TestGenManTree(t *testing.T) {
cmd := &cobra.Command{ c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
Use: "do [OPTIONS] arg1 arg2",
}
header := &GenManHeader{Section: "2"} header := &GenManHeader{Section: "2"}
tmpdir, err := ioutil.TempDir("", "test-gen-man-tree") tmpdir, err := ioutil.TempDir("", "test-gen-man-tree")
if err != nil { if err != nil {
@ -154,7 +116,7 @@ func TestGenManTree(t *testing.T) {
} }
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
if err := GenManTree(cmd, header, tmpdir); err != nil { if err := GenManTree(c, header, tmpdir); err != nil {
t.Fatalf("GenManTree failed: %s", err.Error()) t.Fatalf("GenManTree failed: %s", err.Error())
} }
@ -167,7 +129,7 @@ func TestGenManTree(t *testing.T) {
} }
} }
func AssertLineFound(scanner *bufio.Scanner, expectedLine string) error { func assertLineFound(scanner *bufio.Scanner, expectedLine string) error {
for scanner.Scan() { for scanner.Scan() {
line := scanner.Text() line := scanner.Text()
if line == expectedLine { if line == expectedLine {
@ -176,30 +138,29 @@ func AssertLineFound(scanner *bufio.Scanner, expectedLine string) error {
} }
if err := scanner.Err(); err != nil { if err := scanner.Err(); err != nil {
return fmt.Errorf("AssertLineFound: scan failed: %s", err.Error()) return fmt.Errorf("scan failed: %s", err)
} }
return fmt.Errorf("AssertLineFound: hit EOF before finding %#v", expectedLine) return fmt.Errorf("hit EOF before finding %v", expectedLine)
} }
func AssertNextLineEquals(scanner *bufio.Scanner, expectedLine string) error { func assertNextLineEquals(scanner *bufio.Scanner, expectedLine string) error {
if scanner.Scan() { if scanner.Scan() {
line := scanner.Text() line := scanner.Text()
if line == expectedLine { if line == expectedLine {
return nil return nil
} }
return fmt.Errorf("AssertNextLineEquals: got %#v, not %#v", line, expectedLine) return fmt.Errorf("got %v, not %v", line, expectedLine)
} }
if err := scanner.Err(); err != nil { if err := scanner.Err(); err != nil {
return fmt.Errorf("AssertNextLineEquals: scan failed: %s", err.Error()) return fmt.Errorf("scan failed: %v", err)
} }
return fmt.Errorf("AssertNextLineEquals: hit EOF before finding %#v", expectedLine) return fmt.Errorf("hit EOF before finding %v", expectedLine)
} }
func BenchmarkGenManToFile(b *testing.B) { func BenchmarkGenManToFile(b *testing.B) {
c := initializeWithRootCmd()
file, err := ioutil.TempFile("", "") file, err := ioutil.TempFile("", "")
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
@ -209,7 +170,7 @@ func BenchmarkGenManToFile(b *testing.B) {
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
if err := GenMan(c, nil, file); err != nil { if err := GenMan(rootCmd, nil, file); err != nil {
b.Fatal(err) b.Fatal(err)
} }
} }

View File

@ -5,100 +5,51 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
func TestGenMdDoc(t *testing.T) { func TestGenMdDoc(t *testing.T) {
c := initializeWithRootCmd() // We generate on subcommand so we have both subcommands and parents.
// Need two commands to run the command alphabetical sort buf := new(bytes.Buffer)
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated) if err := GenMarkdown(echoCmd, buf); err != nil {
c.AddCommand(cmdPrint, cmdEcho)
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
out := new(bytes.Buffer)
// We generate on s subcommand so we have both subcommands and parents
if err := GenMarkdown(cmdEcho, out); err != nil {
t.Fatal(err) t.Fatal(err)
} }
found := out.String() output := buf.String()
// Our description checkStringContains(t, output, echoCmd.Long)
expected := cmdEcho.Long checkStringContains(t, output, echoCmd.Example)
if !strings.Contains(found, expected) { checkStringContains(t, output, "boolone")
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) checkStringContains(t, output, "rootflag")
} checkStringContains(t, output, rootCmd.Short)
checkStringContains(t, output, echoSubCmd.Short)
// Better have our example checkStringOmits(t, output, deprecatedCmd.Short)
expected = cmdEcho.Example
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// A local flag
expected = "boolone"
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// persistent flag on parent
expected = "rootflag"
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// We better output info about our parent
expected = cmdRootWithRun.Short
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// And about subcommands
expected = cmdEchoSub.Short
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
unexpected := cmdDeprecated.Short
if strings.Contains(found, unexpected) {
t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)
}
} }
func TestGenMdNoTag(t *testing.T) { func TestGenMdNoTag(t *testing.T) {
c := initializeWithRootCmd() rootCmd.DisableAutoGenTag = true
// Need two commands to run the command alphabetical sort defer func() { rootCmd.DisableAutoGenTag = false }()
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
c.AddCommand(cmdPrint, cmdEcho)
c.DisableAutoGenTag = true
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
out := new(bytes.Buffer)
if err := GenMarkdown(c, out); err != nil { buf := new(bytes.Buffer)
if err := GenMarkdown(rootCmd, buf); err != nil {
t.Fatal(err) t.Fatal(err)
} }
found := out.String() output := buf.String()
unexpected := "Auto generated"
checkStringOmits(t, found, unexpected)
checkStringOmits(t, output, "Auto generated")
} }
func TestGenMdTree(t *testing.T) { func TestGenMdTree(t *testing.T) {
cmd := &cobra.Command{ c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
Use: "do [OPTIONS] arg1 arg2",
}
tmpdir, err := ioutil.TempDir("", "test-gen-md-tree") tmpdir, err := ioutil.TempDir("", "test-gen-md-tree")
if err != nil { if err != nil {
t.Fatalf("Failed to create tmpdir: %s", err.Error()) t.Fatalf("Failed to create tmpdir: %v", err)
} }
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
if err := GenMarkdownTree(cmd, tmpdir); err != nil { if err := GenMarkdownTree(c, tmpdir); err != nil {
t.Fatalf("GenMarkdownTree failed: %s", err.Error()) t.Fatalf("GenMarkdownTree failed: %v", err)
} }
if _, err := os.Stat(filepath.Join(tmpdir, "do.md")); err != nil { if _, err := os.Stat(filepath.Join(tmpdir, "do.md")); err != nil {
@ -107,7 +58,6 @@ func TestGenMdTree(t *testing.T) {
} }
func BenchmarkGenMarkdownToFile(b *testing.B) { func BenchmarkGenMarkdownToFile(b *testing.B) {
c := initializeWithRootCmd()
file, err := ioutil.TempFile("", "") file, err := ioutil.TempFile("", "")
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
@ -117,7 +67,7 @@ func BenchmarkGenMarkdownToFile(b *testing.B) {
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
if err := GenMarkdown(c, file); err != nil { if err := GenMarkdown(rootCmd, file); err != nil {
b.Fatal(err) b.Fatal(err)
} }
} }

View File

@ -5,99 +5,52 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
func TestGenRSTDoc(t *testing.T) { func TestGenRSTDoc(t *testing.T) {
c := initializeWithRootCmd() // We generate on a subcommand so we have both subcommands and parents
// Need two commands to run the command alphabetical sort buf := new(bytes.Buffer)
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated) if err := GenReST(echoCmd, buf); err != nil {
c.AddCommand(cmdPrint, cmdEcho)
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
out := new(bytes.Buffer)
// We generate on s subcommand so we have both subcommands and parents
if err := GenReST(cmdEcho, out); err != nil {
t.Fatal(err) t.Fatal(err)
} }
found := out.String() output := buf.String()
// Our description checkStringContains(t, output, echoCmd.Long)
expected := cmdEcho.Long checkStringContains(t, output, echoCmd.Example)
if !strings.Contains(found, expected) { checkStringContains(t, output, "boolone")
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) checkStringContains(t, output, "rootflag")
} checkStringContains(t, output, rootCmd.Short)
checkStringContains(t, output, echoSubCmd.Short)
// Better have our example checkStringOmits(t, output, deprecatedCmd.Short)
expected = cmdEcho.Example
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// A local flag
expected = "boolone"
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// persistent flag on parent
expected = "rootflag"
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// We better output info about our parent
expected = cmdRootWithRun.Short
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// And about subcommands
expected = cmdEchoSub.Short
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
unexpected := cmdDeprecated.Short
if strings.Contains(found, unexpected) {
t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)
}
} }
func TestGenRSTNoTag(t *testing.T) { func TestGenRSTNoTag(t *testing.T) {
c := initializeWithRootCmd() rootCmd.DisableAutoGenTag = true
// Need two commands to run the command alphabetical sort defer func() { rootCmd.DisableAutoGenTag = false }()
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
c.AddCommand(cmdPrint, cmdEcho)
c.DisableAutoGenTag = true
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
out := new(bytes.Buffer)
if err := GenReST(c, out); err != nil { buf := new(bytes.Buffer)
if err := GenReST(rootCmd, buf); err != nil {
t.Fatal(err) t.Fatal(err)
} }
found := out.String() output := buf.String()
unexpected := "Auto generated" unexpected := "Auto generated"
checkStringOmits(t, found, unexpected) checkStringOmits(t, output, unexpected)
} }
func TestGenRSTTree(t *testing.T) { func TestGenRSTTree(t *testing.T) {
cmd := &cobra.Command{ c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
Use: "do [OPTIONS] arg1 arg2",
}
tmpdir, err := ioutil.TempDir("", "test-gen-rst-tree") tmpdir, err := ioutil.TempDir("", "test-gen-rst-tree")
if err != nil { if err != nil {
t.Fatalf("Failed to create tmpdir: %s", err.Error()) t.Fatalf("Failed to create tmpdir: %s", err.Error())
} }
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
if err := GenReSTTree(cmd, tmpdir); err != nil { if err := GenReSTTree(c, tmpdir); err != nil {
t.Fatalf("GenReSTTree failed: %s", err.Error()) t.Fatalf("GenReSTTree failed: %s", err.Error())
} }
@ -107,7 +60,6 @@ func TestGenRSTTree(t *testing.T) {
} }
func BenchmarkGenReSTToFile(b *testing.B) { func BenchmarkGenReSTToFile(b *testing.B) {
c := initializeWithRootCmd()
file, err := ioutil.TempFile("", "") file, err := ioutil.TempFile("", "")
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
@ -117,7 +69,7 @@ func BenchmarkGenReSTToFile(b *testing.B) {
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
if err := GenReST(c, file); err != nil { if err := GenReST(rootCmd, file); err != nil {
b.Fatal(err) b.Fatal(err)
} }
} }

View File

@ -5,92 +5,42 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
func TestGenYamlDoc(t *testing.T) { func TestGenYamlDoc(t *testing.T) {
c := initializeWithRootCmd()
// Need two commands to run the command alphabetical sort
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
c.AddCommand(cmdPrint, cmdEcho)
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
out := new(bytes.Buffer)
// We generate on s subcommand so we have both subcommands and parents // We generate on s subcommand so we have both subcommands and parents
if err := GenYaml(cmdEcho, out); err != nil { buf := new(bytes.Buffer)
if err := GenYaml(echoCmd, buf); err != nil {
t.Fatal(err) t.Fatal(err)
} }
found := out.String() output := buf.String()
// Our description checkStringContains(t, output, echoCmd.Long)
expected := cmdEcho.Long checkStringContains(t, output, echoCmd.Example)
if !strings.Contains(found, expected) { checkStringContains(t, output, "boolone")
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) checkStringContains(t, output, "rootflag")
} checkStringContains(t, output, rootCmd.Short)
checkStringContains(t, output, echoSubCmd.Short)
// Better have our example
expected = cmdEcho.Example
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// A local flag
expected = "boolone"
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// persistent flag on parent
expected = "rootflag"
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// We better output info about our parent
expected = cmdRootWithRun.Short
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
// And about subcommands
expected = cmdEchoSub.Short
if !strings.Contains(found, expected) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
}
unexpected := cmdDeprecated.Short
if strings.Contains(found, unexpected) {
t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)
}
} }
func TestGenYamlNoTag(t *testing.T) { func TestGenYamlNoTag(t *testing.T) {
c := initializeWithRootCmd() rootCmd.DisableAutoGenTag = true
// Need two commands to run the command alphabetical sort defer func() { rootCmd.DisableAutoGenTag = false }()
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
c.AddCommand(cmdPrint, cmdEcho)
c.DisableAutoGenTag = true
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
out := new(bytes.Buffer)
if err := GenYaml(c, out); err != nil { buf := new(bytes.Buffer)
if err := GenYaml(rootCmd, buf); err != nil {
t.Fatal(err) t.Fatal(err)
} }
found := out.String() output := buf.String()
unexpected := "Auto generated"
checkStringOmits(t, found, unexpected)
checkStringOmits(t, output, "Auto generated")
} }
func TestGenYamlTree(t *testing.T) { func TestGenYamlTree(t *testing.T) {
cmd := &cobra.Command{ c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
Use: "do [OPTIONS] arg1 arg2",
}
tmpdir, err := ioutil.TempDir("", "test-gen-yaml-tree") tmpdir, err := ioutil.TempDir("", "test-gen-yaml-tree")
if err != nil { if err != nil {
@ -98,7 +48,7 @@ func TestGenYamlTree(t *testing.T) {
} }
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
if err := GenYamlTree(cmd, tmpdir); err != nil { if err := GenYamlTree(c, tmpdir); err != nil {
t.Fatalf("GenYamlTree failed: %s", err.Error()) t.Fatalf("GenYamlTree failed: %s", err.Error())
} }
@ -108,7 +58,6 @@ func TestGenYamlTree(t *testing.T) {
} }
func BenchmarkGenYamlToFile(b *testing.B) { func BenchmarkGenYamlToFile(b *testing.B) {
c := initializeWithRootCmd()
file, err := ioutil.TempFile("", "") file, err := ioutil.TempFile("", "")
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
@ -118,7 +67,7 @@ func BenchmarkGenYamlToFile(b *testing.B) {
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
if err := GenYaml(c, file); err != nil { if err := GenYaml(rootCmd, file); err != nil {
b.Fatal(err) b.Fatal(err)
} }
} }