1 //
2 // Copyright (C) 2011 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/net/rtnl_listener.h"
18 
19 #include <linux/netlink.h>
20 #include <sys/socket.h>
21 
22 #include <base/bind.h>
23 #include <gmock/gmock.h>
24 #include <gtest/gtest.h>
25 
26 #include "shill/net/rtnl_handler.h"
27 #include "shill/net/rtnl_message.h"
28 
29 using base::Bind;
30 using base::Callback;
31 using base::Unretained;
32 using testing::_;
33 using testing::A;
34 using testing::Test;
35 
36 namespace shill {
37 
38 class RTNLListenerTest : public Test {
39  public:
RTNLListenerTest()40   RTNLListenerTest()
41       : callback_(Bind(&RTNLListenerTest::ListenerCallback,
42                        Unretained(this))) {}
43 
44   MOCK_METHOD1(ListenerCallback, void(const RTNLMessage&));
45 
SetUp()46   virtual void SetUp() {
47     // RTNLHandler is a singleton, there's no guarentee that it is not
48     // setup/used by other unittests. Clear "listeners_" field before we run
49     // tests.
50     RTNLHandler::GetInstance()->listeners_.clear();
51   }
52 
53  protected:
54   Callback<void(const RTNLMessage&)> callback_;
55 };
56 
TEST_F(RTNLListenerTest,NoRun)57 TEST_F(RTNLListenerTest, NoRun) {
58   {
59     RTNLListener listener(RTNLHandler::kRequestAddr, callback_);
60     EXPECT_EQ(1, RTNLHandler::GetInstance()->listeners_.size());
61     RTNLMessage message;
62     EXPECT_CALL(*this, ListenerCallback(_)).Times(0);
63     listener.NotifyEvent(RTNLHandler::kRequestLink, message);
64   }
65   EXPECT_EQ(0, RTNLHandler::GetInstance()->listeners_.size());
66 }
67 
TEST_F(RTNLListenerTest,Run)68 TEST_F(RTNLListenerTest, Run) {
69   {
70     RTNLListener listener(
71         RTNLHandler::kRequestLink | RTNLHandler::kRequestAddr,
72         callback_);
73     EXPECT_EQ(1, RTNLHandler::GetInstance()->listeners_.size());
74     RTNLMessage message;
75     EXPECT_CALL(*this, ListenerCallback(A<const RTNLMessage&>())).Times(1);
76     listener.NotifyEvent(RTNLHandler::kRequestLink, message);
77   }
78   EXPECT_EQ(0, RTNLHandler::GetInstance()->listeners_.size());
79 }
80 
81 }  // namespace shill
82