From fe480f5e29f212efd5b933475cc6e71fc5937f4d Mon Sep 17 00:00:00 2001 From: Benjamin Barenblat Date: Tue, 6 Jul 2021 19:57:09 -0400 Subject: Add CHECK macro to logging framework Reviewed-by: Alex Chernyakhovsky --- buildconf/common.ninja | 3 ++- log.cc | 17 +++++++++++++++++ log.h | 8 ++++++++ log_test.cc | 12 ++++++++++++ 4 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 log.cc diff --git a/buildconf/common.ninja b/buildconf/common.ninja index 6ec7e96..e3d2298 100644 --- a/buildconf/common.ninja +++ b/buildconf/common.ninja @@ -30,8 +30,9 @@ rule link build gsrsup.o: cxx gsrsup.cc build gsrsup: link gsrsup.o +build log.o: cxx log.cc build log_test.o: cxx log_test.cc -build log_test: link log_test.o +build log_test: link log.o log_test.o libs = -lgmock_main -lgmock -lgtest -labsl_strings -pthread default gsrsup diff --git a/log.cc b/log.cc new file mode 100644 index 0000000..13b74d7 --- /dev/null +++ b/log.cc @@ -0,0 +1,17 @@ +#include "log.h" + +#include +#include + +namespace gsrsup { + +void Check(Log& log, bool condition, const char* condition_str, + const char* file, int line) { + if (!condition) { + log.Error(absl::Substitute("internal error ($0:$1): ", file, line), + condition_str); + exit(1); + } +} + +} // namespace gsrsup diff --git a/log.h b/log.h index e0d3963..d588b8f 100644 --- a/log.h +++ b/log.h @@ -111,6 +111,14 @@ void Log::Message(Level level, Args... args) { out_->write(message.data(), message.size()); } +// If condition is false, logs an internal error and exits the program. +void Check(Log& log, bool condition, const char* condition_str, + const char* file, int line); + } // namespace gsrsup +// A convenience macro to invoke the Check function. +#define CHECK(log, condition) \ + ::gsrsup::Check((log), (condition), #condition, __FILE__, __LINE__) + #endif // GSRSUP_LOG_H_ diff --git a/log_test.cc b/log_test.cc index 0ceb3f2..c06fd90 100644 --- a/log_test.cc +++ b/log_test.cc @@ -80,5 +80,17 @@ TEST(LogTest, DedicatedErrorFunction) { EXPECT_THAT(s.str(), HasSubstr("error:")); } +TEST(LogTest, CheckPasses) { + std::ostringstream s; + Log log("program", s); + CHECK(log, 2 + 2 == 4); + EXPECT_THAT(s.str(), IsEmpty()); +} + +TEST(LogDeathTest, CheckFails) { + Log log("program", std::cerr); + EXPECT_DEATH(CHECK(log, 2 + 2 == 5), "internal error \\(.*\\): 2 \\+ 2 == 5"); +} + } // namespace } // namespace gsrsup -- cgit v1.2.3