xref: /openbmc/linux/tools/perf/tests/expr.c (revision 3e21a28a)
1 // SPDX-License-Identifier: GPL-2.0
2 #include "util/debug.h"
3 #include "util/expr.h"
4 #include "tests.h"
5 #include <stdlib.h>
6 #include <string.h>
7 #include <linux/zalloc.h>
8 
9 static int test(struct expr_parse_ctx *ctx, const char *e, double val2)
10 {
11 	double val;
12 
13 	if (expr__parse(&val, ctx, e, 1))
14 		TEST_ASSERT_VAL("parse test failed", 0);
15 	TEST_ASSERT_VAL("unexpected value", val == val2);
16 	return 0;
17 }
18 
19 int test__expr(struct test *t __maybe_unused, int subtest __maybe_unused)
20 {
21 	const char *p;
22 	double val, *val_ptr;
23 	int ret;
24 	struct expr_parse_ctx ctx;
25 
26 	expr__ctx_init(&ctx);
27 	expr__add_id(&ctx, strdup("FOO"), 1);
28 	expr__add_id(&ctx, strdup("BAR"), 2);
29 
30 	ret = test(&ctx, "1+1", 2);
31 	ret |= test(&ctx, "FOO+BAR", 3);
32 	ret |= test(&ctx, "(BAR/2)%2", 1);
33 	ret |= test(&ctx, "1 - -4",  5);
34 	ret |= test(&ctx, "(FOO-1)*2 + (BAR/2)%2 - -4",  5);
35 	ret |= test(&ctx, "1-1 | 1", 1);
36 	ret |= test(&ctx, "1-1 & 1", 0);
37 	ret |= test(&ctx, "min(1,2) + 1", 2);
38 	ret |= test(&ctx, "max(1,2) + 1", 3);
39 	ret |= test(&ctx, "1+1 if 3*4 else 0", 2);
40 	ret |= test(&ctx, "1.1 + 2.1", 3.2);
41 	ret |= test(&ctx, ".1 + 2.", 2.1);
42 	ret |= test(&ctx, "d_ratio(1, 2)", 0.5);
43 	ret |= test(&ctx, "d_ratio(2.5, 0)", 0);
44 
45 	if (ret)
46 		return ret;
47 
48 	p = "FOO/0";
49 	ret = expr__parse(&val, &ctx, p, 1);
50 	TEST_ASSERT_VAL("division by zero", ret == -1);
51 
52 	p = "BAR/";
53 	ret = expr__parse(&val, &ctx, p, 1);
54 	TEST_ASSERT_VAL("missing operand", ret == -1);
55 
56 	expr__ctx_clear(&ctx);
57 	TEST_ASSERT_VAL("find other",
58 			expr__find_other("FOO + BAR + BAZ + BOZO", "FOO",
59 					 &ctx, 1) == 0);
60 	TEST_ASSERT_VAL("find other", hashmap__size(&ctx.ids) == 3);
61 	TEST_ASSERT_VAL("find other", hashmap__find(&ctx.ids, "BAR",
62 						    (void **)&val_ptr));
63 	TEST_ASSERT_VAL("find other", hashmap__find(&ctx.ids, "BAZ",
64 						    (void **)&val_ptr));
65 	TEST_ASSERT_VAL("find other", hashmap__find(&ctx.ids, "BOZO",
66 						    (void **)&val_ptr));
67 
68 	expr__ctx_clear(&ctx);
69 	TEST_ASSERT_VAL("find other",
70 			expr__find_other("EVENT1\\,param\\=?@ + EVENT2\\,param\\=?@",
71 					 NULL, &ctx, 3) == 0);
72 	TEST_ASSERT_VAL("find other", hashmap__size(&ctx.ids) == 2);
73 	TEST_ASSERT_VAL("find other", hashmap__find(&ctx.ids, "EVENT1,param=3/",
74 						    (void **)&val_ptr));
75 	TEST_ASSERT_VAL("find other", hashmap__find(&ctx.ids, "EVENT2,param=3/",
76 						    (void **)&val_ptr));
77 
78 	expr__ctx_clear(&ctx);
79 
80 	return 0;
81 }
82