Commit 4825ef40 by Abseil Team Committed by Copybara-Service

Initialize ScopedMockLog.is_triggered_ with false.

In C++20, this happens by default, but in C++17, it's left uninitialized if no logs are sent and StartCapturingLogs is never called. The destructor then makes an attempt to access it, which is both unsafe and not very useful while it is uninitialized.

Also add a test that expects the appropriate CHECK fail when StartCapturingLogs is not called.

PiperOrigin-RevId: 511865440
Change-Id: Ie23ff3f901e926761d5f487e10d33c21c3bd43d3
parent 6d162375
...@@ -30,7 +30,7 @@ namespace absl { ...@@ -30,7 +30,7 @@ namespace absl {
ABSL_NAMESPACE_BEGIN ABSL_NAMESPACE_BEGIN
ScopedMockLog::ScopedMockLog(MockLogDefault default_exp) ScopedMockLog::ScopedMockLog(MockLogDefault default_exp)
: sink_(this), is_capturing_logs_(false) { : sink_(this), is_capturing_logs_(false), is_triggered_(false) {
if (default_exp == MockLogDefault::kIgnoreUnexpected) { if (default_exp == MockLogDefault::kIgnoreUnexpected) {
// Ignore all calls to Log we did not set expectations for. // Ignore all calls to Log we did not set expectations for.
EXPECT_CALL(*this, Log).Times(::testing::AnyNumber()); EXPECT_CALL(*this, Log).Times(::testing::AnyNumber());
......
...@@ -185,6 +185,9 @@ class ScopedMockLog final { ...@@ -185,6 +185,9 @@ class ScopedMockLog final {
ForwardingSink sink_; ForwardingSink sink_;
bool is_capturing_logs_; bool is_capturing_logs_;
// Until C++20, the default constructor leaves the underlying value wrapped in
// std::atomic uninitialized, so all constructors should be sure to initialize
// is_triggered_.
std::atomic<bool> is_triggered_; std::atomic<bool> is_triggered_;
}; };
......
...@@ -71,6 +71,11 @@ TEST(ScopedMockLogDeathTest, StopCapturingLogsCannotBeCalledWhenNotCapturing) { ...@@ -71,6 +71,11 @@ TEST(ScopedMockLogDeathTest, StopCapturingLogsCannotBeCalledWhenNotCapturing) {
}, },
"StopCapturingLogs"); "StopCapturingLogs");
} }
TEST(ScopedMockLogDeathTest, FailsCheckIfStartCapturingLogsIsNeverCalled) {
EXPECT_DEATH({ absl::ScopedMockLog log; },
"Did you forget to call StartCapturingLogs");
}
#endif #endif
// Tests that ScopedMockLog intercepts LOG()s when it's alive. // Tests that ScopedMockLog intercepts LOG()s when it's alive.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment