mirror of
https://github.com/httprunner/httprunner.git
synced 2026-05-12 19:39:44 +08:00
feat: call function without argument
This commit is contained in:
@@ -1,15 +1,23 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"math"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
var Functions = map[string]interface{}{
|
||||
"get_timestamp": getTimestamp, // call without arguments
|
||||
"sleep": sleep, // call with one argument
|
||||
"gen_random_string": genRandomString, // call with one argument
|
||||
"max": math.Max, // call with two arguments
|
||||
"md5": MD5,
|
||||
}
|
||||
|
||||
func getTimestamp() int64 {
|
||||
return time.Now().UnixNano() / int64(time.Millisecond)
|
||||
}
|
||||
|
||||
func sleep(nSecs int) {
|
||||
@@ -26,3 +34,9 @@ func genRandomString(n int) string {
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func MD5(str string) string {
|
||||
hasher := md5.New()
|
||||
hasher.Write([]byte(str))
|
||||
return hex.EncodeToString(hasher.Sum(nil))
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ func mergeVariables(variables, overriddenVariables map[string]interface{}) map[s
|
||||
|
||||
// callFunc call function with arguments
|
||||
// only support return at most one result value
|
||||
func callFunc(funcName string, arguments []interface{}) (interface{}, error) {
|
||||
func callFunc(funcName string, arguments ...interface{}) (interface{}, error) {
|
||||
function, ok := builtin.Functions[funcName]
|
||||
if !ok {
|
||||
// function not found
|
||||
|
||||
@@ -282,10 +282,14 @@ func TestMergeVariables(t *testing.T) {
|
||||
|
||||
func TestCallFunction(t *testing.T) {
|
||||
// call function without arguments
|
||||
funcName := "sleep"
|
||||
arguments := []interface{}{1}
|
||||
_, err := callFunc("get_timestamp")
|
||||
if !assert.Nil(t, err) {
|
||||
t.Fail()
|
||||
}
|
||||
|
||||
// call function with one argument
|
||||
timeStart := time.Now()
|
||||
_, err := callFunc(funcName, arguments)
|
||||
_, err = callFunc("sleep", 1)
|
||||
if !assert.Nil(t, err) {
|
||||
t.Fail()
|
||||
}
|
||||
@@ -294,9 +298,7 @@ func TestCallFunction(t *testing.T) {
|
||||
}
|
||||
|
||||
// call function with one argument
|
||||
funcName = "gen_random_string"
|
||||
arguments = []interface{}{10}
|
||||
result, err := callFunc(funcName, arguments)
|
||||
result, err := callFunc("gen_random_string", 10)
|
||||
if !assert.Nil(t, err) {
|
||||
t.Fail()
|
||||
}
|
||||
@@ -305,9 +307,7 @@ func TestCallFunction(t *testing.T) {
|
||||
}
|
||||
|
||||
// call function with two argument
|
||||
funcName = "max"
|
||||
arguments = []interface{}{float64(10), 9.99}
|
||||
result, err = callFunc(funcName, arguments)
|
||||
result, err = callFunc("max", float64(10), 9.99)
|
||||
if !assert.Nil(t, err) {
|
||||
t.Fail()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user