blob: ca23301cd1f89e4ed5e3e7dad00c401a0c7aaf55 [file] [log] [blame]
Christian Heimes292d3512008-02-03 16:51:08 +00001"""
Alexandre Vassalottice261952008-05-12 02:31:37 +00002Test suite for socketserver.
Christian Heimes292d3512008-02-03 16:51:08 +00003"""
Guido van Rossum39f1b362001-07-10 11:52:38 +00004
Christian Heimes70e7ea22008-02-28 20:02:27 +00005import contextlib
Christian Heimes292d3512008-02-03 16:51:08 +00006import imp
Christian Heimes9e7f1d22008-02-28 12:27:11 +00007import os
Guido van Rossum39f1b362001-07-10 11:52:38 +00008import select
Christian Heimes9e7f1d22008-02-28 12:27:11 +00009import signal
10import socket
Antoine Pitroub0a9c662012-04-09 00:47:24 +020011import select
12import errno
Christian Heimes9e7f1d22008-02-28 12:27:11 +000013import tempfile
Christian Heimes292d3512008-02-03 16:51:08 +000014import unittest
Alexandre Vassalottice261952008-05-12 02:31:37 +000015import socketserver
Christian Heimes292d3512008-02-03 16:51:08 +000016
Benjamin Petersonee8712c2008-05-20 21:35:26 +000017import test.support
Antoine Pitrouc00d4b42009-10-27 21:32:38 +000018from test.support import reap_children, reap_threads, verbose
Victor Stinner45df8202010-04-28 22:31:17 +000019try:
20 import threading
21except ImportError:
22 threading = None
Christian Heimes292d3512008-02-03 16:51:08 +000023
Benjamin Petersonee8712c2008-05-20 21:35:26 +000024test.support.requires("network")
Guido van Rossum39f1b362001-07-10 11:52:38 +000025
Christian Heimes292d3512008-02-03 16:51:08 +000026TEST_STR = b"hello world\n"
Benjamin Petersonee8712c2008-05-20 21:35:26 +000027HOST = test.support.HOST
Christian Heimes292d3512008-02-03 16:51:08 +000028
29HAVE_UNIX_SOCKETS = hasattr(socket, "AF_UNIX")
30HAVE_FORKING = hasattr(os, "fork") and os.name != "os2"
31
Christian Heimesdd15f6c2008-03-16 00:07:10 +000032def signal_alarm(n):
33 """Call signal.alarm when it exists (i.e. not on Windows)."""
34 if hasattr(signal, 'alarm'):
35 signal.alarm(n)
Guido van Rossum39f1b362001-07-10 11:52:38 +000036
Antoine Pitrouf18d6f32012-04-09 01:16:47 +020037# Remember real select() to avoid interferences with mocking
38_real_select = select.select
39
Christian Heimes292d3512008-02-03 16:51:08 +000040def receive(sock, n, timeout=20):
Antoine Pitrouf18d6f32012-04-09 01:16:47 +020041 r, w, x = _real_select([sock], [], [], timeout)
Christian Heimes292d3512008-02-03 16:51:08 +000042 if sock in r:
43 return sock.recv(n)
44 else:
45 raise RuntimeError("timed out on %r" % (sock,))
46
Christian Heimes15ebc882008-02-04 18:48:49 +000047if HAVE_UNIX_SOCKETS:
Alexandre Vassalottice261952008-05-12 02:31:37 +000048 class ForkingUnixStreamServer(socketserver.ForkingMixIn,
49 socketserver.UnixStreamServer):
Christian Heimes15ebc882008-02-04 18:48:49 +000050 pass
Christian Heimes292d3512008-02-03 16:51:08 +000051
Alexandre Vassalottice261952008-05-12 02:31:37 +000052 class ForkingUnixDatagramServer(socketserver.ForkingMixIn,
53 socketserver.UnixDatagramServer):
Christian Heimes15ebc882008-02-04 18:48:49 +000054 pass
Christian Heimes292d3512008-02-03 16:51:08 +000055
56
Christian Heimes70e7ea22008-02-28 20:02:27 +000057@contextlib.contextmanager
58def simple_subprocess(testcase):
59 pid = os.fork()
60 if pid == 0:
61 # Don't throw an exception; it would be caught by the test harness.
62 os._exit(72)
63 yield None
64 pid2, status = os.waitpid(pid, 0)
Ezio Melottib3aedd42010-11-20 19:04:17 +000065 testcase.assertEqual(pid2, pid)
66 testcase.assertEqual(72 << 8, status)
Christian Heimes70e7ea22008-02-28 20:02:27 +000067
68
Victor Stinner5f22e722010-05-26 17:33:03 +000069@unittest.skipUnless(threading, 'Threading required for this test.')
Christian Heimes292d3512008-02-03 16:51:08 +000070class SocketServerTest(unittest.TestCase):
71 """Test all socket servers."""
Guido van Rossum39f1b362001-07-10 11:52:38 +000072
Christian Heimes292d3512008-02-03 16:51:08 +000073 def setUp(self):
Victor Stinner5702ae62011-07-14 14:53:24 +020074 signal_alarm(60) # Kill deadlocks after 60 seconds.
Christian Heimes292d3512008-02-03 16:51:08 +000075 self.port_seed = 0
76 self.test_files = []
Guido van Rossum39f1b362001-07-10 11:52:38 +000077
Christian Heimes292d3512008-02-03 16:51:08 +000078 def tearDown(self):
Christian Heimesfe337bf2008-03-23 21:54:12 +000079 signal_alarm(0) # Didn't deadlock.
Christian Heimes292d3512008-02-03 16:51:08 +000080 reap_children()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000081
Christian Heimes292d3512008-02-03 16:51:08 +000082 for fn in self.test_files:
83 try:
84 os.remove(fn)
85 except os.error:
86 pass
87 self.test_files[:] = []
Christian Heimes292d3512008-02-03 16:51:08 +000088
89 def pickaddr(self, proto):
90 if proto == socket.AF_INET:
Christian Heimes9e7f1d22008-02-28 12:27:11 +000091 return (HOST, 0)
Christian Heimes292d3512008-02-03 16:51:08 +000092 else:
Christian Heimes9e7f1d22008-02-28 12:27:11 +000093 # XXX: We need a way to tell AF_UNIX to pick its own name
94 # like AF_INET provides port==0.
95 dir = None
96 if os.name == 'os2':
97 dir = '\socket'
98 fn = tempfile.mktemp(prefix='unix_socket.', dir=dir)
Christian Heimes292d3512008-02-03 16:51:08 +000099 if os.name == 'os2':
100 # AF_UNIX socket names on OS/2 require a specific prefix
101 # which can't include a drive letter and must also use
102 # backslashes as directory separators
103 if fn[1] == ':':
104 fn = fn[2:]
105 if fn[0] in (os.sep, os.altsep):
106 fn = fn[1:]
Christian Heimes292d3512008-02-03 16:51:08 +0000107 if os.sep == '/':
108 fn = fn.replace(os.sep, os.altsep)
109 else:
110 fn = fn.replace(os.altsep, os.sep)
111 self.test_files.append(fn)
112 return fn
113
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000114 def make_server(self, addr, svrcls, hdlrbase):
115 class MyServer(svrcls):
116 def handle_error(self, request, client_address):
117 self.close_request(request)
118 self.server_close()
119 raise
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000120
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000121 class MyHandler(hdlrbase):
122 def handle(self):
123 line = self.rfile.readline()
124 self.wfile.write(line)
125
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000126 if verbose: print("creating server")
127 server = MyServer(addr, MyHandler)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000128 self.assertEqual(server.server_address, server.socket.getsockname())
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000129 return server
130
Antoine Pitrouc00d4b42009-10-27 21:32:38 +0000131 @reap_threads
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000132 def run_server(self, svrcls, hdlrbase, testfunc):
133 server = self.make_server(self.pickaddr(svrcls.address_family),
134 svrcls, hdlrbase)
135 # We had the OS pick a port, so pull the real address out of
136 # the server.
137 addr = server.server_address
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000138 if verbose:
139 print("ADDR =", addr)
140 print("CLASS =", svrcls)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000141
142 t = threading.Thread(
143 name='%s serving' % svrcls,
144 target=server.serve_forever,
145 # Short poll interval to make the test finish quickly.
146 # Time between requests is short enough that we won't wake
147 # up spuriously too many times.
148 kwargs={'poll_interval':0.01})
Benjamin Peterson72753702008-08-18 18:09:21 +0000149 t.daemon = True # In case this function raises.
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000150 t.start()
151 if verbose: print("server running")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000152 for i in range(3):
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000153 if verbose: print("test client", i)
154 testfunc(svrcls.address_family, addr)
155 if verbose: print("waiting for server")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000156 server.shutdown()
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000157 t.join()
Victor Stinner109761b2011-01-03 14:30:39 +0000158 server.server_close()
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000159 if verbose: print("done")
Christian Heimes292d3512008-02-03 16:51:08 +0000160
161 def stream_examine(self, proto, addr):
162 s = socket.socket(proto, socket.SOCK_STREAM)
163 s.connect(addr)
164 s.sendall(TEST_STR)
165 buf = data = receive(s, 100)
Christian Heimesfdb6bb52008-02-03 17:32:13 +0000166 while data and b'\n' not in buf:
Christian Heimes292d3512008-02-03 16:51:08 +0000167 data = receive(s, 100)
168 buf += data
Ezio Melottib3aedd42010-11-20 19:04:17 +0000169 self.assertEqual(buf, TEST_STR)
Christian Heimes292d3512008-02-03 16:51:08 +0000170 s.close()
171
172 def dgram_examine(self, proto, addr):
173 s = socket.socket(proto, socket.SOCK_DGRAM)
174 s.sendto(TEST_STR, addr)
175 buf = data = receive(s, 100)
Christian Heimesfdb6bb52008-02-03 17:32:13 +0000176 while data and b'\n' not in buf:
Christian Heimes292d3512008-02-03 16:51:08 +0000177 data = receive(s, 100)
178 buf += data
Ezio Melottib3aedd42010-11-20 19:04:17 +0000179 self.assertEqual(buf, TEST_STR)
Christian Heimes292d3512008-02-03 16:51:08 +0000180 s.close()
181
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000182 def test_TCPServer(self):
Alexandre Vassalottice261952008-05-12 02:31:37 +0000183 self.run_server(socketserver.TCPServer,
184 socketserver.StreamRequestHandler,
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000185 self.stream_examine)
Christian Heimes292d3512008-02-03 16:51:08 +0000186
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000187 def test_ThreadingTCPServer(self):
Alexandre Vassalottice261952008-05-12 02:31:37 +0000188 self.run_server(socketserver.ThreadingTCPServer,
189 socketserver.StreamRequestHandler,
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000190 self.stream_examine)
Christian Heimes292d3512008-02-03 16:51:08 +0000191
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000192 if HAVE_FORKING:
Christian Heimes70e7ea22008-02-28 20:02:27 +0000193 def test_ForkingTCPServer(self):
194 with simple_subprocess(self):
Alexandre Vassalottice261952008-05-12 02:31:37 +0000195 self.run_server(socketserver.ForkingTCPServer,
196 socketserver.StreamRequestHandler,
Christian Heimes70e7ea22008-02-28 20:02:27 +0000197 self.stream_examine)
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000198
199 if HAVE_UNIX_SOCKETS:
200 def test_UnixStreamServer(self):
Alexandre Vassalottice261952008-05-12 02:31:37 +0000201 self.run_server(socketserver.UnixStreamServer,
202 socketserver.StreamRequestHandler,
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000203 self.stream_examine)
204
205 def test_ThreadingUnixStreamServer(self):
Alexandre Vassalottice261952008-05-12 02:31:37 +0000206 self.run_server(socketserver.ThreadingUnixStreamServer,
207 socketserver.StreamRequestHandler,
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000208 self.stream_examine)
209
Christian Heimes292d3512008-02-03 16:51:08 +0000210 if HAVE_FORKING:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000211 def test_ForkingUnixStreamServer(self):
Christian Heimes70e7ea22008-02-28 20:02:27 +0000212 with simple_subprocess(self):
213 self.run_server(ForkingUnixStreamServer,
Alexandre Vassalottice261952008-05-12 02:31:37 +0000214 socketserver.StreamRequestHandler,
Christian Heimes70e7ea22008-02-28 20:02:27 +0000215 self.stream_examine)
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000216
217 def test_UDPServer(self):
Alexandre Vassalottice261952008-05-12 02:31:37 +0000218 self.run_server(socketserver.UDPServer,
219 socketserver.DatagramRequestHandler,
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000220 self.dgram_examine)
221
222 def test_ThreadingUDPServer(self):
Alexandre Vassalottice261952008-05-12 02:31:37 +0000223 self.run_server(socketserver.ThreadingUDPServer,
224 socketserver.DatagramRequestHandler,
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000225 self.dgram_examine)
226
227 if HAVE_FORKING:
228 def test_ForkingUDPServer(self):
Christian Heimes70e7ea22008-02-28 20:02:27 +0000229 with simple_subprocess(self):
Alexandre Vassalottice261952008-05-12 02:31:37 +0000230 self.run_server(socketserver.ForkingUDPServer,
231 socketserver.DatagramRequestHandler,
Christian Heimes70e7ea22008-02-28 20:02:27 +0000232 self.dgram_examine)
Christian Heimes292d3512008-02-03 16:51:08 +0000233
Antoine Pitroub0a9c662012-04-09 00:47:24 +0200234 @contextlib.contextmanager
235 def mocked_select_module(self):
236 """Mocks the select.select() call to raise EINTR for first call"""
237 old_select = select.select
238
239 class MockSelect:
240 def __init__(self):
241 self.called = 0
242
243 def __call__(self, *args):
244 self.called += 1
245 if self.called == 1:
246 # raise the exception on first call
Antoine Pitrouc0aa9ee2012-04-09 01:37:19 +0200247 raise select.error(errno.EINTR, os.strerror(errno.EINTR))
Antoine Pitroub0a9c662012-04-09 00:47:24 +0200248 else:
249 # Return real select value for consecutive calls
250 return old_select(*args)
251
252 select.select = MockSelect()
253 try:
254 yield select.select
255 finally:
256 select.select = old_select
257
258 def test_InterruptServerSelectCall(self):
259 with self.mocked_select_module() as mock_select:
260 pid = self.run_server(socketserver.TCPServer,
261 socketserver.StreamRequestHandler,
262 self.stream_examine)
263 # Make sure select was called again:
264 self.assertGreater(mock_select.called, 1)
265
Christian Heimes292d3512008-02-03 16:51:08 +0000266 # Alas, on Linux (at least) recvfrom() doesn't return a meaningful
267 # client address so this cannot work:
268
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000269 # if HAVE_UNIX_SOCKETS:
270 # def test_UnixDatagramServer(self):
Alexandre Vassalottice261952008-05-12 02:31:37 +0000271 # self.run_server(socketserver.UnixDatagramServer,
272 # socketserver.DatagramRequestHandler,
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000273 # self.dgram_examine)
274 #
275 # def test_ThreadingUnixDatagramServer(self):
Alexandre Vassalottice261952008-05-12 02:31:37 +0000276 # self.run_server(socketserver.ThreadingUnixDatagramServer,
277 # socketserver.DatagramRequestHandler,
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000278 # self.dgram_examine)
279 #
Christian Heimes292d3512008-02-03 16:51:08 +0000280 # if HAVE_FORKING:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000281 # def test_ForkingUnixDatagramServer(self):
Alexandre Vassalottice261952008-05-12 02:31:37 +0000282 # self.run_server(socketserver.ForkingUnixDatagramServer,
283 # socketserver.DatagramRequestHandler,
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000284 # self.dgram_examine)
Christian Heimes292d3512008-02-03 16:51:08 +0000285
Antoine Pitrou3bcba8e2010-04-25 22:01:43 +0000286 @reap_threads
287 def test_shutdown(self):
288 # Issue #2302: shutdown() should always succeed in making an
289 # other thread leave serve_forever().
290 class MyServer(socketserver.TCPServer):
291 pass
292
293 class MyHandler(socketserver.StreamRequestHandler):
294 pass
295
296 threads = []
297 for i in range(20):
298 s = MyServer((HOST, 0), MyHandler)
299 t = threading.Thread(
300 name='MyServer serving',
301 target=s.serve_forever,
302 kwargs={'poll_interval':0.01})
303 t.daemon = True # In case this function raises.
304 threads.append((t, s))
305 for t, s in threads:
306 t.start()
307 s.shutdown()
308 for t, s in threads:
309 t.join()
Victor Stinner109761b2011-01-03 14:30:39 +0000310 s.server_close()
Antoine Pitrou3bcba8e2010-04-25 22:01:43 +0000311
Guido van Rossum39f1b362001-07-10 11:52:38 +0000312
Tim Petersa9f6f222001-09-17 23:56:20 +0000313def test_main():
Tim Petersa9f6f222001-09-17 23:56:20 +0000314 if imp.lock_held():
Christian Heimes292d3512008-02-03 16:51:08 +0000315 # If the import lock is held, the threads will hang
Benjamin Petersone549ead2009-03-28 21:42:05 +0000316 raise unittest.SkipTest("can't run when import lock is held")
Tim Petersa9f6f222001-09-17 23:56:20 +0000317
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000318 test.support.run_unittest(SocketServerTest)
Guido van Rossum39f1b362001-07-10 11:52:38 +0000319
Tim Petersa9f6f222001-09-17 23:56:20 +0000320if __name__ == "__main__":
321 test_main()