expr_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package expr
  2. import (
  3. "fmt"
  4. "testing"
  5. )
  6. func TestExpr(t *testing.T) {
  7. defer func() {
  8. switch x := recover().(type) {
  9. case nil:
  10. // no panic
  11. case runtimePanic:
  12. fmt.Println(x)
  13. panic(x)
  14. default:
  15. // unexpected panic: resume state of panic.
  16. panic(x)
  17. }
  18. }()
  19. tests := []struct {
  20. expr string
  21. env Env
  22. want string
  23. }{
  24. {`$x == "android"`, Env{"$x": "android"}, "true"},
  25. {"$x == `android`", Env{"$x": "android"}, "true"},
  26. {"to_lower($x) == `android`", Env{"$x": "AnDroId"}, "true"},
  27. {"to_lower($x) == `android`", Env{"$x": "iOS"}, "false"},
  28. {"log($1 + 9 * $1)", Env{"$1": 100}, "3"},
  29. {"$1 > 80 && $2 <9", Env{"$1": 100, "$2": 2}, "true"},
  30. {"pow(x, false) + pow(y, false)", Env{"x": 12, "y": 1}, "2"},
  31. {"pow(x, 3) + pow(y, 3)", Env{"x": 9, "y": 10}, "1729"},
  32. {"9 * (F - 32)/5", Env{"F": -40}, "-129"},
  33. {"-1 + -x", Env{"x": 1}, "-2"},
  34. {"-1 - x", Env{"x": 1}, "-2"},
  35. {"a >= 10", Env{"a": 15}, "true"},
  36. {"b >= sin(10) && a < 1", Env{"a": 9, "b": 10}, "false"},
  37. {"!!!true", Env{"a": 9, "b": 10}, "false"},
  38. }
  39. var prevExpr string
  40. parser := NewExpressionParser()
  41. for _, test := range tests {
  42. // Print expr only when it changes.
  43. if test.expr != prevExpr {
  44. t.Logf("\n%s\n", test.expr)
  45. prevExpr = test.expr
  46. }
  47. if err := parser.Parse(test.expr); err != nil {
  48. t.Error(err) // parse error
  49. continue
  50. }
  51. got := fmt.Sprintf("%v", parser.GetExpr().Eval(test.env))
  52. t.Logf("%s\t%v => %s\n", test.expr, test.env, got)
  53. if got != test.want {
  54. t.Errorf("%s.Eval() in %v = %q, want %q\n",
  55. test.expr, test.env, got, test.want)
  56. }
  57. }
  58. }