Neil Williams | 01d53f4 | 2020-07-07 07:27:29 -0700 | [diff] [blame] | 1 | import errno |
| 2 | import unittest |
| 3 | |
| 4 | from test_sslsocket import ServerAcceptor |
| 5 | |
| 6 | import _import_local_thrift # noqa |
| 7 | |
| 8 | from thrift.transport.TSocket import TServerSocket |
| 9 | from thrift.transport.TSocket import TSocket |
| 10 | from thrift.transport.TTransport import TTransportException |
| 11 | |
| 12 | |
| 13 | class TSocketTest(unittest.TestCase): |
bwangelme | 0ed4a1d | 2024-04-15 12:17:40 +0800 | [diff] [blame] | 14 | 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 Williams | 01d53f4 | 2020-07-07 07:27:29 -0700 | [diff] [blame] | 32 | 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 Smith | e3eb9af | 2022-06-08 17:23:27 -0700 | [diff] [blame] | 46 | self.assertFalse(sock.isOpen()) |
Neil Williams | 01d53f4 | 2020-07-07 07:27:29 -0700 | [diff] [blame] | 47 | 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 | |
| 75 | if __name__ == "__main__": |
| 76 | unittest.main() |