valuate_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package valuate
  2. import (
  3. "fmt"
  4. "testing"
  5. "github.com/Knetic/govaluate"
  6. "github.com/spf13/cast"
  7. )
  8. func TestExpression1(t *testing.T) {
  9. expr, err := govaluate.NewEvaluableExpression("(requests_made * requests_succeeded / 100) >= 90")
  10. if err != nil {
  11. t.Error(err)
  12. }
  13. params := make(map[string]any, 8)
  14. params["requests_made"] = 100
  15. params["requests_succeeded"] = 80
  16. result, err := expr.Evaluate(params)
  17. fmt.Println(result, err)
  18. }
  19. func testExpression() {
  20. expression, _ := govaluate.NewEvaluableExpression("(mem_used / total_mem) * 100")
  21. parameters := map[string]any{
  22. "total_mem": 1024,
  23. "mem_used": 512,
  24. }
  25. evaluate, err := expression.Evaluate(parameters)
  26. if err != nil {
  27. return
  28. }
  29. result := cast.ToInt32(evaluate)
  30. fmt.Println(result)
  31. }
  32. func TestExpression2(t *testing.T) {
  33. testExpression()
  34. }
  35. func BenchmarkEvaluate(b *testing.B) {
  36. for i := 0; i < b.N; i++ {
  37. testExpression()
  38. }
  39. }
  40. func BenchmarkEvaluate1(b *testing.B) {
  41. var x float64
  42. for i := 0; i < b.N; i++ {
  43. x = (1024 / 512) * 100
  44. }
  45. if x == 300 {
  46. fmt.Println(x)
  47. }
  48. }
  49. func testFunction() {
  50. functions := map[string]govaluate.ExpressionFunction{
  51. "strlen": func(args ...any) (any, error) {
  52. length := len(args[0].(string))
  53. return (float64)(length), nil
  54. },
  55. }
  56. expString := "strlen('someReallyLongInputString') <= 16"
  57. expression, _ := govaluate.NewEvaluableExpressionWithFunctions(expString, functions)
  58. //result, err := expression.Evaluate(nil)
  59. //fmt.Println(result, err)
  60. expression.Evaluate(nil)
  61. }
  62. func TestFunction(t *testing.T) {
  63. testFunction()
  64. }
  65. func BenchmarkFunction(b *testing.B) {
  66. for i := 0; i < b.N; i++ {
  67. testFunction()
  68. }
  69. }