2017-07-28 00:11:37 +02:00
|
|
|
package values
|
2017-07-08 15:08:06 +02:00
|
|
|
|
|
|
|
import (
|
2017-07-19 16:49:39 +02:00
|
|
|
"fmt"
|
2017-07-08 15:08:06 +02:00
|
|
|
"reflect"
|
2017-07-26 09:06:57 +02:00
|
|
|
"strings"
|
2017-07-08 15:08:06 +02:00
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestCall(t *testing.T) {
|
|
|
|
fn := func(a, b string) string {
|
|
|
|
return a + "," + b + "."
|
|
|
|
}
|
|
|
|
value, err := Call(reflect.ValueOf(fn), []interface{}{5, 10})
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, "5,10.", value)
|
|
|
|
|
2017-07-26 09:06:57 +02:00
|
|
|
// extra arguments (variadic)
|
|
|
|
fnVaridic := func(a string, b ...string) string {
|
|
|
|
return a + "," + strings.Join(b, ",") + "."
|
|
|
|
}
|
|
|
|
value, err = Call(reflect.ValueOf(fnVaridic), []interface{}{5, 10})
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, "5,10.", value)
|
|
|
|
value, err = Call(reflect.ValueOf(fnVaridic), []interface{}{5, 10, 15, 20})
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, "5,10,15,20.", value)
|
|
|
|
|
|
|
|
// extra arguments (non variadic)
|
2017-07-16 19:47:06 +02:00
|
|
|
_, err = Call(reflect.ValueOf(fn), []interface{}{5, 10, 20})
|
|
|
|
require.Error(t, err)
|
|
|
|
require.Contains(t, err.Error(), "wrong number of arguments")
|
|
|
|
require.Contains(t, err.Error(), "given 3")
|
|
|
|
require.Contains(t, err.Error(), "expected 2")
|
2017-07-08 15:08:06 +02:00
|
|
|
|
2017-07-19 16:49:39 +02:00
|
|
|
// error return
|
|
|
|
fn2 := func(int) (int, error) { return 0, fmt.Errorf("expected error") }
|
|
|
|
_, err = Call(reflect.ValueOf(fn2), []interface{}{2})
|
|
|
|
require.Error(t, err)
|
|
|
|
require.Contains(t, err.Error(), "expected error")
|
2017-07-08 15:08:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestCall_optional(t *testing.T) {
|
|
|
|
fn := func(a string, b func(string) string) string {
|
|
|
|
return a + "," + b("default") + "."
|
|
|
|
}
|
|
|
|
value, err := Call(reflect.ValueOf(fn), []interface{}{5})
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, "5,default.", value)
|
|
|
|
|
|
|
|
value, err = Call(reflect.ValueOf(fn), []interface{}{5, 10})
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, "5,10.", value)
|
|
|
|
}
|