1 /*
2  * Copyright (c) 2024 Mustafa Abdullah Kus, Sparse Technology
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/ztest.h>
8 
9 #include <zephyr/net/prometheus/counter.h>
10 #include <zephyr/net/prometheus/collector.h>
11 #include <zephyr/net/prometheus/formatter.h>
12 
13 #define MAX_BUFFER_SIZE 256
14 
15 PROMETHEUS_COUNTER_DEFINE(test_counter, "Test counter",
16 			  ({ .key = "test", .value = "counter" }), NULL);
17 PROMETHEUS_COUNTER_DEFINE(test_counter2, "Test counter 2",
18 			  ({ .key = "test", .value = "counter" }), NULL);
19 
20 PROMETHEUS_COLLECTOR_DEFINE(test_custom_collector);
21 
22 /**
23  * @brief Test Prometheus formatter
24  * @details The test shall increment the counter value by 1 and check if the
25  * value is incremented correctly. It shall then format the metric and compare
26  * it with the expected output.
27  */
ZTEST(test_formatter,test_prometheus_formatter_simple)28 ZTEST(test_formatter, test_prometheus_formatter_simple)
29 {
30 	int ret;
31 	char formatted[MAX_BUFFER_SIZE] = { 0 };
32 	struct prometheus_counter *counter;
33 	char exposed[] = "# HELP test_counter2 Test counter 2\n"
34 			 "# TYPE test_counter2 counter\n"
35 			 "test_counter2{test=\"counter\"} 1\n"
36 			 "# HELP test_counter Test counter\n"
37 			 "# TYPE test_counter counter\n"
38 			 "test_counter{test=\"counter\"} 1\n";
39 
40 	prometheus_collector_register_metric(&test_custom_collector, &test_counter.base);
41 	prometheus_collector_register_metric(&test_custom_collector, &test_counter2.base);
42 
43 	counter = (struct prometheus_counter *)prometheus_collector_get_metric(
44 		&test_custom_collector, "test_counter");
45 
46 	zassert_equal(counter, &test_counter, "Counter not found in collector");
47 
48 	zassert_equal(test_counter.value, 0, "Counter value is not 0");
49 
50 	ret = prometheus_counter_inc(&test_counter);
51 	zassert_ok(ret, "Error incrementing counter");
52 
53 	ret = prometheus_counter_inc(&test_counter2);
54 	zassert_ok(ret, "Error incrementing counter 2");
55 
56 	zassert_equal(counter->value, 1, "Counter value is not 1");
57 
58 	ret = prometheus_format_exposition(&test_custom_collector, formatted, sizeof(formatted));
59 	zassert_ok(ret, "Error formatting exposition data");
60 
61 	zassert_equal(strcmp(formatted, exposed), 0,
62 		      "Exposition format is not as expected (expected\n\"%s\", got\n\"%s\")",
63 		      exposed, formatted);
64 }
65 
66 ZTEST_SUITE(test_formatter, NULL, NULL, NULL, NULL, NULL);
67