expr.c 2.51 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2 3 4 5
#include "util/debug.h"
#include "util/expr.h"
#include "tests.h"
#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 12
{
	double val;

13
	if (expr__parse(&val, ctx, e, 1))
14 15 16 17 18
		TEST_ASSERT_VAL("parse test failed", 0);
	TEST_ASSERT_VAL("unexpected value", val == val2);
	return 0;
}

19
int test__expr(struct test *t __maybe_unused, int subtest __maybe_unused)
20 21
{
	const char *p;
22 23
	double val, *val_ptr;
	int ret;
24
	struct expr_parse_ctx ctx;
25 26

	expr__ctx_init(&ctx);
27 28
	expr__add_id(&ctx, strdup("FOO"), 1);
	expr__add_id(&ctx, strdup("BAR"), 2);
29 30 31 32 33 34

	ret = test(&ctx, "1+1", 2);
	ret |= test(&ctx, "FOO+BAR", 3);
	ret |= test(&ctx, "(BAR/2)%2", 1);
	ret |= test(&ctx, "1 - -4",  5);
	ret |= test(&ctx, "(FOO-1)*2 + (BAR/2)%2 - -4",  5);
35 36 37 38 39
	ret |= test(&ctx, "1-1 | 1", 1);
	ret |= test(&ctx, "1-1 & 1", 0);
	ret |= test(&ctx, "min(1,2) + 1", 2);
	ret |= test(&ctx, "max(1,2) + 1", 3);
	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 43
	ret |= test(&ctx, "d_ratio(1, 2)", 0.5);
	ret |= test(&ctx, "d_ratio(2.5, 0)", 0);
44 45 46 47 48 49
	ret |= test(&ctx, "1.1 < 2.2", 1);
	ret |= test(&ctx, "2.2 > 1.1", 1);
	ret |= test(&ctx, "1.1 < 1.1", 0);
	ret |= test(&ctx, "2.2 > 2.2", 0);
	ret |= test(&ctx, "2.2 < 1.1", 0);
	ret |= test(&ctx, "1.1 > 2.2", 0);
50 51 52 53 54

	if (ret)
		return ret;

	p = "FOO/0";
55
	ret = expr__parse(&val, &ctx, p, 1);
56
	TEST_ASSERT_VAL("division by zero", ret == -1);
57 58

	p = "BAR/";
59
	ret = expr__parse(&val, &ctx, p, 1);
60
	TEST_ASSERT_VAL("missing operand", ret == -1);
61

62
	expr__ctx_clear(&ctx);
63
	TEST_ASSERT_VAL("find other",
64 65 66 67 68 69 70 71 72
			expr__find_other("FOO + BAR + BAZ + BOZO", "FOO",
					 &ctx, 1) == 0);
	TEST_ASSERT_VAL("find other", hashmap__size(&ctx.ids) == 3);
	TEST_ASSERT_VAL("find other", hashmap__find(&ctx.ids, "BAR",
						    (void **)&val_ptr));
	TEST_ASSERT_VAL("find other", hashmap__find(&ctx.ids, "BAZ",
						    (void **)&val_ptr));
	TEST_ASSERT_VAL("find other", hashmap__find(&ctx.ids, "BOZO",
						    (void **)&val_ptr));
73

74
	expr__ctx_clear(&ctx);
75
	TEST_ASSERT_VAL("find other",
76 77 78 79 80 81 82
			expr__find_other("EVENT1\\,param\\=?@ + EVENT2\\,param\\=?@",
					 NULL, &ctx, 3) == 0);
	TEST_ASSERT_VAL("find other", hashmap__size(&ctx.ids) == 2);
	TEST_ASSERT_VAL("find other", hashmap__find(&ctx.ids, "EVENT1,param=3/",
						    (void **)&val_ptr));
	TEST_ASSERT_VAL("find other", hashmap__find(&ctx.ids, "EVENT2,param=3/",
						    (void **)&val_ptr));
83

84
	expr__ctx_clear(&ctx);
85 86 87

	return 0;
}