blob: 3a33fc8b2d783e9b391408758d703cc61ac50569 [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
4
5# If this fails, the test will be skipped.
6thread = support.import_module('_thread')
7
Victor Stinnerfd5d1b52014-07-08 00:16:54 +02008import asynchat
9import asyncore
Victor Stinner45cff662014-07-24 18:49:36 +020010import errno
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020011import socket
Guido van Rossum806c2462007-08-06 23:33:07 +000012import sys
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020013import time
14import unittest
Giampaolo Rodola'bd048762014-06-21 13:58:30 +020015import warnings
Victor Stinner45cff662014-07-24 18:49:36 +020016import unittest.mock
Victor Stinner45df8202010-04-28 22:31:17 +000017try:
18 import threading
19except ImportError:
20 threading = None
Guido van Rossum66172522001-04-06 16:32:22 +000021
Benjamin Petersonee8712c2008-05-20 21:35:26 +000022HOST = support.HOST
Guido van Rossum806c2462007-08-06 23:33:07 +000023SERVER_QUIT = b'QUIT\n'
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +020024TIMEOUT = 3.0
Guido van Rossum66172522001-04-06 16:32:22 +000025
Victor Stinner45df8202010-04-28 22:31:17 +000026if threading:
27 class echo_server(threading.Thread):
28 # parameter to determine the number of bytes passed back to the
29 # client each send
30 chunk_size = 1
Guido van Rossum66172522001-04-06 16:32:22 +000031
Victor Stinner45df8202010-04-28 22:31:17 +000032 def __init__(self, event):
33 threading.Thread.__init__(self)
34 self.event = event
35 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
36 self.port = support.bind_port(self.sock)
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020037 # This will be set if the client wants us to wait before echoing
38 # data back.
Victor Stinner45df8202010-04-28 22:31:17 +000039 self.start_resend_event = None
Christian Heimesaf98da12008-01-27 15:18:18 +000040
Victor Stinner45df8202010-04-28 22:31:17 +000041 def run(self):
Charles-François Natali6e204602014-07-23 19:28:13 +010042 self.sock.listen()
Victor Stinner45df8202010-04-28 22:31:17 +000043 self.event.set()
44 conn, client = self.sock.accept()
45 self.buffer = b""
46 # collect data until quit message is seen
47 while SERVER_QUIT not in self.buffer:
48 data = conn.recv(1)
49 if not data:
50 break
51 self.buffer = self.buffer + data
Guido van Rossum806c2462007-08-06 23:33:07 +000052
Victor Stinner45df8202010-04-28 22:31:17 +000053 # remove the SERVER_QUIT message
54 self.buffer = self.buffer.replace(SERVER_QUIT, b'')
Guido van Rossum806c2462007-08-06 23:33:07 +000055
Victor Stinner45df8202010-04-28 22:31:17 +000056 if self.start_resend_event:
57 self.start_resend_event.wait()
Collin Winter8641c562010-03-17 23:49:15 +000058
Victor Stinner45df8202010-04-28 22:31:17 +000059 # re-send entire set of collected data
60 try:
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020061 # this may fail on some tests, such as test_close_when_done,
62 # since the client closes the channel when it's done sending
Victor Stinner45df8202010-04-28 22:31:17 +000063 while self.buffer:
64 n = conn.send(self.buffer[:self.chunk_size])
65 time.sleep(0.001)
66 self.buffer = self.buffer[n:]
67 except:
68 pass
Guido van Rossum806c2462007-08-06 23:33:07 +000069
Victor Stinner45df8202010-04-28 22:31:17 +000070 conn.close()
71 self.sock.close()
Guido van Rossum66172522001-04-06 16:32:22 +000072
Victor Stinner45df8202010-04-28 22:31:17 +000073 class echo_client(asynchat.async_chat):
Guido van Rossum66172522001-04-06 16:32:22 +000074
Victor Stinner45df8202010-04-28 22:31:17 +000075 def __init__(self, terminator, server_port):
76 asynchat.async_chat.__init__(self)
77 self.contents = []
78 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
79 self.connect((HOST, server_port))
80 self.set_terminator(terminator)
81 self.buffer = b""
Guido van Rossum66172522001-04-06 16:32:22 +000082
Victor Stinner45df8202010-04-28 22:31:17 +000083 def handle_connect(self):
84 pass
Guido van Rossum806c2462007-08-06 23:33:07 +000085
Victor Stinner45df8202010-04-28 22:31:17 +000086 if sys.platform == 'darwin':
87 # select.poll returns a select.POLLHUP at the end of the tests
88 # on darwin, so just ignore it
89 def handle_expt(self):
90 pass
Guido van Rossum66172522001-04-06 16:32:22 +000091
Victor Stinner45df8202010-04-28 22:31:17 +000092 def collect_incoming_data(self, data):
93 self.buffer += data
Guido van Rossum66172522001-04-06 16:32:22 +000094
Victor Stinner45df8202010-04-28 22:31:17 +000095 def found_terminator(self):
96 self.contents.append(self.buffer)
97 self.buffer = b""
98
99 def start_echo_server():
100 event = threading.Event()
101 s = echo_server(event)
102 s.start()
103 event.wait()
104 event.clear()
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200105 time.sleep(0.01) # Give server time to start accepting.
Victor Stinner45df8202010-04-28 22:31:17 +0000106 return s, event
Guido van Rossum66172522001-04-06 16:32:22 +0000107
Guido van Rossum66172522001-04-06 16:32:22 +0000108
Victor Stinner45df8202010-04-28 22:31:17 +0000109@unittest.skipUnless(threading, 'Threading required for this test.')
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000110class TestAsynchat(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000111 usepoll = False
112
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200113 def setUp(self):
Antoine Pitroue03866f2009-10-30 17:58:27 +0000114 self._threads = support.threading_setup()
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000115
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200116 def tearDown(self):
Antoine Pitroue03866f2009-10-30 17:58:27 +0000117 support.threading_cleanup(*self._threads)
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000118
Guido van Rossum806c2462007-08-06 23:33:07 +0000119 def line_terminator_check(self, term, server_chunk):
Christian Heimesaf98da12008-01-27 15:18:18 +0000120 event = threading.Event()
121 s = echo_server(event)
Guido van Rossum806c2462007-08-06 23:33:07 +0000122 s.chunk_size = server_chunk
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000123 s.start()
Christian Heimesaf98da12008-01-27 15:18:18 +0000124 event.wait()
125 event.clear()
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200126 time.sleep(0.01) # Give server time to start accepting.
Christian Heimes5e696852008-04-09 08:37:03 +0000127 c = echo_client(term, s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000128 c.push(b"hello ")
Josiah Carlsond74900e2008-07-07 04:15:08 +0000129 c.push(b"world" + term)
130 c.push(b"I'm not dead yet!" + term)
Guido van Rossum806c2462007-08-06 23:33:07 +0000131 c.push(SERVER_QUIT)
132 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200133 s.join(timeout=TIMEOUT)
134 if s.is_alive():
135 self.fail("join() timed out")
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000136
Guido van Rossum806c2462007-08-06 23:33:07 +0000137 self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000138
Guido van Rossum806c2462007-08-06 23:33:07 +0000139 # the line terminator tests below check receiving variously-sized
140 # chunks back from the server in order to exercise all branches of
141 # async_chat.handle_read
142
143 def test_line_terminator1(self):
144 # test one-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'\n', l)
Guido van Rossum806c2462007-08-06 23:33:07 +0000147
148 def test_line_terminator2(self):
149 # test two-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'\r\n', l)
Guido van Rossum806c2462007-08-06 23:33:07 +0000152
153 def test_line_terminator3(self):
154 # test three-character terminator
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200155 for l in (1, 2, 3):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000156 self.line_terminator_check(b'qqq', l)
Guido van Rossum806c2462007-08-06 23:33:07 +0000157
158 def numeric_terminator_check(self, termlen):
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000159 # Try reading a fixed number of bytes
Christian Heimesaf98da12008-01-27 15:18:18 +0000160 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000161 c = echo_client(termlen, s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000162 data = b"hello world, I'm not dead yet!\n"
163 c.push(data)
164 c.push(SERVER_QUIT)
165 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200166 s.join(timeout=TIMEOUT)
167 if s.is_alive():
168 self.fail("join() timed out")
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000169
Guido van Rossum806c2462007-08-06 23:33:07 +0000170 self.assertEqual(c.contents, [data[:termlen]])
171
172 def test_numeric_terminator1(self):
173 # check that ints & longs both work (since type is
174 # explicitly checked in async_chat.handle_read)
175 self.numeric_terminator_check(1)
176
177 def test_numeric_terminator2(self):
178 self.numeric_terminator_check(6)
179
180 def test_none_terminator(self):
181 # Try reading a fixed number of bytes
Christian Heimesaf98da12008-01-27 15:18:18 +0000182 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000183 c = echo_client(None, s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000184 data = b"hello world, I'm not dead yet!\n"
185 c.push(data)
186 c.push(SERVER_QUIT)
187 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200188 s.join(timeout=TIMEOUT)
189 if s.is_alive():
190 self.fail("join() timed out")
Guido van Rossum806c2462007-08-06 23:33:07 +0000191
192 self.assertEqual(c.contents, [])
193 self.assertEqual(c.buffer, data)
194
195 def test_simple_producer(self):
Christian Heimesaf98da12008-01-27 15:18:18 +0000196 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000197 c = echo_client(b'\n', s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000198 data = b"hello world\nI'm not dead yet!\n"
199 p = asynchat.simple_producer(data+SERVER_QUIT, buffer_size=8)
200 c.push_with_producer(p)
201 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200202 s.join(timeout=TIMEOUT)
203 if s.is_alive():
204 self.fail("join() timed out")
Guido van Rossum806c2462007-08-06 23:33:07 +0000205
206 self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
207
208 def test_string_producer(self):
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)
Guido van Rossum806c2462007-08-06 23:33:07 +0000211 data = b"hello world\nI'm not dead yet!\n"
212 c.push_with_producer(data+SERVER_QUIT)
213 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200214 s.join(timeout=TIMEOUT)
215 if s.is_alive():
216 self.fail("join() timed out")
Guido van Rossum806c2462007-08-06 23:33:07 +0000217
218 self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
219
220 def test_empty_line(self):
221 # checks that empty lines are handled correctly
Christian Heimesaf98da12008-01-27 15:18:18 +0000222 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000223 c = echo_client(b'\n', s.port)
Josiah Carlsond74900e2008-07-07 04:15:08 +0000224 c.push(b"hello world\n\nI'm not dead yet!\n")
Guido van Rossum806c2462007-08-06 23:33:07 +0000225 c.push(SERVER_QUIT)
226 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200227 s.join(timeout=TIMEOUT)
228 if s.is_alive():
229 self.fail("join() timed out")
Guido van Rossum806c2462007-08-06 23:33:07 +0000230
231 self.assertEqual(c.contents,
232 [b"hello world", b"", b"I'm not dead yet!"])
233
234 def test_close_when_done(self):
Christian Heimesaf98da12008-01-27 15:18:18 +0000235 s, event = start_echo_server()
Collin Winter8641c562010-03-17 23:49:15 +0000236 s.start_resend_event = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000237 c = echo_client(b'\n', s.port)
Josiah Carlsond74900e2008-07-07 04:15:08 +0000238 c.push(b"hello world\nI'm not dead yet!\n")
Guido van Rossum806c2462007-08-06 23:33:07 +0000239 c.push(SERVER_QUIT)
240 c.close_when_done()
241 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Collin Winter8641c562010-03-17 23:49:15 +0000242
243 # Only allow the server to start echoing data back to the client after
244 # the client has closed its connection. This prevents a race condition
245 # where the server echoes all of its data before we can check that it
246 # got any down below.
247 s.start_resend_event.set()
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200248 s.join(timeout=TIMEOUT)
249 if s.is_alive():
250 self.fail("join() timed out")
Guido van Rossum806c2462007-08-06 23:33:07 +0000251
252 self.assertEqual(c.contents, [])
253 # the server might have been able to send a byte or two back, but this
254 # at least checks that it received something and didn't just fail
255 # (which could still result in the client not having received anything)
Alexandre Vassalotti953f5582009-07-22 21:29:01 +0000256 self.assertGreater(len(s.buffer), 0)
Guido van Rossum806c2462007-08-06 23:33:07 +0000257
Victor Stinnerd9e810a2014-07-08 00:00:30 +0200258 def test_push(self):
259 # Issue #12523: push() should raise a TypeError if it doesn't get
260 # a bytes string
261 s, event = start_echo_server()
262 c = echo_client(b'\n', s.port)
263 data = b'bytes\n'
264 c.push(data)
265 c.push(bytearray(data))
266 c.push(memoryview(data))
267 self.assertRaises(TypeError, c.push, 10)
268 self.assertRaises(TypeError, c.push, 'unicode')
269 c.push(SERVER_QUIT)
270 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
271 s.join(timeout=TIMEOUT)
272 self.assertEqual(c.contents, [b'bytes', b'bytes', b'bytes'])
273
Guido van Rossum806c2462007-08-06 23:33:07 +0000274
275class TestAsynchat_WithPoll(TestAsynchat):
276 usepoll = True
277
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200278
Victor Stinner45cff662014-07-24 18:49:36 +0200279class TestAsynchatMocked(unittest.TestCase):
280 def test_blockingioerror(self):
281 # Issue #16133: handle_read() must ignore BlockingIOError
282 sock = unittest.mock.Mock()
283 sock.recv.side_effect = BlockingIOError(errno.EAGAIN)
284
285 dispatcher = asynchat.async_chat()
286 dispatcher.set_socket(sock)
287 self.addCleanup(dispatcher.del_channel)
288
289 with unittest.mock.patch.object(dispatcher, 'handle_error') as error:
290 dispatcher.handle_read()
291 self.assertFalse(error.called)
292
293
Guido van Rossum806c2462007-08-06 23:33:07 +0000294class TestHelperFunctions(unittest.TestCase):
295 def test_find_prefix_at_end(self):
296 self.assertEqual(asynchat.find_prefix_at_end("qwerty\r", "\r\n"), 1)
297 self.assertEqual(asynchat.find_prefix_at_end("qwertydkjf", "\r\n"), 0)
298
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200299
Guido van Rossum806c2462007-08-06 23:33:07 +0000300class TestFifo(unittest.TestCase):
301 def test_basic(self):
Berker Peksage4857f32014-07-09 03:12:23 +0300302 with self.assertWarns(DeprecationWarning) as cm:
Giampaolo Rodola'bd048762014-06-21 13:58:30 +0200303 f = asynchat.fifo()
Berker Peksage4857f32014-07-09 03:12:23 +0300304 self.assertEqual(str(cm.warning),
305 "fifo class will be removed in Python 3.6")
Guido van Rossum806c2462007-08-06 23:33:07 +0000306 f.push(7)
307 f.push(b'a')
308 self.assertEqual(len(f), 2)
309 self.assertEqual(f.first(), 7)
310 self.assertEqual(f.pop(), (1, 7))
311 self.assertEqual(len(f), 1)
312 self.assertEqual(f.first(), b'a')
313 self.assertEqual(f.is_empty(), False)
314 self.assertEqual(f.pop(), (1, b'a'))
315 self.assertEqual(len(f), 0)
316 self.assertEqual(f.is_empty(), True)
317 self.assertEqual(f.pop(), (0, None))
318
319 def test_given_list(self):
Berker Peksage4857f32014-07-09 03:12:23 +0300320 with self.assertWarns(DeprecationWarning) as cm:
Giampaolo Rodola'bd048762014-06-21 13:58:30 +0200321 f = asynchat.fifo([b'x', 17, 3])
Berker Peksage4857f32014-07-09 03:12:23 +0300322 self.assertEqual(str(cm.warning),
323 "fifo class will be removed in Python 3.6")
Guido van Rossum806c2462007-08-06 23:33:07 +0000324 self.assertEqual(len(f), 3)
325 self.assertEqual(f.pop(), (1, b'x'))
326 self.assertEqual(f.pop(), (1, 17))
327 self.assertEqual(f.pop(), (1, 3))
328 self.assertEqual(f.pop(), (0, None))
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000329
330
Victor Stinner630a4f62014-07-08 00:26:36 +0200331class TestNotConnected(unittest.TestCase):
332 def test_disallow_negative_terminator(self):
333 # Issue #11259
334 client = asynchat.async_chat()
335 self.assertRaises(ValueError, client.set_terminator, -1)
336
337
338
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000339if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400340 unittest.main()