expr_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package expr
  2. import (
  3. "fmt"
  4. "testing"
  5. )
  6. func TestExpr(t *testing.T) {
  7. tests := []struct {
  8. expr string
  9. env Env
  10. want string
  11. }{
  12. {"$1 > 80 && $2 <9", Env{"$1": 100, "$2": 2}, "true"},
  13. {"$1 % 10", Env{"$1": 104, "$2": 2}, "4"},
  14. {"pow(x, false) + pow(y, false)", Env{"x": 12, "y": 1}, "2"},
  15. {"pow(x, 3) + pow(y, 3)", Env{"x": 9, "y": 10}, "1729"},
  16. {"5.0 / 9 * (F - 32)", Env{"F": -40}, "-40"},
  17. {"5.0 / 9 * (F - 32)", Env{"F": 32}, "0"},
  18. {"5.0 / 9 * (F - 32)", Env{"F": 212}, "100"},
  19. ////!-Eval
  20. //// additional tests that don't appear in the book
  21. {"-1 + -x", Env{"x": 1}, "-2"},
  22. {"-1 - x", Env{"x": 1}, "-2"},
  23. {"a >= 10", Env{"a": 15}, "true"},
  24. {"b >= sin(10) && a < 1", Env{"a": 9, "b": 10}, "false"},
  25. {"!!!true", Env{"a": 9, "b": 10}, "false"},
  26. //!+Eval
  27. }
  28. var prevExpr string
  29. parser := NewExpressionParser()
  30. for _, test := range tests {
  31. // Print expr only when it changes.
  32. if test.expr != prevExpr {
  33. t.Logf("\n%s\n", test.expr)
  34. prevExpr = test.expr
  35. }
  36. if err := parser.Parse(test.expr); err != nil {
  37. t.Error(err) // parse error
  38. continue
  39. }
  40. got := fmt.Sprintf("%v", parser.GetExpr().Eval(test.env))
  41. t.Logf("\t%v => %s\n", test.env, got)
  42. if got != test.want {
  43. t.Errorf("%s.Eval() in %v = %q, want %q\n",
  44. test.expr, test.env, got, test.want)
  45. }
  46. }
  47. }