expr.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "util/debug.h"
  2. #include "util/expr.h"
  3. #include "tests.h"
  4. #include <stdlib.h>
  5. static int test(struct parse_ctx *ctx, const char *e, double val2)
  6. {
  7. double val;
  8. if (expr__parse(&val, ctx, &e))
  9. TEST_ASSERT_VAL("parse test failed", 0);
  10. TEST_ASSERT_VAL("unexpected value", val == val2);
  11. return 0;
  12. }
  13. int test__expr(int subtest __maybe_unused)
  14. {
  15. const char *p;
  16. const char **other;
  17. double val;
  18. int ret;
  19. struct parse_ctx ctx;
  20. int num_other;
  21. expr__ctx_init(&ctx);
  22. expr__add_id(&ctx, "FOO", 1);
  23. expr__add_id(&ctx, "BAR", 2);
  24. ret = test(&ctx, "1+1", 2);
  25. ret |= test(&ctx, "FOO+BAR", 3);
  26. ret |= test(&ctx, "(BAR/2)%2", 1);
  27. ret |= test(&ctx, "1 - -4", 5);
  28. ret |= test(&ctx, "(FOO-1)*2 + (BAR/2)%2 - -4", 5);
  29. if (ret)
  30. return ret;
  31. p = "FOO/0";
  32. ret = expr__parse(&val, &ctx, &p);
  33. TEST_ASSERT_VAL("division by zero", ret == 1);
  34. p = "BAR/";
  35. ret = expr__parse(&val, &ctx, &p);
  36. TEST_ASSERT_VAL("missing operand", ret == 1);
  37. TEST_ASSERT_VAL("find other",
  38. expr__find_other("FOO + BAR + BAZ + BOZO", "FOO", &other, &num_other) == 0);
  39. TEST_ASSERT_VAL("find other", num_other == 3);
  40. TEST_ASSERT_VAL("find other", !strcmp(other[0], "BAR"));
  41. TEST_ASSERT_VAL("find other", !strcmp(other[1], "BAZ"));
  42. TEST_ASSERT_VAL("find other", !strcmp(other[2], "BOZO"));
  43. TEST_ASSERT_VAL("find other", other[3] == NULL);
  44. free((void *)other);
  45. return 0;
  46. }