Skip to content

Commit 38ed534

Browse files
committed
Fix: checker to correctly expect type cast with As*() modifiers
1 parent e92442f commit 38ed534

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

checker/checker.go

+9-3
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,19 @@ func Check(tree *parser.Tree, config *conf.Config) (t reflect.Type, err error) {
3232
if v.config.Expect != reflect.Invalid {
3333
switch v.config.Expect {
3434
case reflect.Int, reflect.Int64, reflect.Float64:
35-
if !isNumber(t) {
35+
if !isNumber(t) && !isAny(t) {
3636
return nil, fmt.Errorf("expected %v, but got %v", v.config.Expect, t)
3737
}
3838
default:
39-
if t == nil || t.Kind() != v.config.Expect {
40-
return nil, fmt.Errorf("expected %v, but got %v", v.config.Expect, t)
39+
if t != nil {
40+
if t.Kind() == reflect.Interface {
41+
t = t.Elem()
42+
}
43+
if t.Kind() == v.config.Expect {
44+
return t, nil
45+
}
4146
}
47+
return nil, fmt.Errorf("expected %v, but got %v", v.config.Expect, t)
4248
}
4349
}
4450

checker/checker_test.go

+32
Original file line numberDiff line numberDiff line change
@@ -745,3 +745,35 @@ func TestCheck_works_with_nil_types(t *testing.T) {
745745
_, err = checker.Check(tree, conf.New(env))
746746
require.NoError(t, err)
747747
}
748+
749+
func TestCheck_cast_to_expected_works_with_interface(t *testing.T) {
750+
t.Run("float64", func(t *testing.T) {
751+
type Env struct {
752+
Any interface{}
753+
}
754+
755+
tree, err := parser.Parse("Any")
756+
require.NoError(t, err)
757+
758+
config := conf.New(Env{})
759+
expr.AsFloat64()(config)
760+
761+
_, err = checker.Check(tree, config)
762+
require.NoError(t, err)
763+
})
764+
765+
t.Run("kind", func(t *testing.T) {
766+
env := map[string]interface{}{
767+
"Any": interface{}("foo"),
768+
}
769+
770+
tree, err := parser.Parse("Any")
771+
require.NoError(t, err)
772+
773+
config := conf.New(env)
774+
expr.AsKind(reflect.String)(config)
775+
776+
_, err = checker.Check(tree, config)
777+
require.NoError(t, err)
778+
})
779+
}

0 commit comments

Comments
 (0)