apply clang-tidy modernize-use-override
[folly.git] / folly / io / async / test / AsyncSocketTest.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
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 #include <iostream>
17
18 #include <folly/io/async/AsyncSocket.h>
19 #include <folly/io/async/AsyncServerSocket.h>
20 #include <folly/io/async/EventBase.h>
21 #include <folly/portability/GTest.h>
22
23 namespace folly {
24
25 TEST(AsyncSocketTest, getSockOpt) {
26   EventBase evb;
27   std::shared_ptr<AsyncSocket> socket =
28     AsyncSocket::newSocket(&evb, 0);
29
30   int val;
31   socklen_t len;
32
33   int expectedRc = getsockopt(socket->getFd(), SOL_SOCKET,
34                               SO_REUSEADDR, &val, &len);
35   int actualRc = socket->getSockOpt(SOL_SOCKET, SO_REUSEADDR, &val, &len);
36
37   EXPECT_EQ(expectedRc, actualRc);
38 }
39
40 TEST(AsyncSocketTest, REUSEPORT) {
41   EventBase base;
42   auto serverSocket = AsyncServerSocket::newSocket(&base);
43   serverSocket->bind(0);
44   serverSocket->listen(0);
45   serverSocket->startAccepting();
46
47   try {
48     serverSocket->setReusePortEnabled(true);
49   } catch(...) {
50     LOG(INFO) << "Reuse port probably not supported";
51     return;
52   }
53
54   SocketAddress address;
55   serverSocket->getAddress(&address);
56   int port = address.getPort();
57
58   auto serverSocket2 = AsyncServerSocket::newSocket(&base);
59   serverSocket2->setReusePortEnabled(true);
60   serverSocket2->bind(port);
61   serverSocket2->listen(0);
62   serverSocket2->startAccepting();
63
64 }
65
66 TEST(AsyncSocketTest, v4v6samePort) {
67   EventBase base;
68   auto serverSocket = AsyncServerSocket::newSocket(&base);
69   serverSocket->bind(0);
70   auto addrs = serverSocket->getAddresses();
71   ASSERT_GT(addrs.size(), 0);
72   uint16_t port = addrs[0].getPort();
73   for (const auto& addr : addrs) {
74     EXPECT_EQ(port, addr.getPort());
75   }
76 }
77
78 TEST(AsyncSocketTest, duplicateBind) {
79   EventBase base;
80   auto server1 = AsyncServerSocket::newSocket(&base);
81   server1->bind(0);
82   server1->listen(10);
83
84   SocketAddress address;
85   server1->getAddress(std::addressof(address));
86
87   auto server2 = AsyncServerSocket::newSocket(&base);
88   EXPECT_THROW(server2->bind(address.getPort()), std::exception);
89 }
90
91 } // namespace