Darin Petkov | e0a312e | 2011-07-20 13:45:28 -0700 | [diff] [blame] | 1 | // Copyright (c) 2011 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 <string> |
| 6 | |
| 7 | #include <gtest/gtest.h> |
| 8 | #include <net/if.h> |
| 9 | #include <sys/ioctl.h> |
| 10 | |
| 11 | #include "shill/mock_sockets.h" |
| 12 | #include "shill/rtnl_handler.h" |
| 13 | |
| 14 | using std::string; |
| 15 | using testing::_; |
| 16 | using testing::DoAll; |
| 17 | using testing::Return; |
| 18 | using testing::StrictMock; |
| 19 | using testing::Test; |
| 20 | |
| 21 | namespace shill { |
| 22 | |
| 23 | namespace { |
| 24 | |
| 25 | const int kTestInterfaceIndex = 4; |
| 26 | |
| 27 | ACTION(SetInterfaceIndex) { |
| 28 | if (arg2) { |
| 29 | reinterpret_cast<struct ifreq *>(arg2)->ifr_ifindex = kTestInterfaceIndex; |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | } // namespace |
| 34 | |
| 35 | class RTNLHandlerTest : public Test { |
| 36 | protected: |
| 37 | void SetSockets(Sockets *sockets) { |
| 38 | RTNLHandler::GetInstance()->sockets_ = sockets; |
| 39 | } |
| 40 | |
| 41 | virtual void SetUp() { |
| 42 | SetSockets(&sockets_); |
| 43 | } |
| 44 | |
| 45 | virtual void TearDown() { |
| 46 | SetSockets(NULL); |
| 47 | } |
| 48 | |
| 49 | StrictMock<MockSockets> sockets_; |
| 50 | }; |
| 51 | |
| 52 | TEST_F(RTNLHandlerTest, GetInterfaceName) { |
| 53 | EXPECT_EQ(-1, RTNLHandler::GetInstance()->GetInterfaceIndex("")); |
| 54 | { |
| 55 | struct ifreq ifr; |
| 56 | string name(sizeof(ifr.ifr_name), 'x'); |
| 57 | EXPECT_EQ(-1, RTNLHandler::GetInstance()->GetInterfaceIndex(name)); |
| 58 | } |
| 59 | |
| 60 | const int kTestSocket = 123; |
| 61 | EXPECT_CALL(sockets_, Socket(PF_INET, SOCK_DGRAM, 0)) |
| 62 | .Times(3) |
| 63 | .WillOnce(Return(-1)) |
| 64 | .WillRepeatedly(Return(kTestSocket)); |
| 65 | EXPECT_CALL(sockets_, Ioctl(kTestSocket, SIOCGIFINDEX, _)) |
| 66 | .WillOnce(Return(-1)) |
| 67 | .WillOnce(DoAll(SetInterfaceIndex(), Return(0))); |
| 68 | EXPECT_CALL(sockets_, Close(kTestSocket)) |
| 69 | .Times(2) |
| 70 | .WillRepeatedly(Return(0)); |
| 71 | EXPECT_EQ(-1, RTNLHandler::GetInstance()->GetInterfaceIndex("eth0")); |
| 72 | EXPECT_EQ(-1, RTNLHandler::GetInstance()->GetInterfaceIndex("wlan0")); |
| 73 | EXPECT_EQ(kTestInterfaceIndex, |
| 74 | RTNLHandler::GetInstance()->GetInterfaceIndex("usb0")); |
| 75 | } |
| 76 | |
| 77 | } // namespace shill |