blob: 973ac1f7d97c9b083aca6c0b98c4ee524f210009 [file] [log] [blame]
R. David Murraya21e4ca2009-03-31 23:16:50 +00001# test asynchat
Guido van Rossum66172522001-04-06 16:32:22 +00002
R. David Murraya21e4ca2009-03-31 23:16:50 +00003from test import support
Serhiy Storchaka16994912020-04-25 10:06:29 +03004from test.support import socket_helper
Hai Shie80697d2020-05-28 06:10:27 +08005from test.support import threading_helper
R. David Murraya21e4ca2009-03-31 23:16:50 +00006
Victor Stinner45cff662014-07-24 18:49:36 +02007import errno
Victor Stinnerfd5d1b52014-07-08 00:16:54 +02008import socket
Guido van Rossum806c2462007-08-06 23:33:07 +00009import sys
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020010import threading
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020011import time
12import unittest
Victor Stinner45cff662014-07-24 18:49:36 +020013import unittest.mock
Guido van Rossum66172522001-04-06 16:32:22 +000014
Miss Islington (bot)8bec9fb2021-06-24 16:38:01 -070015import warnings
16with warnings.catch_warnings():
17 warnings.simplefilter('ignore', DeprecationWarning)
18 import asynchat
19 import asyncore
20
Serhiy Storchaka16994912020-04-25 10:06:29 +030021HOST = socket_helper.HOST
Guido van Rossum806c2462007-08-06 23:33:07 +000022SERVER_QUIT = b'QUIT\n'
Guido van Rossum66172522001-04-06 16:32:22 +000023
Guido van Rossum66172522001-04-06 16:32:22 +000024
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020025class echo_server(threading.Thread):
26 # parameter to determine the number of bytes passed back to the
27 # client each send
28 chunk_size = 1
Christian Heimesaf98da12008-01-27 15:18:18 +000029
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020030 def __init__(self, event):
31 threading.Thread.__init__(self)
32 self.event = event
33 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +030034 self.port = socket_helper.bind_port(self.sock)
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020035 # This will be set if the client wants us to wait before echoing
36 # data back.
37 self.start_resend_event = None
Guido van Rossum806c2462007-08-06 23:33:07 +000038
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020039 def run(self):
40 self.sock.listen()
41 self.event.set()
42 conn, client = self.sock.accept()
43 self.buffer = b""
44 # collect data until quit message is seen
45 while SERVER_QUIT not in self.buffer:
46 data = conn.recv(1)
47 if not data:
48 break
49 self.buffer = self.buffer + data
Guido van Rossum806c2462007-08-06 23:33:07 +000050
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020051 # remove the SERVER_QUIT message
52 self.buffer = self.buffer.replace(SERVER_QUIT, b'')
Collin Winter8641c562010-03-17 23:49:15 +000053
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020054 if self.start_resend_event:
55 self.start_resend_event.wait()
56
57 # re-send entire set of collected data
58 try:
59 # this may fail on some tests, such as test_close_when_done,
60 # since the client closes the channel when it's done sending
61 while self.buffer:
62 n = conn.send(self.buffer[:self.chunk_size])
63 time.sleep(0.001)
64 self.buffer = self.buffer[n:]
65 except:
66 pass
67
68 conn.close()
69 self.sock.close()
70
71class echo_client(asynchat.async_chat):
72
73 def __init__(self, terminator, server_port):
74 asynchat.async_chat.__init__(self)
75 self.contents = []
76 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
77 self.connect((HOST, server_port))
78 self.set_terminator(terminator)
79 self.buffer = b""
80
Adam Johnson892221b2019-11-19 19:45:20 +000081 def handle_connect(self):
82 pass
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020083
Adam Johnson892221b2019-11-19 19:45:20 +000084 if sys.platform == 'darwin':
85 # select.poll returns a select.POLLHUP at the end of the tests
86 # on darwin, so just ignore it
87 def handle_expt(self):
88 pass
Guido van Rossum806c2462007-08-06 23:33:07 +000089
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020090 def collect_incoming_data(self, data):
91 self.buffer += data
Guido van Rossum66172522001-04-06 16:32:22 +000092
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020093 def found_terminator(self):
94 self.contents.append(self.buffer)
95 self.buffer = b""
Guido van Rossum66172522001-04-06 16:32:22 +000096
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020097def start_echo_server():
98 event = threading.Event()
99 s = echo_server(event)
100 s.start()
101 event.wait()
102 event.clear()
103 time.sleep(0.01) # Give server time to start accepting.
104 return s, event
Guido van Rossum66172522001-04-06 16:32:22 +0000105
Guido van Rossum66172522001-04-06 16:32:22 +0000106
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000107class TestAsynchat(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000108 usepoll = False
109
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200110 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +0800111 self._threads = threading_helper.threading_setup()
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000112
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200113 def tearDown(self):
Hai Shie80697d2020-05-28 06:10:27 +0800114 threading_helper.threading_cleanup(*self._threads)
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000115
Guido van Rossum806c2462007-08-06 23:33:07 +0000116 def line_terminator_check(self, term, server_chunk):
Christian Heimesaf98da12008-01-27 15:18:18 +0000117 event = threading.Event()
118 s = echo_server(event)
Guido van Rossum806c2462007-08-06 23:33:07 +0000119 s.chunk_size = server_chunk
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000120 s.start()
Christian Heimesaf98da12008-01-27 15:18:18 +0000121 event.wait()
122 event.clear()
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200123 time.sleep(0.01) # Give server time to start accepting.
Christian Heimes5e696852008-04-09 08:37:03 +0000124 c = echo_client(term, s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000125 c.push(b"hello ")
Josiah Carlsond74900e2008-07-07 04:15:08 +0000126 c.push(b"world" + term)
127 c.push(b"I'm not dead yet!" + term)
Guido van Rossum806c2462007-08-06 23:33:07 +0000128 c.push(SERVER_QUIT)
129 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Hai Shie80697d2020-05-28 06:10:27 +0800130 threading_helper.join_thread(s)
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000131
Guido van Rossum806c2462007-08-06 23:33:07 +0000132 self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000133
Guido van Rossum806c2462007-08-06 23:33:07 +0000134 # the line terminator tests below check receiving variously-sized
135 # chunks back from the server in order to exercise all branches of
136 # async_chat.handle_read
137
138 def test_line_terminator1(self):
139 # test one-character terminator
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200140 for l in (1, 2, 3):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000141 self.line_terminator_check(b'\n', l)
Guido van Rossum806c2462007-08-06 23:33:07 +0000142
143 def test_line_terminator2(self):
144 # test two-character terminator
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200145 for l in (1, 2, 3):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000146 self.line_terminator_check(b'\r\n', l)
Guido van Rossum806c2462007-08-06 23:33:07 +0000147
148 def test_line_terminator3(self):
149 # test three-character terminator
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200150 for l in (1, 2, 3):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000151 self.line_terminator_check(b'qqq', l)
Guido van Rossum806c2462007-08-06 23:33:07 +0000152
153 def numeric_terminator_check(self, termlen):
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000154 # Try reading a fixed number of bytes
Christian Heimesaf98da12008-01-27 15:18:18 +0000155 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000156 c = echo_client(termlen, s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000157 data = b"hello world, I'm not dead yet!\n"
158 c.push(data)
159 c.push(SERVER_QUIT)
160 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Hai Shie80697d2020-05-28 06:10:27 +0800161 threading_helper.join_thread(s)
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000162
Guido van Rossum806c2462007-08-06 23:33:07 +0000163 self.assertEqual(c.contents, [data[:termlen]])
164
165 def test_numeric_terminator1(self):
166 # check that ints & longs both work (since type is
167 # explicitly checked in async_chat.handle_read)
168 self.numeric_terminator_check(1)
169
170 def test_numeric_terminator2(self):
171 self.numeric_terminator_check(6)
172
173 def test_none_terminator(self):
174 # Try reading a fixed number of bytes
Christian Heimesaf98da12008-01-27 15:18:18 +0000175 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000176 c = echo_client(None, s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000177 data = b"hello world, I'm not dead yet!\n"
178 c.push(data)
179 c.push(SERVER_QUIT)
180 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Hai Shie80697d2020-05-28 06:10:27 +0800181 threading_helper.join_thread(s)
Guido van Rossum806c2462007-08-06 23:33:07 +0000182
183 self.assertEqual(c.contents, [])
184 self.assertEqual(c.buffer, data)
185
186 def test_simple_producer(self):
Christian Heimesaf98da12008-01-27 15:18:18 +0000187 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000188 c = echo_client(b'\n', s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000189 data = b"hello world\nI'm not dead yet!\n"
190 p = asynchat.simple_producer(data+SERVER_QUIT, buffer_size=8)
191 c.push_with_producer(p)
192 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Hai Shie80697d2020-05-28 06:10:27 +0800193 threading_helper.join_thread(s)
Guido van Rossum806c2462007-08-06 23:33:07 +0000194
195 self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
196
197 def test_string_producer(self):
Christian Heimesaf98da12008-01-27 15:18:18 +0000198 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000199 c = echo_client(b'\n', s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000200 data = b"hello world\nI'm not dead yet!\n"
201 c.push_with_producer(data+SERVER_QUIT)
202 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Hai Shie80697d2020-05-28 06:10:27 +0800203 threading_helper.join_thread(s)
Guido van Rossum806c2462007-08-06 23:33:07 +0000204
205 self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
206
207 def test_empty_line(self):
208 # checks that empty lines are handled correctly
Christian Heimesaf98da12008-01-27 15:18:18 +0000209 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000210 c = echo_client(b'\n', s.port)
Josiah Carlsond74900e2008-07-07 04:15:08 +0000211 c.push(b"hello world\n\nI'm not dead yet!\n")
Guido van Rossum806c2462007-08-06 23:33:07 +0000212 c.push(SERVER_QUIT)
213 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Hai Shie80697d2020-05-28 06:10:27 +0800214 threading_helper.join_thread(s)
Guido van Rossum806c2462007-08-06 23:33:07 +0000215
216 self.assertEqual(c.contents,
217 [b"hello world", b"", b"I'm not dead yet!"])
218
219 def test_close_when_done(self):
Christian Heimesaf98da12008-01-27 15:18:18 +0000220 s, event = start_echo_server()
Collin Winter8641c562010-03-17 23:49:15 +0000221 s.start_resend_event = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000222 c = echo_client(b'\n', s.port)
Josiah Carlsond74900e2008-07-07 04:15:08 +0000223 c.push(b"hello world\nI'm not dead yet!\n")
Guido van Rossum806c2462007-08-06 23:33:07 +0000224 c.push(SERVER_QUIT)
225 c.close_when_done()
226 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Collin Winter8641c562010-03-17 23:49:15 +0000227
228 # Only allow the server to start echoing data back to the client after
229 # the client has closed its connection. This prevents a race condition
230 # where the server echoes all of its data before we can check that it
231 # got any down below.
232 s.start_resend_event.set()
Hai Shie80697d2020-05-28 06:10:27 +0800233 threading_helper.join_thread(s)
Guido van Rossum806c2462007-08-06 23:33:07 +0000234
235 self.assertEqual(c.contents, [])
236 # the server might have been able to send a byte or two back, but this
237 # at least checks that it received something and didn't just fail
238 # (which could still result in the client not having received anything)
Alexandre Vassalotti953f5582009-07-22 21:29:01 +0000239 self.assertGreater(len(s.buffer), 0)
Guido van Rossum806c2462007-08-06 23:33:07 +0000240
Victor Stinnerd9e810a2014-07-08 00:00:30 +0200241 def test_push(self):
242 # Issue #12523: push() should raise a TypeError if it doesn't get
243 # a bytes string
244 s, event = start_echo_server()
245 c = echo_client(b'\n', s.port)
246 data = b'bytes\n'
247 c.push(data)
248 c.push(bytearray(data))
249 c.push(memoryview(data))
250 self.assertRaises(TypeError, c.push, 10)
251 self.assertRaises(TypeError, c.push, 'unicode')
252 c.push(SERVER_QUIT)
253 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Hai Shie80697d2020-05-28 06:10:27 +0800254 threading_helper.join_thread(s)
Victor Stinnerd9e810a2014-07-08 00:00:30 +0200255 self.assertEqual(c.contents, [b'bytes', b'bytes', b'bytes'])
256
Guido van Rossum806c2462007-08-06 23:33:07 +0000257
258class TestAsynchat_WithPoll(TestAsynchat):
259 usepoll = True
260
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200261
Victor Stinner45cff662014-07-24 18:49:36 +0200262class TestAsynchatMocked(unittest.TestCase):
263 def test_blockingioerror(self):
264 # Issue #16133: handle_read() must ignore BlockingIOError
265 sock = unittest.mock.Mock()
266 sock.recv.side_effect = BlockingIOError(errno.EAGAIN)
267
268 dispatcher = asynchat.async_chat()
269 dispatcher.set_socket(sock)
270 self.addCleanup(dispatcher.del_channel)
271
272 with unittest.mock.patch.object(dispatcher, 'handle_error') as error:
273 dispatcher.handle_read()
274 self.assertFalse(error.called)
275
276
Guido van Rossum806c2462007-08-06 23:33:07 +0000277class TestHelperFunctions(unittest.TestCase):
278 def test_find_prefix_at_end(self):
279 self.assertEqual(asynchat.find_prefix_at_end("qwerty\r", "\r\n"), 1)
280 self.assertEqual(asynchat.find_prefix_at_end("qwertydkjf", "\r\n"), 0)
281
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200282
Victor Stinner630a4f62014-07-08 00:26:36 +0200283class TestNotConnected(unittest.TestCase):
284 def test_disallow_negative_terminator(self):
285 # Issue #11259
286 client = asynchat.async_chat()
287 self.assertRaises(ValueError, client.set_terminator, -1)
288
289
290
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000291if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400292 unittest.main()