blob: ab56a6ec3fc25de7e38188d43c500341abd76f67 [file] [log] [blame]
Neil Williams01d53f42020-07-07 07:27:29 -07001import errno
2import unittest
3
4from test_sslsocket import ServerAcceptor
5
6import _import_local_thrift # noqa
7
8from thrift.transport.TSocket import TServerSocket
9from thrift.transport.TSocket import TSocket
10from thrift.transport.TTransport import TTransportException
11
12
13class TSocketTest(unittest.TestCase):
bwangelme0ed4a1d2024-04-15 12:17:40 +080014 def test_socket_readtimeout_exception(self):
15 acc = ServerAcceptor(TServerSocket(port=0))
16 acc.start()
17
18 sock = TSocket(host="localhost", port=acc.port)
19 sock.open()
20 sock.setTimeout(1)
21 sock.write(b"sleep")
22
23 with self.assertRaises(TTransportException) as ctx:
24 sock.read(5)
25 exc = ctx.exception
26 self.assertEqual(exc.message, "read timeout")
27
28 acc.client.close() # this also blocks until the other thread is done
29 acc.close()
30 sock.close()
31
Neil Williams01d53f42020-07-07 07:27:29 -070032 def test_isOpen_checks_for_readability(self):
33 # https://docs.python.org/3/library/socket.html#notes-on-socket-timeouts
34 # https://docs.python.org/3/library/socket.html#socket.socket.settimeout
35 timeouts = [
36 None, # blocking mode
37 0, # non-blocking mode
38 1.0, # timeout mode
39 ]
40
41 for timeout in timeouts:
42 acc = ServerAcceptor(TServerSocket(port=0))
43 acc.start()
44
45 sock = TSocket(host="localhost", port=acc.port)
Michael Smithe3eb9af2022-06-08 17:23:27 -070046 self.assertFalse(sock.isOpen())
Neil Williams01d53f42020-07-07 07:27:29 -070047 sock.open()
48 sock.setTimeout(timeout)
49
50 # the socket shows as open immediately after connecting
51 self.assertTrue(sock.isOpen())
52
53 # and remains open during usage
54 sock.write(b"hello")
55 self.assertTrue(sock.isOpen())
56 while True:
57 try:
58 sock.read(5)
59 except TTransportException as exc:
60 if exc.inner.errno == errno.EAGAIN:
61 # try again when we're in non-blocking mode
62 continue
63 raise
64 break
65 self.assertTrue(sock.isOpen())
66
67 # once the server side closes, it no longer shows open
68 acc.client.close() # this also blocks until the other thread is done
69 acc.close()
70 self.assertFalse(sock.isOpen())
71
72 sock.close()
73
74
75if __name__ == "__main__":
76 unittest.main()