xref: /netbsd-src/external/bsd/ntp/dist/sntp/tests/t-log.c (revision 3117ece4fc4a4ca4489ba793710b60b0d26bab6c)
1 /*	$NetBSD: t-log.c,v 1.3 2024/08/18 20:47:26 christos Exp $	*/
2 
3 #include "config.h"
4 #include "unity.h"
5 #include "ntp_types.h"
6 
7 
8 #include "log.c"
9 
10 void setUp(void);
11 void testChangePrognameInMysyslog(void);
12 void testOpenLogfileTest(void);
13 void testWriteInCustomLogfile(void);
14 
15 
16 void
17 setUp(void) {
18 	init_lib();
19 }
20 
21 
22 //in var/log/syslog (may differ depending on your OS), logged name of the program will be "TEST_PROGNAME".
23 
24 void
25 testChangePrognameInMysyslog(void)
26 {
27 	sntp_init_logging("TEST_PROGNAME");
28 	msyslog(LOG_ERR, "TESTING sntp_init_logging()");
29 
30 	return;
31 }
32 
33 //writes log files in your own file instead of syslog! (MAY BE USEFUL TO SUPPRESS ERROR MESSAGES!)
34 
35 void
36 testOpenLogfileTest(void)
37 {
38 	sntp_init_logging("TEST_PROGNAME2"); //this name is consistent through the entire program unless changed
39 	open_logfile("testLogfile.log");
40 	//open_logfile("/var/log/syslog"); //this gives me "Permission Denied" when i do %m
41 
42 	msyslog(LOG_ERR, "Cannot open log file %s","abcXX");
43 	//cleanup_log(); //unnecessary  after log.c fix!
44 
45 	return;
46 }
47 
48 
49 //multiple cleanup_log() causes segfault. Probably the reason it's static. Opening multiple open_logfile(name) will cause segfault x.x I'm guessing it's not intended to be changed. Cleanup after unity test doesn't fix it, looks like. Calling in tearDown() also causes issues.
50 
51 void
52 testWriteInCustomLogfile(void)
53 {
54 	char testString[256] = "12345 ABC";
55 	char testName[256] = "TEST_PROGNAME3";
56 
57 	(void)remove("testLogfile2.log");
58 
59 	sntp_init_logging(testName);
60 	open_logfile("testLogfile2.log"); // ./ causing issues
61 	//sntp_init_logging(testName);
62 
63 
64 	msyslog(LOG_ERR, "%s", testString);
65 	FILE * f = fopen("testLogfile2.log","r");
66 	char line[256];
67 
68 	TEST_ASSERT_TRUE( f != NULL);
69 
70 	//should be only 1 line
71 	while (fgets(line, sizeof(line), f)) {
72 		printf("%s", line);
73 	}
74 
75 
76 	char* x = strstr(line,testName);
77 
78 	TEST_ASSERT_TRUE( x != NULL);
79 
80 	x = strstr(line,testString);
81 	TEST_ASSERT_TRUE( x != NULL);
82 	//cleanup_log();
83 	fclose(f); //using this will also cause segfault, because at the end, log.c will  call (using atexit(func) function) cleanup_log(void)-> fclose(syslog_file);
84 	//After the 1st fclose, syslog_file = NULL, and is never reset -> hopefully fixed by editing log.c
85 	//TEST_ASSERT_EQUAL_STRING(testString,line); //doesn't work, line is dynamic because the process name is random.
86 
87 	return;
88 }
89