Files
kong/options_test.go
T
Alec Thomas bf0cbf5d7c feat: Embed() option and Context.Call()
The former allows arbitrary structs to be embedded in the root of the
CLI, with optional tags.

The latter allows an arbitrary function to be called using Kong's
binding functionality.
2022-11-22 23:34:56 +11:00

115 lines
2.4 KiB
Go

package kong
import (
"reflect"
"testing"
"github.com/alecthomas/assert/v2"
)
func TestOptions(t *testing.T) {
var cli struct{}
p, err := New(&cli, Name("name"), Description("description"), Writers(nil, nil), Exit(nil))
assert.NoError(t, err)
assert.Equal(t, "name", p.Model.Name)
assert.Equal(t, "description", p.Model.Help)
assert.Zero(t, p.Stdout)
assert.Zero(t, p.Stderr)
assert.Zero(t, p.Exit)
}
type impl string
func (impl) Method() {}
func TestBindTo(t *testing.T) {
type iface interface {
Method()
}
saw := ""
method := func(i iface) error {
saw = string(i.(impl)) // nolint
return nil
}
var cli struct{}
p, err := New(&cli, BindTo(impl("foo"), (*iface)(nil)))
assert.NoError(t, err)
err = callMethod("method", reflect.ValueOf(impl("??")), reflect.ValueOf(method), p.bindings)
assert.NoError(t, err)
assert.Equal(t, "foo", saw)
}
func TestInvalidCallback(t *testing.T) {
type iface interface {
Method()
}
saw := ""
method := func(i iface) string {
saw = string(i.(impl)) // nolint
return saw
}
var cli struct{}
p, err := New(&cli, BindTo(impl("foo"), (*iface)(nil)))
assert.NoError(t, err)
err = callMethod("method", reflect.ValueOf(impl("??")), reflect.ValueOf(method), p.bindings)
assert.EqualError(t, err, `kong.impl.method(): return value of func(kong.iface) string must implement "error"`)
}
type zrror struct{}
func (*zrror) Error() string {
return "error"
}
func TestCallbackCustomError(t *testing.T) {
type iface interface {
Method()
}
saw := ""
method := func(i iface) *zrror {
saw = string(i.(impl)) // nolint
return nil
}
var cli struct{}
p, err := New(&cli, BindTo(impl("foo"), (*iface)(nil)))
assert.NoError(t, err)
err = callMethod("method", reflect.ValueOf(impl("??")), reflect.ValueOf(method), p.bindings)
assert.NoError(t, err)
assert.Equal(t, "foo", saw)
}
type bindToProviderCLI struct {
Called bool
Cmd bindToProviderCmd `cmd:""`
}
type boundThing struct {
}
type bindToProviderCmd struct{}
func (*bindToProviderCmd) Run(cli *bindToProviderCLI, b *boundThing) error {
cli.Called = true
return nil
}
func TestBindToProvider(t *testing.T) {
var cli bindToProviderCLI
app, err := New(&cli, BindToProvider(func() (*boundThing, error) { return &boundThing{}, nil }))
assert.NoError(t, err)
ctx, err := app.Parse([]string{"cmd"})
assert.NoError(t, err)
err = ctx.Run()
assert.NoError(t, err)
assert.True(t, cli.Called)
}