1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #include <boost/test/unit_test.hpp>
21 #include <thrift/transport/TSocket.h>
22 #include <thrift/transport/TServerSocket.h>
23 #include <memory>
24 #include "TTransportCheckThrow.h"
25 #include <iostream>
26 
27 using apache::thrift::transport::TServerSocket;
28 using apache::thrift::transport::TSocket;
29 using apache::thrift::transport::TTransport;
30 using apache::thrift::transport::TTransportException;
31 using std::shared_ptr;
32 
33 BOOST_AUTO_TEST_SUITE(TServerSocketTest)
34 
BOOST_AUTO_TEST_CASE(test_bind_to_address)35 BOOST_AUTO_TEST_CASE(test_bind_to_address) {
36   TServerSocket sock1("localhost", 0);
37   sock1.listen();
38   BOOST_CHECK(sock1.isOpen());
39   int port = sock1.getPort();
40   TSocket clientSock("localhost", port);
41   clientSock.open();
42   shared_ptr<TTransport> accepted = sock1.accept();
43   accepted->close();
44   sock1.close();
45 
46   std::cout << "An error message from getaddrinfo on the console is expected:" << std::endl;
47   TServerSocket sock2("257.258.259.260", 0);
48   BOOST_CHECK_THROW(sock2.listen(), TTransportException);
49   sock2.close();
50 }
51 
BOOST_AUTO_TEST_CASE(test_listen_invalid_port)52 BOOST_AUTO_TEST_CASE(test_listen_invalid_port) {
53   TServerSocket sock1(-1);
54   TTRANSPORT_CHECK_THROW(sock1.listen(), TTransportException::BAD_ARGS);
55   BOOST_CHECK(!sock1.isOpen());
56 
57   TServerSocket sock2(65536);
58   TTRANSPORT_CHECK_THROW(sock2.listen(), TTransportException::BAD_ARGS);
59   BOOST_CHECK(!sock1.isOpen());
60 }
61 
BOOST_AUTO_TEST_CASE(test_close_before_listen)62 BOOST_AUTO_TEST_CASE(test_close_before_listen) {
63   TServerSocket sock1("localhost", 0);
64   sock1.close();
65   BOOST_CHECK(!sock1.isOpen());
66 }
67 
BOOST_AUTO_TEST_CASE(test_get_port)68 BOOST_AUTO_TEST_CASE(test_get_port) {
69   TServerSocket sock1("localHost", 888);
70   BOOST_CHECK_EQUAL(888, sock1.getPort());
71 }
72 
73 BOOST_AUTO_TEST_SUITE_END()
74