blob: b9b9db69eadc8c62d53909f8987b30317a8fd57e [file] [log] [blame]
Guido van Rossum24e4af82002-06-12 19:18:08 +00001#!/usr/bin/env python
Barry Warsawcf3d4b51997-01-03 20:03:32 +00002
Guido van Rossum24e4af82002-06-12 19:18:08 +00003import unittest
4import test_support
Barry Warsawcf3d4b51997-01-03 20:03:32 +00005
Barry Warsawcf3d4b51997-01-03 20:03:32 +00006import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00007import select
Barry Warsawcf3d4b51997-01-03 20:03:32 +00008import time
Guido van Rossum24e4af82002-06-12 19:18:08 +00009import thread, threading
10import Queue
Barry Warsawcf3d4b51997-01-03 20:03:32 +000011
Guido van Rossum24e4af82002-06-12 19:18:08 +000012PORT = 50007
13HOST = 'localhost'
14MSG = 'Michael Gilfix was here\n'
Barry Warsawcf3d4b51997-01-03 20:03:32 +000015
Guido van Rossum24e4af82002-06-12 19:18:08 +000016class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000017
Guido van Rossum24e4af82002-06-12 19:18:08 +000018 def setUp(self):
19 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
20 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
21 self.serv.bind((HOST, PORT))
22 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000023
Guido van Rossum24e4af82002-06-12 19:18:08 +000024 def tearDown(self):
25 self.serv.close()
26 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000027
Guido van Rossum24e4af82002-06-12 19:18:08 +000028class SocketUDPTest(unittest.TestCase):
29
30 def setUp(self):
31 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
32 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
33 self.serv.bind((HOST, PORT))
34
35 def tearDown(self):
36 self.serv.close()
37 self.serv = None
38
39class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000040 """Threadable Test class
41
42 The ThreadableTest class makes it easy to create a threaded
43 client/server pair from an existing unit test. To create a
44 new threaded class from an existing unit test, use multiple
45 inheritance:
46
47 class NewClass (OldClass, ThreadableTest):
48 pass
49
50 This class defines two new fixture functions with obvious
51 purposes for overriding:
52
53 clientSetUp ()
54 clientTearDown ()
55
56 Any new test functions within the class must then define
57 tests in pairs, where the test name is preceeded with a
58 '_' to indicate the client portion of the test. Ex:
59
60 def testFoo(self):
61 # Server portion
62
63 def _testFoo(self):
64 # Client portion
65
66 Any exceptions raised by the clients during their tests
67 are caught and transferred to the main thread to alert
68 the testing framework.
69
70 Note, the server setup function cannot call any blocking
71 functions that rely on the client thread during setup,
72 unless serverExplicityReady() is called just before
73 the blocking call (such as in setting up a client/server
74 connection and performing the accept() in setUp().
75 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000076
77 def __init__(self):
78 # Swap the true setup function
79 self.__setUp = self.setUp
80 self.__tearDown = self.tearDown
81 self.setUp = self._setUp
82 self.tearDown = self._tearDown
83
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000084 def serverExplicitReady(self):
85 """This method allows the server to explicitly indicate that
86 it wants the client thread to proceed. This is useful if the
87 server is about to execute a blocking routine that is
88 dependent upon the client thread during its setup routine."""
89 self.server_ready.set()
90
Guido van Rossum24e4af82002-06-12 19:18:08 +000091 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000092 self.server_ready = threading.Event()
93 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +000094 self.done = threading.Event()
95 self.queue = Queue.Queue(1)
96
97 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +000098 methodname = self.id()
99 i = methodname.rfind('.')
100 methodname = methodname[i+1:]
101 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000102 self.client_thread = thread.start_new_thread(
103 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000104
105 self.__setUp()
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000106 if not self.server_ready.isSet():
107 self.server_ready.set()
108 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000109
110 def _tearDown(self):
111 self.__tearDown()
112 self.done.wait()
113
114 if not self.queue.empty():
115 msg = self.queue.get()
116 self.fail(msg)
117
118 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000119 self.server_ready.wait()
120 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000121 self.clientSetUp()
122 if not callable(test_func):
123 raise TypeError, "test_func must be a callable function"
124 try:
125 test_func()
126 except Exception, strerror:
127 self.queue.put(strerror)
128 self.clientTearDown()
129
130 def clientSetUp(self):
131 raise NotImplementedError, "clientSetUp must be implemented."
132
133 def clientTearDown(self):
134 self.done.set()
135 thread.exit()
136
137class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
138
139 def __init__(self, methodName='runTest'):
140 SocketTCPTest.__init__(self, methodName=methodName)
141 ThreadableTest.__init__(self)
142
143 def clientSetUp(self):
144 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
145
146 def clientTearDown(self):
147 self.cli.close()
148 self.cli = None
149 ThreadableTest.clientTearDown(self)
150
151class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
152
153 def __init__(self, methodName='runTest'):
154 SocketUDPTest.__init__(self, methodName=methodName)
155 ThreadableTest.__init__(self)
156
157 def clientSetUp(self):
158 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
159
160class SocketConnectedTest(ThreadedTCPSocketTest):
161
162 def __init__(self, methodName='runTest'):
163 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
164
165 def setUp(self):
166 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000167 # Indicate explicitly we're ready for the client thread to
168 # proceed and then perform the blocking call to accept
169 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000170 conn, addr = self.serv.accept()
171 self.cli_conn = conn
172
173 def tearDown(self):
174 self.cli_conn.close()
175 self.cli_conn = None
176 ThreadedTCPSocketTest.tearDown(self)
177
178 def clientSetUp(self):
179 ThreadedTCPSocketTest.clientSetUp(self)
180 self.cli.connect((HOST, PORT))
181 self.serv_conn = self.cli
182
183 def clientTearDown(self):
184 self.serv_conn.close()
185 self.serv_conn = None
186 ThreadedTCPSocketTest.clientTearDown(self)
187
188#######################################################################
189## Begin Tests
190
191class GeneralModuleTests(unittest.TestCase):
192
193 def testSocketError(self):
194 """Testing that socket module exceptions."""
195 def raise_error(*args, **kwargs):
196 raise socket.error
197 def raise_herror(*args, **kwargs):
198 raise socket.herror
199 def raise_gaierror(*args, **kwargs):
200 raise socket.gaierror
201 self.failUnlessRaises(socket.error, raise_error,
202 "Error raising socket exception.")
203 self.failUnlessRaises(socket.error, raise_herror,
204 "Error raising socket exception.")
205 self.failUnlessRaises(socket.error, raise_gaierror,
206 "Error raising socket exception.")
207
208 def testCrucialConstants(self):
209 """Testing for mission critical constants."""
210 socket.AF_INET
211 socket.SOCK_STREAM
212 socket.SOCK_DGRAM
213 socket.SOCK_RAW
214 socket.SOCK_RDM
215 socket.SOCK_SEQPACKET
216 socket.SOL_SOCKET
217 socket.SO_REUSEADDR
218
219 def testNonCrucialConstants(self):
220 """Testing for existance of non-crucial constants."""
221 for const in (
222 "AF_UNIX",
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000223
Guido van Rossum41360a41998-03-26 19:42:58 +0000224 "SO_DEBUG", "SO_ACCEPTCONN", "SO_REUSEADDR", "SO_KEEPALIVE",
225 "SO_DONTROUTE", "SO_BROADCAST", "SO_USELOOPBACK", "SO_LINGER",
226 "SO_OOBINLINE", "SO_REUSEPORT", "SO_SNDBUF", "SO_RCVBUF",
227 "SO_SNDLOWAT", "SO_RCVLOWAT", "SO_SNDTIMEO", "SO_RCVTIMEO",
228 "SO_ERROR", "SO_TYPE", "SOMAXCONN",
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000229
Guido van Rossum41360a41998-03-26 19:42:58 +0000230 "MSG_OOB", "MSG_PEEK", "MSG_DONTROUTE", "MSG_EOR",
231 "MSG_TRUNC", "MSG_CTRUNC", "MSG_WAITALL", "MSG_BTAG",
232 "MSG_ETAG",
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000233
Guido van Rossum41360a41998-03-26 19:42:58 +0000234 "SOL_SOCKET",
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000235
Guido van Rossum41360a41998-03-26 19:42:58 +0000236 "IPPROTO_IP", "IPPROTO_ICMP", "IPPROTO_IGMP",
237 "IPPROTO_GGP", "IPPROTO_TCP", "IPPROTO_EGP",
238 "IPPROTO_PUP", "IPPROTO_UDP", "IPPROTO_IDP",
239 "IPPROTO_HELLO", "IPPROTO_ND", "IPPROTO_TP",
240 "IPPROTO_XTP", "IPPROTO_EON", "IPPROTO_BIP",
241 "IPPROTO_RAW", "IPPROTO_MAX",
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000242
Guido van Rossum41360a41998-03-26 19:42:58 +0000243 "IPPORT_RESERVED", "IPPORT_USERRESERVED",
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000244
Guido van Rossum41360a41998-03-26 19:42:58 +0000245 "INADDR_ANY", "INADDR_BROADCAST", "INADDR_LOOPBACK",
246 "INADDR_UNSPEC_GROUP", "INADDR_ALLHOSTS_GROUP",
247 "INADDR_MAX_LOCAL_GROUP", "INADDR_NONE",
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000248
Guido van Rossum41360a41998-03-26 19:42:58 +0000249 "IP_OPTIONS", "IP_HDRINCL", "IP_TOS", "IP_TTL",
250 "IP_RECVOPTS", "IP_RECVRETOPTS", "IP_RECVDSTADDR",
251 "IP_RETOPTS", "IP_MULTICAST_IF", "IP_MULTICAST_TTL",
252 "IP_MULTICAST_LOOP", "IP_ADD_MEMBERSHIP",
253 "IP_DROP_MEMBERSHIP",
Guido van Rossum24e4af82002-06-12 19:18:08 +0000254 ):
255 try:
256 getattr(socket, const)
257 except AttributeError:
258 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000259
Guido van Rossum654c11e2002-06-13 20:24:17 +0000260 def testHostnameRes(self):
261 """Testing hostname resolution mechanisms."""
262 hostname = socket.gethostname()
263 ip = socket.gethostbyname(hostname)
264 self.assert_(ip.find('.') >= 0, "Error resolving host to ip.")
265 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
266 all_host_names = [hname] + aliases
267 fqhn = socket.getfqdn()
268 if not fqhn in all_host_names:
269 self.fail("Error testing host resolution mechanisms.")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000270
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000271 def testRefCountGetNameInfo(self):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000272 """Testing reference count for getnameinfo."""
273 import sys
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000274 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000275 try:
276 # On some versions, this loses a reference
277 orig = sys.getrefcount(__name__)
278 socket.getnameinfo(__name__,0)
279 except SystemError:
280 if sys.getrefcount(__name__) <> orig:
281 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000282
Guido van Rossum24e4af82002-06-12 19:18:08 +0000283 def testInterpreterCrash(self):
284 """Making sure getnameinfo doesn't crash the interpreter."""
285 try:
286 # On some versions, this crashes the interpreter.
287 socket.getnameinfo(('x', 0, 0, 0), 0)
288 except socket.error:
289 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000290
Guido van Rossum24e4af82002-06-12 19:18:08 +0000291 def testGetServByName(self):
Guido van Rossum1c938012002-06-12 21:17:20 +0000292 """Testing getservbyname()."""
Guido van Rossum24e4af82002-06-12 19:18:08 +0000293 if hasattr(socket, 'getservbyname'):
294 socket.getservbyname('telnet', 'tcp')
295 try:
296 socket.getservbyname('telnet', 'udp')
297 except socket.error:
298 pass
299
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000300 def testDefaultTimeout(self):
301 """Testing default timeout."""
302 # The default timeout should initially be None
303 self.assertEqual(socket.getdefaulttimeout(), None)
304 s = socket.socket()
305 self.assertEqual(s.gettimeout(), None)
306 s.close()
307
308 # Set the default timeout to 10, and see if it propagates
309 socket.setdefaulttimeout(10)
310 self.assertEqual(socket.getdefaulttimeout(), 10)
311 s = socket.socket()
312 self.assertEqual(s.gettimeout(), 10)
313 s.close()
314
315 # Reset the default timeout to None, and see if it propagates
316 socket.setdefaulttimeout(None)
317 self.assertEqual(socket.getdefaulttimeout(), None)
318 s = socket.socket()
319 self.assertEqual(s.gettimeout(), None)
320 s.close()
321
322 # Check that setting it to an invalid value raises ValueError
323 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
324
325 # Check that setting it to an invalid type raises TypeError
326 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
327
328 # XXX The following three don't test module-level functionality...
329
Guido van Rossum24e4af82002-06-12 19:18:08 +0000330 def testSockName(self):
331 """Testing getsockname()."""
332 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum1c938012002-06-12 21:17:20 +0000333 sock.bind(("0.0.0.0", PORT+1))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000334 name = sock.getsockname()
Guido van Rossum1c938012002-06-12 21:17:20 +0000335 self.assertEqual(name, ("0.0.0.0", PORT+1))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000336
337 def testGetSockOpt(self):
338 """Testing getsockopt()."""
339 # We know a socket should start without reuse==0
340 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
341 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000342 self.failIf(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000343
344 def testSetSockOpt(self):
345 """Testing setsockopt()."""
346 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
347 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
348 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000349 self.failIf(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000350
351class BasicTCPTest(SocketConnectedTest):
352
353 def __init__(self, methodName='runTest'):
354 SocketConnectedTest.__init__(self, methodName=methodName)
355
356 def testRecv(self):
357 """Testing large receive over TCP."""
358 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000359 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000360
361 def _testRecv(self):
362 self.serv_conn.send(MSG)
363
364 def testOverFlowRecv(self):
365 """Testing receive in chunks over TCP."""
366 seg1 = self.cli_conn.recv(len(MSG) - 3)
367 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000368 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000369 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000370
371 def _testOverFlowRecv(self):
372 self.serv_conn.send(MSG)
373
374 def testRecvFrom(self):
375 """Testing large recvfrom() over TCP."""
376 msg, addr = self.cli_conn.recvfrom(1024)
377 hostname, port = addr
Guido van Rossum1c938012002-06-12 21:17:20 +0000378 ##self.assertEqual(hostname, socket.gethostbyname('localhost'))
Guido van Rossum76489682002-06-12 20:38:30 +0000379 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000380
381 def _testRecvFrom(self):
382 self.serv_conn.send(MSG)
383
384 def testOverFlowRecvFrom(self):
385 """Testing recvfrom() in chunks over TCP."""
386 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
387 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000388 msg = seg1 + seg2
Guido van Rossum24e4af82002-06-12 19:18:08 +0000389 hostname, port = addr
Guido van Rossum1c938012002-06-12 21:17:20 +0000390 ##self.assertEqual(hostname, socket.gethostbyname('localhost'))
Guido van Rossum76489682002-06-12 20:38:30 +0000391 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000392
393 def _testOverFlowRecvFrom(self):
394 self.serv_conn.send(MSG)
395
396 def testSendAll(self):
397 """Testing sendall() with a 2048 byte string over TCP."""
398 while 1:
399 read = self.cli_conn.recv(1024)
400 if not read:
401 break
402 self.assert_(len(read) == 1024, "Error performing sendall.")
403 read = filter(lambda x: x == 'f', read)
404 self.assert_(len(read) == 1024, "Error performing sendall.")
405
406 def _testSendAll(self):
Guido van Rossumab659962002-06-12 21:29:43 +0000407 big_chunk = 'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000408 self.serv_conn.sendall(big_chunk)
409
410 def testFromFd(self):
411 """Testing fromfd()."""
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000412 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000413 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000414 fd = self.cli_conn.fileno()
415 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
416 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000417 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000418
419 def _testFromFd(self):
420 self.serv_conn.send(MSG)
421
422 def testShutdown(self):
423 """Testing shutdown()."""
424 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000425 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000426
427 def _testShutdown(self):
428 self.serv_conn.send(MSG)
429 self.serv_conn.shutdown(2)
430
431class BasicUDPTest(ThreadedUDPSocketTest):
432
433 def __init__(self, methodName='runTest'):
434 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
435
436 def testSendtoAndRecv(self):
437 """Testing sendto() and Recv() over UDP."""
438 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000439 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000440
441 def _testSendtoAndRecv(self):
442 self.cli.sendto(MSG, 0, (HOST, PORT))
443
Guido van Rossum1c938012002-06-12 21:17:20 +0000444 def testRecvFrom(self):
Guido van Rossumdfad1a92002-06-13 15:03:01 +0000445 """Testing recvfrom() over UDP."""
Guido van Rossum24e4af82002-06-12 19:18:08 +0000446 msg, addr = self.serv.recvfrom(len(MSG))
447 hostname, port = addr
Guido van Rossum1c938012002-06-12 21:17:20 +0000448 ##self.assertEqual(hostname, socket.gethostbyname('localhost'))
Guido van Rossum76489682002-06-12 20:38:30 +0000449 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000450
Guido van Rossum1c938012002-06-12 21:17:20 +0000451 def _testRecvFrom(self):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000452 self.cli.sendto(MSG, 0, (HOST, PORT))
453
454class NonBlockingTCPTests(ThreadedTCPSocketTest):
455
456 def __init__(self, methodName='runTest'):
457 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
458
459 def testSetBlocking(self):
460 """Testing whether set blocking works."""
461 self.serv.setblocking(0)
462 start = time.time()
463 try:
464 self.serv.accept()
465 except socket.error:
466 pass
467 end = time.time()
468 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
469
470 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000471 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000472
Guido van Rossum24e4af82002-06-12 19:18:08 +0000473 def testAccept(self):
474 """Testing non-blocking accept."""
475 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000476 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000477 conn, addr = self.serv.accept()
478 except socket.error:
479 pass
480 else:
481 self.fail("Error trying to do non-blocking accept.")
482 read, write, err = select.select([self.serv], [], [])
483 if self.serv in read:
484 conn, addr = self.serv.accept()
485 else:
486 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000487
Guido van Rossum24e4af82002-06-12 19:18:08 +0000488 def _testAccept(self):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000489 self.cli.connect((HOST, PORT))
490
491 def testConnect(self):
492 """Testing non-blocking connect."""
Guido van Rossum24e4af82002-06-12 19:18:08 +0000493 conn, addr = self.serv.accept()
494
495 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000496 self.cli.settimeout(10)
497 self.cli.connect((HOST, PORT))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000498
499 def testRecv(self):
500 """Testing non-blocking recv."""
501 conn, addr = self.serv.accept()
502 conn.setblocking(0)
503 try:
504 msg = conn.recv(len(MSG))
505 except socket.error:
506 pass
507 else:
508 self.fail("Error trying to do non-blocking recv.")
509 read, write, err = select.select([conn], [], [])
510 if conn in read:
511 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000512 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000513 else:
514 self.fail("Error during select call to non-blocking socket.")
515
516 def _testRecv(self):
517 self.cli.connect((HOST, PORT))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000518 self.cli.send(MSG)
519
520class FileObjectClassTestCase(SocketConnectedTest):
521
522 def __init__(self, methodName='runTest'):
523 SocketConnectedTest.__init__(self, methodName=methodName)
524
525 def setUp(self):
526 SocketConnectedTest.setUp(self)
527 self.serv_file = socket._fileobject(self.cli_conn, 'rb', 8192)
528
529 def tearDown(self):
530 self.serv_file.close()
531 self.serv_file = None
532 SocketConnectedTest.tearDown(self)
533
534 def clientSetUp(self):
535 SocketConnectedTest.clientSetUp(self)
536 self.cli_file = socket._fileobject(self.serv_conn, 'rb', 8192)
537
538 def clientTearDown(self):
539 self.cli_file.close()
540 self.cli_file = None
541 SocketConnectedTest.clientTearDown(self)
542
543 def testSmallRead(self):
544 """Performing small file read test."""
545 first_seg = self.serv_file.read(len(MSG)-3)
546 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000547 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000548 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000549
550 def _testSmallRead(self):
551 self.cli_file.write(MSG)
552 self.cli_file.flush()
553
554 def testUnbufferedRead(self):
555 """Performing unbuffered file read test."""
556 buf = ''
557 while 1:
558 char = self.serv_file.read(1)
Guido van Rossum76489682002-06-12 20:38:30 +0000559 self.failIf(not char)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000560 buf += char
561 if buf == MSG:
562 break
563
564 def _testUnbufferedRead(self):
565 self.cli_file.write(MSG)
566 self.cli_file.flush()
567
568 def testReadline(self):
569 """Performing file readline test."""
570 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000571 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000572
573 def _testReadline(self):
574 self.cli_file.write(MSG)
575 self.cli_file.flush()
576
Guido van Rossum3875e902002-06-20 03:40:16 +0000577def main():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000578 suite = unittest.TestSuite()
579 suite.addTest(unittest.makeSuite(GeneralModuleTests))
580 suite.addTest(unittest.makeSuite(BasicTCPTest))
581 suite.addTest(unittest.makeSuite(BasicUDPTest))
582 suite.addTest(unittest.makeSuite(NonBlockingTCPTests))
583 suite.addTest(unittest.makeSuite(FileObjectClassTestCase))
584 test_support.run_suite(suite)
585
586if __name__ == "__main__":
Guido van Rossum3875e902002-06-20 03:40:16 +0000587 main()