logger_test.cxx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // logger_test.cxx
  3. // logger
  4. //
  5. // Created by Sam Jaffe on 3/31/19.
  6. //
  7. #include <gmock/gmock.h>
  8. #include "logger/logger.h"
  9. #include "logger/logger_impl.h"
  10. namespace logging {
  11. void PrintTo(location_info const & info, std::ostream * os) {
  12. if (info.line) {
  13. (*os) << "{\"" << info.filename << "\", \"" <<
  14. info.function << "\", " << info.line << "}";
  15. } else {
  16. (*os) << "NULL";
  17. }
  18. }
  19. void PrintTo(logpacket const & pkt, std::ostream * os) {
  20. (*os) << "{ " << pkt.level << ", ";
  21. PrintTo(pkt.info, os);
  22. (*os) << ", \"" << pkt.logger << "\", \"" << pkt.message << "\" }";
  23. }
  24. }
  25. struct MockLoggerImpl : public logging::logger_impl {
  26. MockLoggerImpl() {
  27. SetLogLevel(logging::LTRACE);
  28. }
  29. void SetLogLevel(logging::log_level ll) {
  30. min_log_level = ll;
  31. }
  32. MOCK_METHOD0(flush, void());
  33. MOCK_METHOD1(write, void(logging::logpacket const &));
  34. MOCK_METHOD2(write, void(logging::log_level, std::string const &));
  35. };
  36. struct LoggerTest : public testing::Test {
  37. void SetUp() override;
  38. void TearDown() override;
  39. std::shared_ptr<MockLoggerImpl> pimpl;
  40. };
  41. using namespace logging;
  42. struct t_logger : public logger {
  43. t_logger(std::string const & name, std::shared_ptr<logger_impl> impl)
  44. : logger(name, impl) {}
  45. };
  46. void LoggerTest::SetUp() {
  47. pimpl.reset(new MockLoggerImpl);
  48. using testing::AnyNumber;
  49. EXPECT_CALL(*pimpl, flush()).Times(AnyNumber());
  50. }
  51. void LoggerTest::TearDown() {
  52. pimpl.reset();
  53. }
  54. TEST_F(LoggerTest, LogsWithBraceFmtCode) {
  55. using testing::Field;
  56. EXPECT_CALL(*pimpl, write(Field(&logpacket::message, "5"))).Times(1);
  57. t_logger("", pimpl).log(LERROR, "{}", 5);
  58. }
  59. TEST_F(LoggerTest, DoesNotLogAboveLevel) {
  60. using testing::_;
  61. pimpl->SetLogLevel(LFATAL);
  62. EXPECT_CALL(*pimpl, write(_)).Times(0);
  63. t_logger("", pimpl).log(LERROR, "{}", 5);
  64. }
  65. TEST_F(LoggerTest, LogCurlyBraceLiteralByDoubling) {
  66. using testing::Field;
  67. EXPECT_CALL(*pimpl, write(Field(&logpacket::message, "{}"))).Times(1);
  68. t_logger("", pimpl).log(LERROR, "{{}}", 5);
  69. }