Gary Morain | 8a5726a | 2012-05-15 10:56:49 -0700 | [diff] [blame] | 1 | // Copyright (c) 2012 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "shill/mock_log.h" |
| 6 | |
| 7 | #include <string> |
| 8 | |
| 9 | using std::string; |
| 10 | |
| 11 | namespace shill { |
| 12 | |
| 13 | ScopedMockLog *ScopedMockLog::instance_ = NULL; |
| 14 | |
| 15 | ScopedMockLog::ScopedMockLog() { |
| 16 | previous_handler_ = ::logging::GetLogMessageHandler(); |
| 17 | ::logging::SetLogMessageHandler(HandleLogMessages); |
| 18 | instance_ = this; |
| 19 | } |
| 20 | |
| 21 | ScopedMockLog::~ScopedMockLog() { |
| 22 | ::logging::SetLogMessageHandler(previous_handler_); |
| 23 | instance_ = NULL; |
| 24 | } |
| 25 | |
| 26 | // static |
| 27 | bool ScopedMockLog::HandleLogMessages(int severity, |
| 28 | const char *file, |
| 29 | int line, |
| 30 | size_t message_start, |
| 31 | const string &full_message) { |
| 32 | CHECK(instance_); |
| 33 | |
| 34 | // |full_message| looks like this: |
| 35 | // "[0514/165501:INFO:mock_log_unittest.cc(22)] Some message\n" |
| 36 | // The user wants to match just the substring "Some message". Strip off the |
| 37 | // extra stuff. |message_start| is the position where the user's message |
| 38 | // begins. |
| 39 | const string::size_type message_length = |
| 40 | full_message.length() - message_start - 1; |
| 41 | const string message(full_message, message_start, message_length); |
| 42 | |
| 43 | // Call Log. Because Log is a mock method, this sets in motion the mocking |
| 44 | // magic. |
| 45 | instance_->Log(severity, file, message); |
| 46 | |
| 47 | // Invoke the previously installed message handler if there was one. |
| 48 | if (instance_->previous_handler_ != NULL) { |
| 49 | return (*instance_->previous_handler_)(severity, file, line, |
| 50 | message_start, full_message); |
| 51 | } |
| 52 | |
| 53 | // Return false so that messages show up on stderr. |
| 54 | return false; |
| 55 | } |
| 56 | |
| 57 | } // namespace shill |