blob: 202f2da2e745fef2dabfcf8d277bf83ccf7a5a5f [file] [log] [blame]
Guido van Rossum39f1b362001-07-10 11:52:38 +00001# Test suite for SocketServer.py
2
Barry Warsaw04f357c2002-07-23 19:04:11 +00003from test import test_support
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004from test.test_support import (verbose, verify, TESTFN, TestSkipped,
5 reap_children)
Tim Petersa86f0c12001-09-18 02:18:57 +00006test_support.requires('network')
Guido van Rossum39f1b362001-07-10 11:52:38 +00007
8from SocketServer import *
9import socket
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010import errno
Guido van Rossum39f1b362001-07-10 11:52:38 +000011import select
12import time
13import threading
14import os
15
16NREQ = 3
17DELAY = 0.5
18
19class MyMixinHandler:
20 def handle(self):
21 time.sleep(DELAY)
22 line = self.rfile.readline()
23 time.sleep(DELAY)
24 self.wfile.write(line)
25
26class MyStreamHandler(MyMixinHandler, StreamRequestHandler):
27 pass
28
29class MyDatagramHandler(MyMixinHandler, DatagramRequestHandler):
30 pass
31
32class MyMixinServer:
33 def serve_a_few(self):
34 for i in range(NREQ):
35 self.handle_request()
36 def handle_error(self, request, client_address):
37 self.close_request(request)
38 self.server_close()
39 raise
40
41teststring = "hello world\n"
42
43def receive(sock, n, timeout=20):
44 r, w, x = select.select([sock], [], [], timeout)
45 if sock in r:
46 return sock.recv(n)
47 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +000048 raise RuntimeError, "timed out on %r" % (sock,)
Guido van Rossum39f1b362001-07-10 11:52:38 +000049
50def testdgram(proto, addr):
51 s = socket.socket(proto, socket.SOCK_DGRAM)
52 s.sendto(teststring, addr)
53 buf = data = receive(s, 100)
54 while data and '\n' not in buf:
55 data = receive(s, 100)
56 buf += data
57 verify(buf == teststring)
58 s.close()
59
60def teststream(proto, addr):
61 s = socket.socket(proto, socket.SOCK_STREAM)
62 s.connect(addr)
Guido van Rossum9bd14012001-10-29 07:18:02 +000063 s.sendall(teststring)
Guido van Rossum39f1b362001-07-10 11:52:38 +000064 buf = data = receive(s, 100)
65 while data and '\n' not in buf:
66 data = receive(s, 100)
67 buf += data
68 verify(buf == teststring)
69 s.close()
70
71class ServerThread(threading.Thread):
72 def __init__(self, addr, svrcls, hdlrcls):
73 threading.Thread.__init__(self)
74 self.__addr = addr
75 self.__svrcls = svrcls
76 self.__hdlrcls = hdlrcls
77 def run(self):
78 class svrcls(MyMixinServer, self.__svrcls):
79 pass
80 if verbose: print "thread: creating server"
81 svr = svrcls(self.__addr, self.__hdlrcls)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000082 # pull the address out of the server in case it changed
83 # this can happen if another process is using the port
84 addr = getattr(svr, 'server_address')
85 if addr:
86 self.__addr = addr
Guido van Rossum39f1b362001-07-10 11:52:38 +000087 if verbose: print "thread: serving three times"
88 svr.serve_a_few()
89 if verbose: print "thread: done"
90
91seed = 0
92def pickport():
93 global seed
94 seed += 1
95 return 10000 + (os.getpid() % 1000)*10 + seed
96
Guido van Rossum05be1a02001-07-10 15:46:34 +000097host = "localhost"
Guido van Rossum39f1b362001-07-10 11:52:38 +000098testfiles = []
99def pickaddr(proto):
100 if proto == socket.AF_INET:
101 return (host, pickport())
102 else:
103 fn = TESTFN + str(pickport())
Andrew MacIntyredaedf212004-04-11 12:03:57 +0000104 if os.name == 'os2':
105 # AF_UNIX socket names on OS/2 require a specific prefix
106 # which can't include a drive letter and must also use
107 # backslashes as directory separators
108 if fn[1] == ':':
109 fn = fn[2:]
110 if fn[0] in (os.sep, os.altsep):
111 fn = fn[1:]
112 fn = os.path.join('\socket', fn)
113 if os.sep == '/':
114 fn = fn.replace(os.sep, os.altsep)
115 else:
116 fn = fn.replace(os.altsep, os.sep)
Guido van Rossum39f1b362001-07-10 11:52:38 +0000117 testfiles.append(fn)
118 return fn
119
120def cleanup():
121 for fn in testfiles:
122 try:
123 os.remove(fn)
124 except os.error:
125 pass
126 testfiles[:] = []
127
128def testloop(proto, servers, hdlrcls, testfunc):
129 for svrcls in servers:
130 addr = pickaddr(proto)
131 if verbose:
132 print "ADDR =", addr
133 print "CLASS =", svrcls
134 t = ServerThread(addr, svrcls, hdlrcls)
135 if verbose: print "server created"
136 t.start()
137 if verbose: print "server running"
138 for i in range(NREQ):
139 time.sleep(DELAY)
140 if verbose: print "test client", i
141 testfunc(proto, addr)
142 if verbose: print "waiting for server"
143 t.join()
144 if verbose: print "done"
145
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146class ForgivingTCPServer(TCPServer):
147 # prevent errors if another process is using the port we want
148 def server_bind(self):
149 host, default_port = self.server_address
150 # this code shamelessly stolen from test.test_support
151 # the ports were changed to protect the innocent
152 import sys
153 for port in [default_port, 3434, 8798, 23833]:
154 try:
155 self.server_address = host, port
156 TCPServer.server_bind(self)
157 break
Guido van Rossumb940e112007-01-10 16:19:56 +0000158 except socket.error as e:
159 (err, msg) = e
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000160 if err != errno.EADDRINUSE:
161 raise
162 print >>sys.__stderr__, \
163 ' WARNING: failed to listen on port %d, trying another' % port
164
165tcpservers = [ForgivingTCPServer, ThreadingTCPServer]
Andrew MacIntyrec6fff892003-01-02 12:49:00 +0000166if hasattr(os, 'fork') and os.name not in ('os2',):
Guido van Rossum39f1b362001-07-10 11:52:38 +0000167 tcpservers.append(ForkingTCPServer)
168udpservers = [UDPServer, ThreadingUDPServer]
Andrew MacIntyrec6fff892003-01-02 12:49:00 +0000169if hasattr(os, 'fork') and os.name not in ('os2',):
Guido van Rossum39f1b362001-07-10 11:52:38 +0000170 udpservers.append(ForkingUDPServer)
171
172if not hasattr(socket, 'AF_UNIX'):
173 streamservers = []
174 dgramservers = []
175else:
176 class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): pass
Andrew MacIntyredaedf212004-04-11 12:03:57 +0000177 streamservers = [UnixStreamServer, ThreadingUnixStreamServer]
178 if hasattr(os, 'fork') and os.name not in ('os2',):
179 streamservers.append(ForkingUnixStreamServer)
Guido van Rossum39f1b362001-07-10 11:52:38 +0000180 class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): pass
Andrew MacIntyredaedf212004-04-11 12:03:57 +0000181 dgramservers = [UnixDatagramServer, ThreadingUnixDatagramServer]
182 if hasattr(os, 'fork') and os.name not in ('os2',):
183 dgramservers.append(ForkingUnixDatagramServer)
Guido van Rossum39f1b362001-07-10 11:52:38 +0000184
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000185def sloppy_cleanup():
186 # See http://python.org/sf/1540386
187 # We need to reap children here otherwise a child from one server
188 # can be left running for the next server and cause a test failure.
189 time.sleep(DELAY)
190 reap_children()
191
Guido van Rossum39f1b362001-07-10 11:52:38 +0000192def testall():
193 testloop(socket.AF_INET, tcpservers, MyStreamHandler, teststream)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000194 sloppy_cleanup()
Guido van Rossum39f1b362001-07-10 11:52:38 +0000195 testloop(socket.AF_INET, udpservers, MyDatagramHandler, testdgram)
Guido van Rossum05be1a02001-07-10 15:46:34 +0000196 if hasattr(socket, 'AF_UNIX'):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000197 sloppy_cleanup()
Guido van Rossum05be1a02001-07-10 15:46:34 +0000198 testloop(socket.AF_UNIX, streamservers, MyStreamHandler, teststream)
199 # Alas, on Linux (at least) recvfrom() doesn't return a meaningful
200 # client address so this cannot work:
201 ##testloop(socket.AF_UNIX, dgramservers, MyDatagramHandler, testdgram)
Guido van Rossum39f1b362001-07-10 11:52:38 +0000202
Tim Petersa9f6f222001-09-17 23:56:20 +0000203def test_main():
204 import imp
205 if imp.lock_held():
206 # If the import lock is held, the threads will hang.
207 raise TestSkipped("can't run when import lock is held")
208
Guido van Rossum39f1b362001-07-10 11:52:38 +0000209 try:
210 testall()
211 finally:
212 cleanup()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000213 reap_children()
Guido van Rossum39f1b362001-07-10 11:52:38 +0000214
Tim Petersa9f6f222001-09-17 23:56:20 +0000215if __name__ == "__main__":
216 test_main()