Skip to content

Commit

Permalink
Fix: checker to correctly expect type cast with As*() modifiers
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Jan 23, 2023
1 parent e92442f commit 38ed534
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
12 changes: 9 additions & 3 deletions checker/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,19 @@ func Check(tree *parser.Tree, config *conf.Config) (t reflect.Type, err error) {
if v.config.Expect != reflect.Invalid {
switch v.config.Expect {
case reflect.Int, reflect.Int64, reflect.Float64:
if !isNumber(t) {
if !isNumber(t) && !isAny(t) {
return nil, fmt.Errorf("expected %v, but got %v", v.config.Expect, t)
}
default:
if t == nil || t.Kind() != v.config.Expect {
return nil, fmt.Errorf("expected %v, but got %v", v.config.Expect, t)
if t != nil {
if t.Kind() == reflect.Interface {
t = t.Elem()
}
if t.Kind() == v.config.Expect {
return t, nil
}
}
return nil, fmt.Errorf("expected %v, but got %v", v.config.Expect, t)
}
}

Expand Down
32 changes: 32 additions & 0 deletions checker/checker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -745,3 +745,35 @@ func TestCheck_works_with_nil_types(t *testing.T) {
_, err = checker.Check(tree, conf.New(env))
require.NoError(t, err)
}

func TestCheck_cast_to_expected_works_with_interface(t *testing.T) {
t.Run("float64", func(t *testing.T) {
type Env struct {
Any interface{}
}

tree, err := parser.Parse("Any")
require.NoError(t, err)

config := conf.New(Env{})
expr.AsFloat64()(config)

_, err = checker.Check(tree, config)
require.NoError(t, err)
})

t.Run("kind", func(t *testing.T) {
env := map[string]interface{}{
"Any": interface{}("foo"),
}

tree, err := parser.Parse("Any")
require.NoError(t, err)

config := conf.New(env)
expr.AsKind(reflect.String)(config)

_, err = checker.Check(tree, config)
require.NoError(t, err)
})
}

0 comments on commit 38ed534

Please sign in to comment.