Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added MustEvaluate which turns panics into errors + tests #17

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions evaluator.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package goval

import (
"fmt"

"github.com/maja42/goval/internal"
)

Expand Down Expand Up @@ -30,3 +32,24 @@ type ExpressionFunction = func(args ...interface{}) (interface{}, error)
func (e *Evaluator) Evaluate(str string, variables map[string]interface{}, functions map[string]ExpressionFunction) (result interface{}, err error) {
return internal.Evaluate(str, variables, functions)
}

// MustEvaluate evaluates the given expression string.
//
// Never panics: instead turns any panic into an error (e.g., division by zero).
//
// Optionally accepts a list of variables (accessible but not modifiable from within expressions).
//
// Optionally accepts a list of expression functions (can be called from within expressions).
//
// Returns the resulting object or an error.
//
// Stateless. Can be called concurrently. If expression functions modify variables, concurrent execution requires additional synchronization.
func (e *Evaluator) MustEvaluate(str string, variables map[string]interface{}, functions map[string]ExpressionFunction) (result interface{}, err error) {
defer func() {
if r := recover(); r != nil {
result = nil
err = fmt.Errorf("%v", r)
}
}()
return internal.Evaluate(str, variables, functions)
}
22 changes: 21 additions & 1 deletion evaluator_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package goval

import (
"github.com/stretchr/testify/assert"
"testing"

"github.com/stretchr/testify/assert"
)

func Test_Evaluator(t *testing.T) {
Expand All @@ -20,3 +21,22 @@ func Test_Evaluator(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, 42, result)
}

func Test_MustEvaluator(t *testing.T) {
variables := map[string]interface{}{
"var": 21,
}
functions := map[string]ExpressionFunction{
"func": func(args ...interface{}) (interface{}, error) {
return args[0], nil
},
}

evaluator := NewEvaluator()
result, err := evaluator.MustEvaluate("func( var ) + 21", variables, functions)
assert.NoError(t, err)
assert.Equal(t, 42, result)
result, err = evaluator.MustEvaluate("1/0", variables, functions)
assert.Nil(t, result)
assert.NotNil(t, err)
}