1 /*
2  * Copyright (c) 2023 Nobleo Technology
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file
9  * @brief Test log timestamp
10  */
11 
12 #include <zephyr/logging/log.h>
13 #include <zephyr/logging/log_output.h>
14 #include <zephyr/logging/log_output_custom.h>
15 
16 #include <zephyr/tc_util.h>
17 #include <stdbool.h>
18 #include <zephyr/kernel.h>
19 #include <zephyr/ztest.h>
20 
21 #define LOG_MODULE_NAME test
22 LOG_MODULE_REGISTER(LOG_MODULE_NAME);
23 
24 #define SNAME "src"
25 #define DNAME "domain"
26 #define TEST_STR "test"
27 
28 static uint8_t mock_buffer[512];
29 static uint8_t log_output_buf[4];
30 static uint32_t mock_len;
31 
reset_mock_buffer(void)32 static void reset_mock_buffer(void)
33 {
34 	mock_len = 0U;
35 	memset(mock_buffer, 0, sizeof(mock_buffer));
36 }
37 
mock_output_func(uint8_t * buf,size_t size,void * ctx)38 static int mock_output_func(uint8_t *buf, size_t size, void *ctx)
39 {
40 	memcpy(&mock_buffer[mock_len], buf, size);
41 	mock_len += size;
42 
43 	return size;
44 }
45 
46 LOG_OUTPUT_DEFINE(log_output, mock_output_func,
47 		  log_output_buf, sizeof(log_output_buf));
48 
custom_timestamp(const struct log_output * output,const log_timestamp_t timestamp,const log_timestamp_printer_t printer)49 int custom_timestamp(const struct log_output *output,
50 				const log_timestamp_t timestamp,
51 				const log_timestamp_printer_t printer)
52 {
53 	uint8_t buffer[] = "custom-timestamp: ";
54 
55 	return printer(output, "%s", buffer);
56 }
57 
ZTEST(test_timestamp,test_custom_timestamp)58 ZTEST(test_timestamp, test_custom_timestamp)
59 {
60 	if (IS_ENABLED(CONFIG_LOG_OUTPUT_FORMAT_CUSTOM_TIMESTAMP)) {
61 		log_custom_timestamp_set(custom_timestamp);
62 	}
63 	static const char *exp_str = IS_ENABLED(CONFIG_LOG_OUTPUT_FORMAT_CUSTOM_TIMESTAMP) ?
64 			"custom-timestamp: " DNAME "/" SNAME ": " TEST_STR "\r\n" :
65 			"[00000001] " DNAME "/" SNAME ": " TEST_STR "\r\n";
66 
67 	char package[256];
68 	uint32_t flags = LOG_OUTPUT_FLAG_TIMESTAMP;
69 	int err;
70 
71 	err = cbprintf_package(package, sizeof(package), 0, TEST_STR);
72 	zassert_true(err > 0);
73 
74 	log_output_process(&log_output, 1, DNAME, SNAME, NULL, LOG_LEVEL_INF,
75 			   package, NULL, 0, flags);
76 
77 	mock_buffer[mock_len] = '\0';
78 	zassert_str_equal(exp_str, mock_buffer);
79 }
80 
before(void * notused)81 static void before(void *notused)
82 {
83 	reset_mock_buffer();
84 }
85 
86 ZTEST_SUITE(test_timestamp, NULL, NULL, before, NULL, NULL);
87