2013-09-24 17:04:00 -04:00
|
|
|
package cobra
|
2013-09-03 18:54:51 -04:00
|
|
|
|
|
|
|
import (
|
2021-12-21 15:08:30 +01:00
|
|
|
"errors"
|
2013-09-03 18:54:51 -04:00
|
|
|
"testing"
|
2015-08-31 22:36:55 -05:00
|
|
|
"text/template"
|
2013-09-03 18:54:51 -04:00
|
|
|
)
|
|
|
|
|
2021-02-08 00:08:50 +00:00
|
|
|
func assertNoErr(t *testing.T, e error) {
|
|
|
|
if e != nil {
|
|
|
|
t.Error(e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-08-31 22:36:55 -05:00
|
|
|
func TestAddTemplateFunctions(t *testing.T) {
|
|
|
|
AddTemplateFunc("t", func() bool { return true })
|
|
|
|
AddTemplateFuncs(template.FuncMap{
|
2015-09-04 14:34:51 -06:00
|
|
|
"f": func() bool { return false },
|
|
|
|
"h": func() string { return "Hello," },
|
2015-08-31 22:36:55 -05:00
|
|
|
"w": func() string { return "world." }})
|
|
|
|
|
|
|
|
c := &Command{}
|
|
|
|
c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)
|
2015-09-04 14:34:51 -06:00
|
|
|
|
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)
|
2017-04-05 18:44:50 +02:00
|
|
|
}
|
|
|
|
}
|
2021-12-21 15:08:30 +01:00
|
|
|
|
|
|
|
func TestCheckErr(t *testing.T) {
|
|
|
|
tests := []struct {
|
|
|
|
name string
|
|
|
|
msg interface{}
|
|
|
|
panic bool
|
|
|
|
}{
|
|
|
|
{
|
|
|
|
name: "no error",
|
|
|
|
msg: nil,
|
|
|
|
panic: false,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "panic string",
|
|
|
|
msg: "test",
|
|
|
|
panic: true,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "panic error",
|
|
|
|
msg: errors.New("test error"),
|
|
|
|
panic: true,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
|
|
defer func() {
|
|
|
|
r := recover()
|
|
|
|
if r != nil {
|
|
|
|
if !tt.panic {
|
|
|
|
t.Error("Didn't expect panic")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if tt.panic {
|
|
|
|
t.Error("Expected to panic")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
CheckErr(tt.msg)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|