feat: call function

This commit is contained in:
debugtalk
2021-10-03 10:04:29 +08:00
parent dd0b2d3aa4
commit a2cc1fae7f
3 changed files with 51 additions and 0 deletions

11
builtin/function.go Normal file
View File

@@ -0,0 +1,11 @@
package builtin
import "time"
var FunctionsMap = map[string]interface{}{
"sleep": Sleep,
}
func Sleep(nSecs int) {
time.Sleep(time.Duration(nSecs) * time.Second)
}

View File

@@ -7,6 +7,8 @@ import (
"reflect"
"regexp"
"strings"
"github.com/httprunner/httpboomer/builtin"
)
func parseStep(step IStep, config *TConfig) *TStep {
@@ -166,3 +168,27 @@ func mergeVariables(variables, overriddenVariables map[string]interface{}) map[s
}
return mergedVariables
}
func callFunction(funcName string, params []interface{}) (interface{}, error) {
function, ok := builtin.FunctionsMap[funcName]
if !ok {
// function not found
return nil, fmt.Errorf("function %s is not found", funcName)
}
funcValue := reflect.ValueOf(function)
if funcValue.Kind() != reflect.Func {
// function not valid
return nil, fmt.Errorf("function %s is invalid", funcName)
}
paramsValue := make([]reflect.Value, len(params))
for index, param := range params {
paramsValue[index] = reflect.ValueOf(param)
}
log.Printf("[callFunction] function: %v, params: %v", funcName, params)
result := funcValue.Call(paramsValue)
log.Printf("[callFunction] result: %v", result)
return result, nil
}

View File

@@ -2,6 +2,7 @@ package httpboomer
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
@@ -278,3 +279,16 @@ func TestMergeVariables(t *testing.T) {
t.Fail()
}
}
func TestCallFunction(t *testing.T) {
funcName := "sleep"
params := []interface{}{1}
timeStart := time.Now()
_, err := callFunction(funcName, params)
if !assert.Nil(t, err) {
t.Fail()
}
if !assert.Greater(t, time.Since(timeStart), time.Duration(1)*time.Second) {
t.Fail()
}
}