summaryrefslogtreecommitdiff
path: root/libmisc/tests/test_log.c
blob: 286738d1e3b0ed1ba70c6b165abc2fbc2df414ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* libmisc/tests/test_log.c - Tests for <libmisc/log.h>
 *
 * Copyright (C) 2024  Luke T. Shumaker <lukeshu@lukeshu.com>
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

#define _GNU_SOURCE /* for vasprintf() */
#include <stdarg.h> /* for va_list */
#include <stdio.h>  /* for vasprintf() */
#include <stdlib.h> /* for free() */
#include <string.h> /* for strcmp() */

#define LOG_NAME FROBNICATE
#include <libmisc/log.h>

#include "test.h"

/* Intercept output ***********************************************************/

static char *log_output = NULL;

int vprintf(const char *format, va_list ap) {
	return vasprintf(&log_output, format, ap);
}

/* Actual tests ***************************************************************/

#define should_print(_exp, cmd) do {                           \
		char *exp = _exp;                              \
		test_assert(!log_output);                      \
		cmd;                                           \
		if (!exp)                                      \
			test_assert(!log_output);              \
		else                                           \
			if (!(log_output != NULL &&            \
			      strcmp(log_output, exp) == 0)) { \
				printf("exp = \"%s\"\n"        \
				       "act = \"%s\"\n",       \
				       exp, log_output);       \
				test_assert(0);                \
			}                                      \
		if (log_output) {                              \
			free(log_output);                      \
			log_output = NULL;                     \
		}                                              \
	} while (0)

int main() {
	should_print("error: FROBNICATE: val=42\n",
	             errorf("val=%d", 42));
	should_print("info : FROBNICATE: val=0\n",
	             infof("val=%d", 0));
#define CONFIG_FROBNICATE_DEBUG 1
	should_print("debug: FROBNICATE: val=-2\n",
	             debugf("val=%d", -2));
#undef CONFIG_FROBNICATE_DEBUG
#define CONFIG_FROBNICATE_DEBUG 0
	should_print(NULL,
	             debugf("val=%d", -2));
	return 0;
}