blob: e34d9831a817ae0766a22e443d62a21238963cb3 [file] [log] [blame]
Gary Morain8a5726a2012-05-15 10:56:49 -07001// 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
Christopher Wileyd7783522012-08-10 14:21:47 -07009#include "shill/memory_log.h"
10
Gary Morain8a5726a2012-05-15 10:56:49 -070011using std::string;
12
13namespace shill {
14
15ScopedMockLog *ScopedMockLog::instance_ = NULL;
16
17ScopedMockLog::ScopedMockLog() {
18 previous_handler_ = ::logging::GetLogMessageHandler();
19 ::logging::SetLogMessageHandler(HandleLogMessages);
20 instance_ = this;
21}
22
23ScopedMockLog::~ScopedMockLog() {
24 ::logging::SetLogMessageHandler(previous_handler_);
25 instance_ = NULL;
26}
27
28// static
29bool ScopedMockLog::HandleLogMessages(int severity,
30 const char *file,
31 int line,
32 size_t message_start,
33 const string &full_message) {
34 CHECK(instance_);
35
Christopher Wileyd7783522012-08-10 14:21:47 -070036 // |full_message| looks like this if it came through MemoryLog:
Christopher Wiley6e8c54b2012-08-15 16:12:30 -070037 // "[0514/165501:INFO:mock_log_unittest.cc(22)] Some message\n"
Gary Morain8a5726a2012-05-15 10:56:49 -070038 // The user wants to match just the substring "Some message". Strip off the
Christopher Wiley6e8c54b2012-08-15 16:12:30 -070039 // extra stuff. |message_start| is the position where "Some message" begins.
Christopher Wileyd7783522012-08-10 14:21:47 -070040 //
Christopher Wileyd7783522012-08-10 14:21:47 -070041 // Note that the -1 is to remove the trailing return line.
Gary Morain8a5726a2012-05-15 10:56:49 -070042 const string::size_type message_length =
Christopher Wiley6e8c54b2012-08-15 16:12:30 -070043 full_message.length() - message_start - 1;
44 const string message(full_message, message_start, message_length);
Gary Morain8a5726a2012-05-15 10:56:49 -070045
46 // Call Log. Because Log is a mock method, this sets in motion the mocking
47 // magic.
48 instance_->Log(severity, file, message);
49
50 // Invoke the previously installed message handler if there was one.
51 if (instance_->previous_handler_ != NULL) {
52 return (*instance_->previous_handler_)(severity, file, line,
53 message_start, full_message);
54 }
55
56 // Return false so that messages show up on stderr.
57 return false;
58}
59
60} // namespace shill