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