From a2cc1fae7f6b06a1adb309ef2f42072c4c6c674e Mon Sep 17 00:00:00 2001 From: debugtalk Date: Sun, 3 Oct 2021 10:04:29 +0800 Subject: [PATCH] feat: call function --- builtin/function.go | 11 +++++++++++ parser.go | 26 ++++++++++++++++++++++++++ parser_test.go | 14 ++++++++++++++ 3 files changed, 51 insertions(+) create mode 100644 builtin/function.go diff --git a/builtin/function.go b/builtin/function.go new file mode 100644 index 00000000..8ea6792d --- /dev/null +++ b/builtin/function.go @@ -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) +} diff --git a/parser.go b/parser.go index b4ea30d9..7b8ee46d 100644 --- a/parser.go +++ b/parser.go @@ -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 +} diff --git a/parser_test.go b/parser_test.go index c1db12b3..9cd7a026 100644 --- a/parser_test.go +++ b/parser_test.go @@ -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() + } +}