blob: 0eba76db4782102a9d42c0224527c4eaeeecbfe7 [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
Victor Stinner45cff662014-07-24 18:49:36 +020015import unittest.mock
Victor Stinner45df8202010-04-28 22:31:17 +000016try:
17 import threading
18except ImportError:
19 threading = None
Guido van Rossum66172522001-04-06 16:32:22 +000020
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021HOST = support.HOST
Guido van Rossum806c2462007-08-06 23:33:07 +000022SERVER_QUIT = b'QUIT\n'
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +020023TIMEOUT = 3.0
Guido van Rossum66172522001-04-06 16:32:22 +000024
Victor Stinner45df8202010-04-28 22:31:17 +000025if threading:
26 class echo_server(threading.Thread):
27 # parameter to determine the number of bytes passed back to the
28 # client each send
29 chunk_size = 1
Guido van Rossum66172522001-04-06 16:32:22 +000030
Victor Stinner45df8202010-04-28 22:31:17 +000031 def __init__(self, event):
32 threading.Thread.__init__(self)
33 self.event = event
34 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
35 self.port = support.bind_port(self.sock)
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020036 # This will be set if the client wants us to wait before echoing
37 # data back.
Victor Stinner45df8202010-04-28 22:31:17 +000038 self.start_resend_event = None
Christian Heimesaf98da12008-01-27 15:18:18 +000039
Victor Stinner45df8202010-04-28 22:31:17 +000040 def run(self):
Charles-François Natali6e204602014-07-23 19:28:13 +010041 self.sock.listen()
Victor Stinner45df8202010-04-28 22:31:17 +000042 self.event.set()
43 conn, client = self.sock.accept()
44 self.buffer = b""
45 # collect data until quit message is seen
46 while SERVER_QUIT not in self.buffer:
47 data = conn.recv(1)
48 if not data:
49 break
50 self.buffer = self.buffer + data
Guido van Rossum806c2462007-08-06 23:33:07 +000051
Victor Stinner45df8202010-04-28 22:31:17 +000052 # remove the SERVER_QUIT message
53 self.buffer = self.buffer.replace(SERVER_QUIT, b'')
Guido van Rossum806c2462007-08-06 23:33:07 +000054
Victor Stinner45df8202010-04-28 22:31:17 +000055 if self.start_resend_event:
56 self.start_resend_event.wait()
Collin Winter8641c562010-03-17 23:49:15 +000057
Victor Stinner45df8202010-04-28 22:31:17 +000058 # re-send entire set of collected data
59 try:
Victor Stinnerfd5d1b52014-07-08 00:16:54 +020060 # this may fail on some tests, such as test_close_when_done,
61 # since the client closes the channel when it's done sending
Victor Stinner45df8202010-04-28 22:31:17 +000062 while self.buffer:
63 n = conn.send(self.buffer[:self.chunk_size])
64 time.sleep(0.001)
65 self.buffer = self.buffer[n:]
66 except:
67 pass
Guido van Rossum806c2462007-08-06 23:33:07 +000068
Victor Stinner45df8202010-04-28 22:31:17 +000069 conn.close()
70 self.sock.close()
Guido van Rossum66172522001-04-06 16:32:22 +000071
Victor Stinner45df8202010-04-28 22:31:17 +000072 class echo_client(asynchat.async_chat):
Guido van Rossum66172522001-04-06 16:32:22 +000073
Victor Stinner45df8202010-04-28 22:31:17 +000074 def __init__(self, terminator, server_port):
75 asynchat.async_chat.__init__(self)
76 self.contents = []
77 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
78 self.connect((HOST, server_port))
79 self.set_terminator(terminator)
80 self.buffer = b""
Guido van Rossum66172522001-04-06 16:32:22 +000081
Victor Stinner45df8202010-04-28 22:31:17 +000082 def handle_connect(self):
83 pass
Guido van Rossum806c2462007-08-06 23:33:07 +000084
Victor Stinner45df8202010-04-28 22:31:17 +000085 if sys.platform == 'darwin':
86 # select.poll returns a select.POLLHUP at the end of the tests
87 # on darwin, so just ignore it
88 def handle_expt(self):
89 pass
Guido van Rossum66172522001-04-06 16:32:22 +000090
Victor Stinner45df8202010-04-28 22:31:17 +000091 def collect_incoming_data(self, data):
92 self.buffer += data
Guido van Rossum66172522001-04-06 16:32:22 +000093
Victor Stinner45df8202010-04-28 22:31:17 +000094 def found_terminator(self):
95 self.contents.append(self.buffer)
96 self.buffer = b""
97
98 def start_echo_server():
99 event = threading.Event()
100 s = echo_server(event)
101 s.start()
102 event.wait()
103 event.clear()
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200104 time.sleep(0.01) # Give server time to start accepting.
Victor Stinner45df8202010-04-28 22:31:17 +0000105 return s, event
Guido van Rossum66172522001-04-06 16:32:22 +0000106
Guido van Rossum66172522001-04-06 16:32:22 +0000107
Victor Stinner45df8202010-04-28 22:31:17 +0000108@unittest.skipUnless(threading, 'Threading required for this test.')
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000109class TestAsynchat(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000110 usepoll = False
111
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200112 def setUp(self):
Antoine Pitroue03866f2009-10-30 17:58:27 +0000113 self._threads = support.threading_setup()
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000114
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200115 def tearDown(self):
Antoine Pitroue03866f2009-10-30 17:58:27 +0000116 support.threading_cleanup(*self._threads)
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000117
Guido van Rossum806c2462007-08-06 23:33:07 +0000118 def line_terminator_check(self, term, server_chunk):
Christian Heimesaf98da12008-01-27 15:18:18 +0000119 event = threading.Event()
120 s = echo_server(event)
Guido van Rossum806c2462007-08-06 23:33:07 +0000121 s.chunk_size = server_chunk
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000122 s.start()
Christian Heimesaf98da12008-01-27 15:18:18 +0000123 event.wait()
124 event.clear()
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200125 time.sleep(0.01) # Give server time to start accepting.
Christian Heimes5e696852008-04-09 08:37:03 +0000126 c = echo_client(term, s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000127 c.push(b"hello ")
Josiah Carlsond74900e2008-07-07 04:15:08 +0000128 c.push(b"world" + term)
129 c.push(b"I'm not dead yet!" + term)
Guido van Rossum806c2462007-08-06 23:33:07 +0000130 c.push(SERVER_QUIT)
131 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200132 s.join(timeout=TIMEOUT)
133 if s.is_alive():
134 self.fail("join() timed out")
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000135
Guido van Rossum806c2462007-08-06 23:33:07 +0000136 self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000137
Guido van Rossum806c2462007-08-06 23:33:07 +0000138 # the line terminator tests below check receiving variously-sized
139 # chunks back from the server in order to exercise all branches of
140 # async_chat.handle_read
141
142 def test_line_terminator1(self):
143 # test one-character terminator
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200144 for l in (1, 2, 3):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000145 self.line_terminator_check(b'\n', l)
Guido van Rossum806c2462007-08-06 23:33:07 +0000146
147 def test_line_terminator2(self):
148 # test two-character terminator
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200149 for l in (1, 2, 3):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000150 self.line_terminator_check(b'\r\n', l)
Guido van Rossum806c2462007-08-06 23:33:07 +0000151
152 def test_line_terminator3(self):
153 # test three-character terminator
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200154 for l in (1, 2, 3):
Josiah Carlsond74900e2008-07-07 04:15:08 +0000155 self.line_terminator_check(b'qqq', l)
Guido van Rossum806c2462007-08-06 23:33:07 +0000156
157 def numeric_terminator_check(self, termlen):
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000158 # Try reading a fixed number of bytes
Christian Heimesaf98da12008-01-27 15:18:18 +0000159 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000160 c = echo_client(termlen, s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000161 data = b"hello world, I'm not dead yet!\n"
162 c.push(data)
163 c.push(SERVER_QUIT)
164 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200165 s.join(timeout=TIMEOUT)
166 if s.is_alive():
167 self.fail("join() timed out")
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000168
Guido van Rossum806c2462007-08-06 23:33:07 +0000169 self.assertEqual(c.contents, [data[:termlen]])
170
171 def test_numeric_terminator1(self):
172 # check that ints & longs both work (since type is
173 # explicitly checked in async_chat.handle_read)
174 self.numeric_terminator_check(1)
175
176 def test_numeric_terminator2(self):
177 self.numeric_terminator_check(6)
178
179 def test_none_terminator(self):
180 # Try reading a fixed number of bytes
Christian Heimesaf98da12008-01-27 15:18:18 +0000181 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000182 c = echo_client(None, s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000183 data = b"hello world, I'm not dead yet!\n"
184 c.push(data)
185 c.push(SERVER_QUIT)
186 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200187 s.join(timeout=TIMEOUT)
188 if s.is_alive():
189 self.fail("join() timed out")
Guido van Rossum806c2462007-08-06 23:33:07 +0000190
191 self.assertEqual(c.contents, [])
192 self.assertEqual(c.buffer, data)
193
194 def test_simple_producer(self):
Christian Heimesaf98da12008-01-27 15:18:18 +0000195 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000196 c = echo_client(b'\n', s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000197 data = b"hello world\nI'm not dead yet!\n"
198 p = asynchat.simple_producer(data+SERVER_QUIT, buffer_size=8)
199 c.push_with_producer(p)
200 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200201 s.join(timeout=TIMEOUT)
202 if s.is_alive():
203 self.fail("join() timed out")
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_string_producer(self):
Christian Heimesaf98da12008-01-27 15:18:18 +0000208 s, event = start_echo_server()
Christian Heimes5e696852008-04-09 08:37:03 +0000209 c = echo_client(b'\n', s.port)
Guido van Rossum806c2462007-08-06 23:33:07 +0000210 data = b"hello world\nI'm not dead yet!\n"
211 c.push_with_producer(data+SERVER_QUIT)
212 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200213 s.join(timeout=TIMEOUT)
214 if s.is_alive():
215 self.fail("join() timed out")
Guido van Rossum806c2462007-08-06 23:33:07 +0000216
217 self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
218
219 def test_empty_line(self):
220 # checks that empty lines are handled correctly
Christian Heimesaf98da12008-01-27 15:18:18 +0000221 s, event = start_echo_server()
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\n\nI'm not dead yet!\n")
Guido van Rossum806c2462007-08-06 23:33:07 +0000224 c.push(SERVER_QUIT)
225 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200226 s.join(timeout=TIMEOUT)
227 if s.is_alive():
228 self.fail("join() timed out")
Guido van Rossum806c2462007-08-06 23:33:07 +0000229
230 self.assertEqual(c.contents,
231 [b"hello world", b"", b"I'm not dead yet!"])
232
233 def test_close_when_done(self):
Christian Heimesaf98da12008-01-27 15:18:18 +0000234 s, event = start_echo_server()
Collin Winter8641c562010-03-17 23:49:15 +0000235 s.start_resend_event = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000236 c = echo_client(b'\n', s.port)
Josiah Carlsond74900e2008-07-07 04:15:08 +0000237 c.push(b"hello world\nI'm not dead yet!\n")
Guido van Rossum806c2462007-08-06 23:33:07 +0000238 c.push(SERVER_QUIT)
239 c.close_when_done()
240 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
Collin Winter8641c562010-03-17 23:49:15 +0000241
242 # Only allow the server to start echoing data back to the client after
243 # the client has closed its connection. This prevents a race condition
244 # where the server echoes all of its data before we can check that it
245 # got any down below.
246 s.start_resend_event.set()
Giampaolo Rodola'3cb09062013-05-16 15:21:53 +0200247 s.join(timeout=TIMEOUT)
248 if s.is_alive():
249 self.fail("join() timed out")
Guido van Rossum806c2462007-08-06 23:33:07 +0000250
251 self.assertEqual(c.contents, [])
252 # the server might have been able to send a byte or two back, but this
253 # at least checks that it received something and didn't just fail
254 # (which could still result in the client not having received anything)
Alexandre Vassalotti953f5582009-07-22 21:29:01 +0000255 self.assertGreater(len(s.buffer), 0)
Guido van Rossum806c2462007-08-06 23:33:07 +0000256
Victor Stinnerd9e810a2014-07-08 00:00:30 +0200257 def test_push(self):
258 # Issue #12523: push() should raise a TypeError if it doesn't get
259 # a bytes string
260 s, event = start_echo_server()
261 c = echo_client(b'\n', s.port)
262 data = b'bytes\n'
263 c.push(data)
264 c.push(bytearray(data))
265 c.push(memoryview(data))
266 self.assertRaises(TypeError, c.push, 10)
267 self.assertRaises(TypeError, c.push, 'unicode')
268 c.push(SERVER_QUIT)
269 asyncore.loop(use_poll=self.usepoll, count=300, timeout=.01)
270 s.join(timeout=TIMEOUT)
271 self.assertEqual(c.contents, [b'bytes', b'bytes', b'bytes'])
272
Guido van Rossum806c2462007-08-06 23:33:07 +0000273
274class TestAsynchat_WithPoll(TestAsynchat):
275 usepoll = True
276
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200277
Victor Stinner45cff662014-07-24 18:49:36 +0200278class TestAsynchatMocked(unittest.TestCase):
279 def test_blockingioerror(self):
280 # Issue #16133: handle_read() must ignore BlockingIOError
281 sock = unittest.mock.Mock()
282 sock.recv.side_effect = BlockingIOError(errno.EAGAIN)
283
284 dispatcher = asynchat.async_chat()
285 dispatcher.set_socket(sock)
286 self.addCleanup(dispatcher.del_channel)
287
288 with unittest.mock.patch.object(dispatcher, 'handle_error') as error:
289 dispatcher.handle_read()
290 self.assertFalse(error.called)
291
292
Guido van Rossum806c2462007-08-06 23:33:07 +0000293class TestHelperFunctions(unittest.TestCase):
294 def test_find_prefix_at_end(self):
295 self.assertEqual(asynchat.find_prefix_at_end("qwerty\r", "\r\n"), 1)
296 self.assertEqual(asynchat.find_prefix_at_end("qwertydkjf", "\r\n"), 0)
297
Victor Stinnerfd5d1b52014-07-08 00:16:54 +0200298
Victor Stinner630a4f62014-07-08 00:26:36 +0200299class TestNotConnected(unittest.TestCase):
300 def test_disallow_negative_terminator(self):
301 # Issue #11259
302 client = asynchat.async_chat()
303 self.assertRaises(ValueError, client.set_terminator, -1)
304
305
306
Andrew M. Kuchling5ac25342005-06-09 14:56:31 +0000307if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400308 unittest.main()