1 // Copyright 2022 The Abseil Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // ----------------------------------------------------------------------------- 16 // File: log/scoped_mock_log.h 17 // ----------------------------------------------------------------------------- 18 // 19 // This header declares `class absl::ScopedMockLog`, for use in testing. 20 21 #ifndef ABSL_LOG_SCOPED_MOCK_LOG_H_ 22 #define ABSL_LOG_SCOPED_MOCK_LOG_H_ 23 24 #include <atomic> 25 #include <string> 26 27 #include "gmock/gmock.h" 28 #include "absl/base/config.h" 29 #include "absl/base/log_severity.h" 30 #include "absl/log/log_entry.h" 31 #include "absl/log/log_sink.h" 32 33 namespace absl { 34 ABSL_NAMESPACE_BEGIN 35 36 // MockLogDefault 37 // 38 // Controls how ScopedMockLog responds to unexpected calls by default. 39 enum class MockLogDefault { kIgnoreUnexpected, kDisallowUnexpected }; 40 41 // ScopedMockLog 42 // 43 // ScopedMockLog is a LogSink that intercepts LOG() messages issued during its 44 // lifespan. 45 // 46 // Using this together with GoogleTest, it's easy to test how a piece of code 47 // calls LOG(). The typical usage, noting the distinction between 48 // "uninteresting" and "unexpected", looks like this: 49 // 50 // using ::testing::_; 51 // using ::testing::AnyNumber; 52 // using ::testing::EndsWith; 53 // using ::testing::kDoNotCaptureLogsYet; 54 // using ::testing::Lt; 55 // 56 // TEST(FooTest, LogsCorrectly) { 57 // // Simple robust setup, ignores unexpected logs. 58 // absl::ScopedMockLog log; 59 // 60 // // We expect the WARNING "Something bad!" exactly twice. 61 // EXPECT_CALL(log, Log(absl::LogSeverity::kWarning, _, "Something bad!")) 62 // .Times(2); 63 // 64 // // But we want no messages from foo.cc. 65 // EXPECT_CALL(log, Log(_, EndsWith("/foo.cc"), _)).Times(0); 66 // 67 // log.StartCapturingLogs(); // Call this after done setting expectations. 68 // Foo(); // Exercises the code under test. 69 // } 70 // 71 // TEST(BarTest, LogsExactlyCorrectly) { 72 // // Strict checking, fails for unexpected logs. 73 // absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); 74 // 75 // // ... but ignore low severity messages 76 // EXPECT_CALL(log, Log(Lt(absl::LogSeverity::kWarning), _, _)) 77 // .Times(AnyNumber()); 78 // 79 // // We expect the ERROR "Something bad!" exactly once. 80 // EXPECT_CALL(log, Log(absl::LogSeverity::kError, EndsWith("/foo.cc"), 81 // "Something bad!")) 82 // .Times(1); 83 // 84 // log.StartCapturingLogs(); // Call this after done setting expectations. 85 // Bar(); // Exercises the code under test. 86 // } 87 // 88 // Note that in a multi-threaded environment, all LOG() messages from a single 89 // thread will be handled in sequence, but that cannot be guaranteed for 90 // messages from different threads. In fact, if the same or multiple 91 // expectations are matched on two threads concurrently, their actions will be 92 // executed concurrently as well and may interleave. 93 class ScopedMockLog final { 94 public: 95 // ScopedMockLog::ScopedMockLog() 96 // 97 // Sets up the log and adds default expectations. 98 explicit ScopedMockLog( 99 MockLogDefault default_exp = MockLogDefault::kIgnoreUnexpected); 100 ScopedMockLog(const ScopedMockLog&) = delete; 101 ScopedMockLog& operator=(const ScopedMockLog&) = delete; 102 103 // ScopedMockLog::~ScopedMockLog() 104 // 105 // Stops intercepting logs and destroys this ScopedMockLog. 106 ~ScopedMockLog(); 107 108 // ScopedMockLog::StartCapturingLogs() 109 // 110 // Starts log capturing if the object isn't already doing so. Otherwise 111 // crashes. 112 // 113 // Usually this method is called in the same thread that created this 114 // ScopedMockLog. It is the user's responsibility to not call this method if 115 // another thread may be calling it or StopCapturingLogs() at the same time. 116 // It is undefined behavior to add expectations while capturing logs is 117 // enabled. 118 void StartCapturingLogs(); 119 120 // ScopedMockLog::StopCapturingLogs() 121 // 122 // Stops log capturing if the object is capturing logs. Otherwise crashes. 123 // 124 // Usually this method is called in the same thread that created this object. 125 // It is the user's responsibility to not call this method if another thread 126 // may be calling it or StartCapturingLogs() at the same time. 127 // 128 // It is UB to add expectations, while capturing logs is enabled. 129 void StopCapturingLogs(); 130 131 // ScopedMockLog::UseAsLocalSink() 132 // 133 // Each `ScopedMockLog` is implemented with an `absl::LogSink`; this method 134 // returns a reference to that sink (e.g. for use with 135 // `LOG(...).ToSinkOnly()`) and marks the `ScopedMockLog` as having been used 136 // even if `StartCapturingLogs` is never called. 137 absl::LogSink& UseAsLocalSink(); 138 139 // Implements the mock method: 140 // 141 // void Log(LogSeverity severity, absl::string_view file_path, 142 // absl::string_view message); 143 // 144 // The second argument to Log() is the full path of the source file in 145 // which the LOG() was issued. 146 // 147 // This is a shorthand form, which should be used by most users. Use the 148 // `Send` mock only if you want to add expectations for other log message 149 // attributes. 150 MOCK_METHOD(void, Log, 151 (absl::LogSeverity severity, const std::string& file_path, 152 const std::string& message)); 153 154 // Implements the mock method: 155 // 156 // void Send(const absl::LogEntry& entry); 157 // 158 // This is the most generic form of mock that can be specified. Use this mock 159 // only if you want to add expectations for log message attributes different 160 // from the log message text, log message path and log message severity. 161 // 162 // If no expectations are specified for this mock, the default action is to 163 // forward the call to the `Log` mock. 164 MOCK_METHOD(void, Send, (const absl::LogEntry&)); 165 166 // Implements the mock method: 167 // 168 // void Flush(); 169 // 170 // Use this mock only if you want to add expectations for log flush calls. 171 MOCK_METHOD(void, Flush, ()); 172 173 private: 174 class ForwardingSink final : public absl::LogSink { 175 public: ForwardingSink(ScopedMockLog * sml)176 explicit ForwardingSink(ScopedMockLog* sml) : sml_(sml) {} 177 ForwardingSink(const ForwardingSink&) = delete; 178 ForwardingSink& operator=(const ForwardingSink&) = delete; Send(const absl::LogEntry & entry)179 void Send(const absl::LogEntry& entry) override { sml_->Send(entry); } Flush()180 void Flush() override { sml_->Flush(); } 181 182 private: 183 ScopedMockLog* sml_; 184 }; 185 186 ForwardingSink sink_; 187 bool is_capturing_logs_; 188 // Until C++20, the default constructor leaves the underlying value wrapped in 189 // std::atomic uninitialized, so all constructors should be sure to initialize 190 // is_triggered_. 191 std::atomic<bool> is_triggered_; 192 }; 193 194 ABSL_NAMESPACE_END 195 } // namespace absl 196 197 #endif // ABSL_LOG_SCOPED_MOCK_LOG_H_ 198