test_source_location.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <zf_log.c>
  2. #include <zf_test.h>
  3. #include <stdio.h>
  4. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) && !defined(snprintf)
  5. #define snprintf(buf, len, ...) _snprintf_s(buf, len, _TRUNCATE, __VA_ARGS__)
  6. #endif
  7. const char *const c_filename = "test_source_location.c";
  8. static char g_srcloc_buf[ZF_LOG_BUF_SZ];
  9. static const char *g_srcloc;
  10. static char *trim(char *s)
  11. {
  12. char *sb;
  13. while (0 != *(sb = s) && ' ' == *s) ++s;
  14. char *se;
  15. while (0 != *(se = s) && ' ' != *s) ++s;
  16. *se = 0;
  17. return sb;
  18. }
  19. static void mock_output_callback(const zf_log_message *msg, void *arg)
  20. {
  21. (void)arg;
  22. const size_t len = msg->msg_b - msg->tag_e;
  23. memcpy(g_srcloc_buf, msg->tag_e, len);
  24. g_srcloc_buf[len] = 0;
  25. g_srcloc = trim(g_srcloc_buf);
  26. }
  27. static void test_function()
  28. {
  29. const unsigned line = __LINE__ + 1;
  30. ZF_LOGI("test message");
  31. char expected[64];
  32. #if ZF_LOG_SRCLOC_NONE==TEST_SRCLOC
  33. (void)line;
  34. *expected = 0;
  35. #endif
  36. #if ZF_LOG_SRCLOC_SHORT==TEST_SRCLOC
  37. snprintf(expected, sizeof(expected), "@%s:%u",
  38. c_filename, line);
  39. #endif
  40. #if ZF_LOG_SRCLOC_LONG==TEST_SRCLOC
  41. snprintf(expected, sizeof(expected), "%s@%s:%u",
  42. _ZF_LOG_FUNCTION, c_filename, line);
  43. #endif
  44. TEST_VERIFY_EQUAL(strcmp(expected, g_srcloc), 0);
  45. }
  46. int main(int argc, char *argv[])
  47. {
  48. zf_log_set_output_v(ZF_LOG_PUT_STD, 0, mock_output_callback);
  49. TEST_RUNNER_CREATE(argc, argv);
  50. TEST_EXECUTE(test_function());
  51. return TEST_RUNNER_EXIT_CODE();
  52. }