Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ clean:
.PHONY: unit-tests
unit-tests: clean
# In case NUMBER_OF_WORKERS has been set, unset it.
cmake -B build -UNUMBER_OF_WORKERS
cmake -B build -UNUMBER_OF_WORKERS -DLOG_LEVEL=4
cmake --build build
cd build && make test

Expand Down
3 changes: 2 additions & 1 deletion logging/api/logging_macros.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#define LOGGING_MACROS_H
#include "logging.h"
#include <stdbool.h>
#include "low_level_platform.h"

/** Default log level. */
#ifndef LOG_LEVEL
Expand Down Expand Up @@ -72,7 +73,7 @@ static const bool _lf_log_level_is_debug = LOG_LEVEL >= LOG_LEVEL_DEBUG;
#define LF_PRINT_DEBUG(format, ...) \
do { \
if (_lf_log_level_is_debug) { \
lf_print_debug(format, ##__VA_ARGS__); \
lf_print_debug("[" PRINTF_TIME "]" format, lf_time_physical_elapsed(), ##__VA_ARGS__); \
} \
} while (0)

Expand Down
71 changes: 71 additions & 0 deletions test/general/logging_test.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#include "logging_macros.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <regex.h>

#define TIMEED_DEBUG_CHAR_LEN 30
#define SOME_EXTRA_SPACE 10
/**
* @brief unit for LF_PRINT_DEBUG macro
* must be in LOG_LEVEL LOG_LEVEL_DEBUG
*/
void test_logging_macro(const char* expected, int st_len) {

FILE* tmp = tmpfile(); // auto-deletes when closed
char* buffer;
char pattern[256];
regex_t re;
int result;

// Computing the buffer size based on strlen("DEBUG: ") + \0 + \n + extra space
int buffer_size = st_len + TIMEED_DEBUG_CHAR_LEN + SOME_EXTRA_SPACE;

if (!tmp) {
perror("tmpfile");
exit(1);
}

// Redirect stdout -> tmp
fflush(stdout);
int fd = fileno(tmp);
if (fd == -1 || dup2(fd, STDOUT_FILENO) == -1) {
perror("redirect stdout");
exit(1);
}

// Call code under test
LF_PRINT_DEBUG("%s", expected);

fflush(stdout); // flush so data goes into tmp
rewind(tmp); // reset read position

// Read back
buffer = (char*)malloc(buffer_size);
size_t n = fread(buffer, 1, buffer_size - 1, tmp);
buffer[n] = '\0';

// Regex to check format: DEBUG: [number]expected\n
snprintf(pattern, sizeof(pattern), "^DEBUG: \\[-?[0-9]+\\]%s\\n?$", expected);

if (regcomp(&re, pattern, REG_EXTENDED | REG_NEWLINE) != 0) {
perror("regcomp");
exit(1);
}

result = regexec(&re, buffer, 0, NULL, 0);
regfree(&re);

assert(result == 0); // match succeeded

fclose(tmp); // deletes the file
free(buffer);
}

int main() {
char* str_test = "Hello World";
test_logging_macro(str_test, strlen(str_test));
return 0;
}
Loading