1 //
2 // Copyright (C) 2012 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #include "shill/mock_log.h"
18
19 #include <string>
20
21 #include <gtest/gtest.h>
22
23 using std::string;
24 using testing::_;
25 using testing::AnyNumber;
26
27 namespace shill {
28
29 ScopedMockLog* ScopedMockLog::instance_ = nullptr;
30
ScopedMockLog()31 ScopedMockLog::ScopedMockLog() {
32 previous_handler_ = ::logging::GetLogMessageHandler();
33 ::logging::SetLogMessageHandler(HandleLogMessages);
34 instance_ = this;
35 }
36
~ScopedMockLog()37 ScopedMockLog::~ScopedMockLog() {
38 ::logging::SetLogMessageHandler(previous_handler_);
39 instance_ = nullptr;
40 }
41
42 // static
HandleLogMessages(int severity,const char * file,int line,size_t message_start,const string & full_message)43 bool ScopedMockLog::HandleLogMessages(int severity,
44 const char* file,
45 int line,
46 size_t message_start,
47 const string& full_message) {
48 CHECK(instance_);
49
50 // |full_message| looks like this if it came through MemoryLog:
51 // "[0514/165501:INFO:mock_log_unittest.cc(22)] Some message\n"
52 // The user wants to match just the substring "Some message". Strip off the
53 // extra stuff. |message_start| is the position where "Some message" begins.
54 //
55 // Note that the -1 is to remove the trailing return line.
56 const string::size_type message_length =
57 full_message.length() - message_start - 1;
58 const string message(full_message, message_start, message_length);
59
60 // Call Log. Because Log is a mock method, this sets in motion the mocking
61 // magic.
62 instance_->Log(severity, file, message);
63
64 // Invoke the previously installed message handler if there was one.
65 if (instance_->previous_handler_) {
66 return (*instance_->previous_handler_)(severity, file, line,
67 message_start, full_message);
68 }
69
70 // Return false so that messages show up on stderr.
71 return false;
72 }
73
NiceScopedMockLog()74 NiceScopedMockLog::NiceScopedMockLog() : ScopedMockLog() {
75 EXPECT_CALL(*this, Log(_, _, _)).Times(AnyNumber());
76 }
77
~NiceScopedMockLog()78 NiceScopedMockLog::~NiceScopedMockLog() {}
79
80 } // namespace shill
81