xref: /openbmc/linux/tools/perf/tests/expr.c (revision 15e3ae36)
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 parse_ctx *ctx, const char *e, double val2)
10 {
11 	double val;
12 
13 	if (expr__parse(&val, ctx, e))
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 	const char **other;
23 	double val;
24 	int i, ret;
25 	struct parse_ctx ctx;
26 	int num_other;
27 
28 	expr__ctx_init(&ctx);
29 	expr__add_id(&ctx, "FOO", 1);
30 	expr__add_id(&ctx, "BAR", 2);
31 
32 	ret = test(&ctx, "1+1", 2);
33 	ret |= test(&ctx, "FOO+BAR", 3);
34 	ret |= test(&ctx, "(BAR/2)%2", 1);
35 	ret |= test(&ctx, "1 - -4",  5);
36 	ret |= test(&ctx, "(FOO-1)*2 + (BAR/2)%2 - -4",  5);
37 	ret |= test(&ctx, "1-1 | 1", 1);
38 	ret |= test(&ctx, "1-1 & 1", 0);
39 	ret |= test(&ctx, "min(1,2) + 1", 2);
40 	ret |= test(&ctx, "max(1,2) + 1", 3);
41 	ret |= test(&ctx, "1+1 if 3*4 else 0", 2);
42 
43 	if (ret)
44 		return ret;
45 
46 	p = "FOO/0";
47 	ret = expr__parse(&val, &ctx, p);
48 	TEST_ASSERT_VAL("division by zero", ret == -1);
49 
50 	p = "BAR/";
51 	ret = expr__parse(&val, &ctx, p);
52 	TEST_ASSERT_VAL("missing operand", ret == -1);
53 
54 	TEST_ASSERT_VAL("find other",
55 			expr__find_other("FOO + BAR + BAZ + BOZO", "FOO", &other, &num_other) == 0);
56 	TEST_ASSERT_VAL("find other", num_other == 3);
57 	TEST_ASSERT_VAL("find other", !strcmp(other[0], "BAR"));
58 	TEST_ASSERT_VAL("find other", !strcmp(other[1], "BAZ"));
59 	TEST_ASSERT_VAL("find other", !strcmp(other[2], "BOZO"));
60 	TEST_ASSERT_VAL("find other", other[3] == NULL);
61 
62 	for (i = 0; i < num_other; i++)
63 		zfree(&other[i]);
64 	free((void *)other);
65 
66 	return 0;
67 }
68