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