spf13--cobra/cobra_test.go

59 lines
1.2 KiB
Go
Raw Normal View History

package cobra
2013-09-03 18:54:51 -04:00
import (
2022-05-09 18:11:52 +01:00
"errors"
2013-09-03 18:54:51 -04:00
"testing"
"text/template"
2013-09-03 18:54:51 -04:00
)
func assertNoErr(t *testing.T, e error) {
if e != nil {
t.Error(e)
}
}
func TestAddTemplateFunctions(t *testing.T) {
AddTemplateFunc("t", func() bool { return true })
AddTemplateFuncs(template.FuncMap{
"f": func() bool { return false },
"h": func() string { return "Hello," },
"w": func() string { return "world." }})
c := &Command{}
c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)
2017-10-31 19:58:37 +01:00
const expected = "Hello, world."
if got := c.UsageString(); got != expected {
t.Errorf("Expected UsageString: %v\nGot: %v", expected, got)
}
}
2022-05-09 18:11:52 +01:00
func Test_OnInitialize(t *testing.T) {
call := false
c := &Command{Use: "c", Run: emptyRun}
OnInitialize(func() {
call = true
})
_, err := executeCommand(c)
2022-05-12 17:31:26 +01:00
initializers = nil
2022-05-09 18:11:52 +01:00
if err != nil {
t.Error(err)
}
if !call {
t.Error("expected OnInitialize func to be called")
}
}
func Test_OnInitializeE(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
e := errors.New("test error")
OnInitializeE(func() error {
return e
})
_, err := executeCommand(c)
2022-05-12 17:31:26 +01:00
initializersE = nil
2022-05-09 18:11:52 +01:00
if err != e {
t.Error("expected error: %w", e)
}
}