blob: bf2ecae507c245ba131fb3b26ca73e4a6d22388b [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
Barry Warsaw04f357c2002-07-23 19:04:11 +00004from test import 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
Jack Jansen522e7692002-09-06 21:57:50 +000011import sys
Raymond Hettinger027bb632004-05-31 03:09:25 +000012from weakref import proxy
Barry Warsawcf3d4b51997-01-03 20:03:32 +000013
Guido van Rossum24e4af82002-06-12 19:18:08 +000014PORT = 50007
15HOST = 'localhost'
16MSG = 'Michael Gilfix was here\n'
Barry Warsawcf3d4b51997-01-03 20:03:32 +000017
Guido van Rossum24e4af82002-06-12 19:18:08 +000018class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000019
Guido van Rossum24e4af82002-06-12 19:18:08 +000020 def setUp(self):
21 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
22 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
23 self.serv.bind((HOST, PORT))
24 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000025
Guido van Rossum24e4af82002-06-12 19:18:08 +000026 def tearDown(self):
27 self.serv.close()
28 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000029
Guido van Rossum24e4af82002-06-12 19:18:08 +000030class SocketUDPTest(unittest.TestCase):
31
32 def setUp(self):
33 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
34 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
35 self.serv.bind((HOST, PORT))
36
37 def tearDown(self):
38 self.serv.close()
39 self.serv = None
40
41class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000042 """Threadable Test class
43
44 The ThreadableTest class makes it easy to create a threaded
45 client/server pair from an existing unit test. To create a
46 new threaded class from an existing unit test, use multiple
47 inheritance:
48
49 class NewClass (OldClass, ThreadableTest):
50 pass
51
52 This class defines two new fixture functions with obvious
53 purposes for overriding:
54
55 clientSetUp ()
56 clientTearDown ()
57
58 Any new test functions within the class must then define
59 tests in pairs, where the test name is preceeded with a
60 '_' to indicate the client portion of the test. Ex:
61
62 def testFoo(self):
63 # Server portion
64
65 def _testFoo(self):
66 # Client portion
67
68 Any exceptions raised by the clients during their tests
69 are caught and transferred to the main thread to alert
70 the testing framework.
71
72 Note, the server setup function cannot call any blocking
73 functions that rely on the client thread during setup,
74 unless serverExplicityReady() is called just before
75 the blocking call (such as in setting up a client/server
76 connection and performing the accept() in setUp().
77 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000078
79 def __init__(self):
80 # Swap the true setup function
81 self.__setUp = self.setUp
82 self.__tearDown = self.tearDown
83 self.setUp = self._setUp
84 self.tearDown = self._tearDown
85
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000086 def serverExplicitReady(self):
87 """This method allows the server to explicitly indicate that
88 it wants the client thread to proceed. This is useful if the
89 server is about to execute a blocking routine that is
90 dependent upon the client thread during its setup routine."""
91 self.server_ready.set()
92
Guido van Rossum24e4af82002-06-12 19:18:08 +000093 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000094 self.server_ready = threading.Event()
95 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +000096 self.done = threading.Event()
97 self.queue = Queue.Queue(1)
98
99 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000100 methodname = self.id()
101 i = methodname.rfind('.')
102 methodname = methodname[i+1:]
103 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000104 self.client_thread = thread.start_new_thread(
105 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000106
107 self.__setUp()
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000108 if not self.server_ready.isSet():
109 self.server_ready.set()
110 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000111
112 def _tearDown(self):
113 self.__tearDown()
114 self.done.wait()
115
116 if not self.queue.empty():
117 msg = self.queue.get()
118 self.fail(msg)
119
120 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000121 self.server_ready.wait()
122 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000123 self.clientSetUp()
124 if not callable(test_func):
125 raise TypeError, "test_func must be a callable function"
126 try:
127 test_func()
128 except Exception, strerror:
129 self.queue.put(strerror)
130 self.clientTearDown()
131
132 def clientSetUp(self):
133 raise NotImplementedError, "clientSetUp must be implemented."
134
135 def clientTearDown(self):
136 self.done.set()
137 thread.exit()
138
139class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
140
141 def __init__(self, methodName='runTest'):
142 SocketTCPTest.__init__(self, methodName=methodName)
143 ThreadableTest.__init__(self)
144
145 def clientSetUp(self):
146 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
147
148 def clientTearDown(self):
149 self.cli.close()
150 self.cli = None
151 ThreadableTest.clientTearDown(self)
152
153class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
154
155 def __init__(self, methodName='runTest'):
156 SocketUDPTest.__init__(self, methodName=methodName)
157 ThreadableTest.__init__(self)
158
159 def clientSetUp(self):
160 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
161
162class SocketConnectedTest(ThreadedTCPSocketTest):
163
164 def __init__(self, methodName='runTest'):
165 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
166
167 def setUp(self):
168 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000169 # Indicate explicitly we're ready for the client thread to
170 # proceed and then perform the blocking call to accept
171 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000172 conn, addr = self.serv.accept()
173 self.cli_conn = conn
174
175 def tearDown(self):
176 self.cli_conn.close()
177 self.cli_conn = None
178 ThreadedTCPSocketTest.tearDown(self)
179
180 def clientSetUp(self):
181 ThreadedTCPSocketTest.clientSetUp(self)
182 self.cli.connect((HOST, PORT))
183 self.serv_conn = self.cli
184
185 def clientTearDown(self):
186 self.serv_conn.close()
187 self.serv_conn = None
188 ThreadedTCPSocketTest.clientTearDown(self)
189
Dave Cole331708b2004-08-09 04:51:41 +0000190class SocketPairTest(unittest.TestCase, ThreadableTest):
191
192 def __init__(self, methodName='runTest'):
193 unittest.TestCase.__init__(self, methodName=methodName)
194 ThreadableTest.__init__(self)
195
196 def setUp(self):
197 self.serv, self.cli = socket.socketpair()
198
199 def tearDown(self):
200 self.serv.close()
201 self.serv = None
202
203 def clientSetUp(self):
204 pass
205
206 def clientTearDown(self):
207 self.cli.close()
208 self.cli = None
209 ThreadableTest.clientTearDown(self)
210
Tim Peters494aaee2004-08-09 18:54:11 +0000211
Guido van Rossum24e4af82002-06-12 19:18:08 +0000212#######################################################################
213## Begin Tests
214
215class GeneralModuleTests(unittest.TestCase):
216
Raymond Hettinger027bb632004-05-31 03:09:25 +0000217 def test_weakref(self):
218 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
219 p = proxy(s)
220 self.assertEqual(p.fileno(), s.fileno())
221 s.close()
222 s = None
223 try:
224 p.fileno()
225 except ReferenceError:
226 pass
227 else:
228 self.fail('Socket proxy still exists')
229
Guido van Rossum24e4af82002-06-12 19:18:08 +0000230 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000231 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000232 def raise_error(*args, **kwargs):
233 raise socket.error
234 def raise_herror(*args, **kwargs):
235 raise socket.herror
236 def raise_gaierror(*args, **kwargs):
237 raise socket.gaierror
238 self.failUnlessRaises(socket.error, raise_error,
239 "Error raising socket exception.")
240 self.failUnlessRaises(socket.error, raise_herror,
241 "Error raising socket exception.")
242 self.failUnlessRaises(socket.error, raise_gaierror,
243 "Error raising socket exception.")
244
245 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000246 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000247 socket.AF_INET
248 socket.SOCK_STREAM
249 socket.SOCK_DGRAM
250 socket.SOCK_RAW
251 socket.SOCK_RDM
252 socket.SOCK_SEQPACKET
253 socket.SOL_SOCKET
254 socket.SO_REUSEADDR
255
Guido van Rossum654c11e2002-06-13 20:24:17 +0000256 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000257 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000258 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000259 try:
260 ip = socket.gethostbyname(hostname)
261 except socket.error:
262 # Probably name lookup wasn't set up right; skip this test
263 return
Guido van Rossum654c11e2002-06-13 20:24:17 +0000264 self.assert_(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000265 try:
266 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
267 except socket.error:
268 # Probably a similar problem as above; skip this test
269 return
Brett Cannon01668a12005-03-11 00:04:17 +0000270 all_host_names = [hostname, hname] + aliases
Guido van Rossum654c11e2002-06-13 20:24:17 +0000271 fqhn = socket.getfqdn()
272 if not fqhn in all_host_names:
273 self.fail("Error testing host resolution mechanisms.")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000274
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000275 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000276 # Testing reference count for getnameinfo
Guido van Rossum24e4af82002-06-12 19:18:08 +0000277 import sys
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000278 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000279 try:
280 # On some versions, this loses a reference
281 orig = sys.getrefcount(__name__)
282 socket.getnameinfo(__name__,0)
283 except SystemError:
284 if sys.getrefcount(__name__) <> orig:
285 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000286
Guido van Rossum24e4af82002-06-12 19:18:08 +0000287 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000288 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000289 try:
290 # On some versions, this crashes the interpreter.
291 socket.getnameinfo(('x', 0, 0, 0), 0)
292 except socket.error:
293 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000294
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000295 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000296 # This just checks that htons etc. are their own inverse,
297 # when looking at the lower 16 or 32 bits.
298 sizes = {socket.htonl: 32, socket.ntohl: 32,
299 socket.htons: 16, socket.ntohs: 16}
300 for func, size in sizes.items():
301 mask = (1L<<size) - 1
302 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
303 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000304
Guido van Rossuma2627af2002-09-14 00:58:46 +0000305 swapped = func(mask)
306 self.assertEqual(swapped & mask, mask)
307 self.assertRaises(OverflowError, func, 1L<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000308
Barry Warsaw11b91a02004-06-28 00:50:43 +0000309 def testGetServBy(self):
310 eq = self.assertEqual
311 # Find one service that exists, then check all the related interfaces.
312 # I've ordered this by protocols that have both a tcp and udp
313 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000314 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
315 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000316 # avoid the 'echo' service on this platform, as there is an
317 # assumption breaking non-standard port/protocol entry
318 services = ('daytime', 'qotd', 'domain')
319 else:
320 services = ('echo', 'daytime', 'domain')
321 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000322 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000323 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000324 break
325 except socket.error:
326 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000327 else:
328 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000329 # Try same call with optional protocol omitted
330 port2 = socket.getservbyname(service)
331 eq(port, port2)
332 # Try udp, but don't barf it it doesn't exist
333 try:
334 udpport = socket.getservbyname(service, 'udp')
335 except socket.error:
336 udpport = None
337 else:
338 eq(udpport, port)
339 # Now make sure the lookup by port returns the same service name
340 eq(socket.getservbyport(port2), service)
341 eq(socket.getservbyport(port, 'tcp'), service)
342 if udpport is not None:
343 eq(socket.getservbyport(udpport, 'udp'), service)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000344
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000345 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000346 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000347 # The default timeout should initially be None
348 self.assertEqual(socket.getdefaulttimeout(), None)
349 s = socket.socket()
350 self.assertEqual(s.gettimeout(), None)
351 s.close()
352
353 # Set the default timeout to 10, and see if it propagates
354 socket.setdefaulttimeout(10)
355 self.assertEqual(socket.getdefaulttimeout(), 10)
356 s = socket.socket()
357 self.assertEqual(s.gettimeout(), 10)
358 s.close()
359
360 # Reset the default timeout to None, and see if it propagates
361 socket.setdefaulttimeout(None)
362 self.assertEqual(socket.getdefaulttimeout(), None)
363 s = socket.socket()
364 self.assertEqual(s.gettimeout(), None)
365 s.close()
366
367 # Check that setting it to an invalid value raises ValueError
368 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
369
370 # Check that setting it to an invalid type raises TypeError
371 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
372
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000373 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000374 if not hasattr(socket, 'inet_pton'):
375 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000376 from socket import inet_aton as f, inet_pton, AF_INET
377 g = lambda a: inet_pton(AF_INET, a)
378
379 self.assertEquals('\x00\x00\x00\x00', f('0.0.0.0'))
380 self.assertEquals('\xff\x00\xff\x00', f('255.0.255.0'))
381 self.assertEquals('\xaa\xaa\xaa\xaa', f('170.170.170.170'))
382 self.assertEquals('\x01\x02\x03\x04', f('1.2.3.4'))
383
384 self.assertEquals('\x00\x00\x00\x00', g('0.0.0.0'))
385 self.assertEquals('\xff\x00\xff\x00', g('255.0.255.0'))
386 self.assertEquals('\xaa\xaa\xaa\xaa', g('170.170.170.170'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000387
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000388 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000389 if not hasattr(socket, 'inet_pton'):
390 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000391 try:
392 from socket import inet_pton, AF_INET6, has_ipv6
393 if not has_ipv6:
394 return
395 except ImportError:
396 return
397 f = lambda a: inet_pton(AF_INET6, a)
398
399 self.assertEquals('\x00' * 16, f('::'))
400 self.assertEquals('\x00' * 16, f('0::0'))
401 self.assertEquals('\x00\x01' + '\x00' * 14, f('1::'))
402 self.assertEquals(
403 '\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
404 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
405 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000406
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000407 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000408 if not hasattr(socket, 'inet_ntop'):
409 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000410 from socket import inet_ntoa as f, inet_ntop, AF_INET
411 g = lambda a: inet_ntop(AF_INET, a)
412
413 self.assertEquals('1.0.1.0', f('\x01\x00\x01\x00'))
414 self.assertEquals('170.85.170.85', f('\xaa\x55\xaa\x55'))
415 self.assertEquals('255.255.255.255', f('\xff\xff\xff\xff'))
416 self.assertEquals('1.2.3.4', f('\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000417
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000418 self.assertEquals('1.0.1.0', g('\x01\x00\x01\x00'))
419 self.assertEquals('170.85.170.85', g('\xaa\x55\xaa\x55'))
420 self.assertEquals('255.255.255.255', g('\xff\xff\xff\xff'))
421
422 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000423 if not hasattr(socket, 'inet_ntop'):
424 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000425 try:
426 from socket import inet_ntop, AF_INET6, has_ipv6
427 if not has_ipv6:
428 return
429 except ImportError:
430 return
431 f = lambda a: inet_ntop(AF_INET6, a)
432
433 self.assertEquals('::', f('\x00' * 16))
434 self.assertEquals('::1', f('\x00' * 15 + '\x01'))
435 self.assertEquals(
436 'aef:b01:506:1001:ffff:9997:55:170',
437 f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
438 )
439
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000440 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000441
Guido van Rossum24e4af82002-06-12 19:18:08 +0000442 def testSockName(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000443 # Testing getsockname()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000444 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum1c938012002-06-12 21:17:20 +0000445 sock.bind(("0.0.0.0", PORT+1))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000446 name = sock.getsockname()
Guido van Rossum1c938012002-06-12 21:17:20 +0000447 self.assertEqual(name, ("0.0.0.0", PORT+1))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000448
449 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000450 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000451 # We know a socket should start without reuse==0
452 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
453 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000454 self.failIf(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000455
456 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000457 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000458 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
459 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
460 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000461 self.failIf(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000462
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000463 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000464 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000465 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
466 sock.settimeout(1)
467 sock.close()
468 self.assertRaises(socket.error, sock.send, "spam")
469
Guido van Rossum24e4af82002-06-12 19:18:08 +0000470class BasicTCPTest(SocketConnectedTest):
471
472 def __init__(self, methodName='runTest'):
473 SocketConnectedTest.__init__(self, methodName=methodName)
474
475 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000476 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000477 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000478 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000479
480 def _testRecv(self):
481 self.serv_conn.send(MSG)
482
483 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000484 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000485 seg1 = self.cli_conn.recv(len(MSG) - 3)
486 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000487 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000488 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000489
490 def _testOverFlowRecv(self):
491 self.serv_conn.send(MSG)
492
493 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000494 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000495 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000496 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000497
498 def _testRecvFrom(self):
499 self.serv_conn.send(MSG)
500
501 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000502 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000503 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
504 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000505 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000506 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000507
508 def _testOverFlowRecvFrom(self):
509 self.serv_conn.send(MSG)
510
511 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000512 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossume531e292002-08-08 20:28:34 +0000513 msg = ''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000514 while 1:
515 read = self.cli_conn.recv(1024)
516 if not read:
517 break
Guido van Rossume531e292002-08-08 20:28:34 +0000518 msg += read
519 self.assertEqual(msg, 'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000520
521 def _testSendAll(self):
Guido van Rossumab659962002-06-12 21:29:43 +0000522 big_chunk = 'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000523 self.serv_conn.sendall(big_chunk)
524
525 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000526 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000527 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000528 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000529 fd = self.cli_conn.fileno()
530 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
531 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000532 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000533
534 def _testFromFd(self):
535 self.serv_conn.send(MSG)
536
537 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000538 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000539 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000540 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000541
542 def _testShutdown(self):
543 self.serv_conn.send(MSG)
544 self.serv_conn.shutdown(2)
545
546class BasicUDPTest(ThreadedUDPSocketTest):
547
548 def __init__(self, methodName='runTest'):
549 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
550
551 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000552 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000553 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000554 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000555
556 def _testSendtoAndRecv(self):
557 self.cli.sendto(MSG, 0, (HOST, PORT))
558
Guido van Rossum1c938012002-06-12 21:17:20 +0000559 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000560 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000561 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000562 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000563
Guido van Rossum1c938012002-06-12 21:17:20 +0000564 def _testRecvFrom(self):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000565 self.cli.sendto(MSG, 0, (HOST, PORT))
566
Dave Cole331708b2004-08-09 04:51:41 +0000567class BasicSocketPairTest(SocketPairTest):
568
569 def __init__(self, methodName='runTest'):
570 SocketPairTest.__init__(self, methodName=methodName)
571
572 def testRecv(self):
573 msg = self.serv.recv(1024)
574 self.assertEqual(msg, MSG)
575
576 def _testRecv(self):
577 self.cli.send(MSG)
578
579 def testSend(self):
580 self.serv.send(MSG)
581
582 def _testSend(self):
583 msg = self.cli.recv(1024)
584 self.assertEqual(msg, MSG)
585
Guido van Rossum24e4af82002-06-12 19:18:08 +0000586class NonBlockingTCPTests(ThreadedTCPSocketTest):
587
588 def __init__(self, methodName='runTest'):
589 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
590
591 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000592 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000593 self.serv.setblocking(0)
594 start = time.time()
595 try:
596 self.serv.accept()
597 except socket.error:
598 pass
599 end = time.time()
600 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
601
602 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000603 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000604
Guido van Rossum24e4af82002-06-12 19:18:08 +0000605 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000606 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000607 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000608 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000609 conn, addr = self.serv.accept()
610 except socket.error:
611 pass
612 else:
613 self.fail("Error trying to do non-blocking accept.")
614 read, write, err = select.select([self.serv], [], [])
615 if self.serv in read:
616 conn, addr = self.serv.accept()
617 else:
618 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000619
Guido van Rossum24e4af82002-06-12 19:18:08 +0000620 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000621 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000622 self.cli.connect((HOST, PORT))
623
624 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000625 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000626 conn, addr = self.serv.accept()
627
628 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000629 self.cli.settimeout(10)
630 self.cli.connect((HOST, PORT))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000631
632 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000633 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000634 conn, addr = self.serv.accept()
635 conn.setblocking(0)
636 try:
637 msg = conn.recv(len(MSG))
638 except socket.error:
639 pass
640 else:
641 self.fail("Error trying to do non-blocking recv.")
642 read, write, err = select.select([conn], [], [])
643 if conn in read:
644 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000645 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000646 else:
647 self.fail("Error during select call to non-blocking socket.")
648
649 def _testRecv(self):
650 self.cli.connect((HOST, PORT))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000651 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000652 self.cli.send(MSG)
653
654class FileObjectClassTestCase(SocketConnectedTest):
655
Guido van Rossume9f66142002-08-07 15:46:19 +0000656 bufsize = -1 # Use default buffer size
657
Guido van Rossum24e4af82002-06-12 19:18:08 +0000658 def __init__(self, methodName='runTest'):
659 SocketConnectedTest.__init__(self, methodName=methodName)
660
661 def setUp(self):
662 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000663 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000664
665 def tearDown(self):
666 self.serv_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000667 self.assert_(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000668 self.serv_file = None
669 SocketConnectedTest.tearDown(self)
670
671 def clientSetUp(self):
672 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000673 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000674
675 def clientTearDown(self):
676 self.cli_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000677 self.assert_(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000678 self.cli_file = None
679 SocketConnectedTest.clientTearDown(self)
680
681 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000682 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000683 first_seg = self.serv_file.read(len(MSG)-3)
684 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000685 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000686 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000687
688 def _testSmallRead(self):
689 self.cli_file.write(MSG)
690 self.cli_file.flush()
691
Guido van Rossum8c943832002-08-08 01:00:28 +0000692 def testFullRead(self):
693 # read until EOF
694 msg = self.serv_file.read()
695 self.assertEqual(msg, MSG)
696
697 def _testFullRead(self):
698 self.cli_file.write(MSG)
699 self.cli_file.close()
700
Guido van Rossum24e4af82002-06-12 19:18:08 +0000701 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000702 # Performing unbuffered file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000703 buf = ''
704 while 1:
705 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000706 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000707 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000708 buf += char
709 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000710
711 def _testUnbufferedRead(self):
712 self.cli_file.write(MSG)
713 self.cli_file.flush()
714
715 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000716 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000717 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000718 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000719
720 def _testReadline(self):
721 self.cli_file.write(MSG)
722 self.cli_file.flush()
723
Tim Peters116d83c2004-03-28 02:20:45 +0000724 def testClosedAttr(self):
725 self.assert_(not self.serv_file.closed)
726
727 def _testClosedAttr(self):
728 self.assert_(not self.cli_file.closed)
729
Guido van Rossume9f66142002-08-07 15:46:19 +0000730class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
731
732 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000733
Guido van Rossume9f66142002-08-07 15:46:19 +0000734 In this case (and in this case only), it should be possible to
735 create a file object, read a line from it, create another file
736 object, read another line from it, without loss of data in the
737 first file object's buffer. Note that httplib relies on this
738 when reading multiple requests from the same socket."""
739
740 bufsize = 0 # Use unbuffered mode
741
742 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000743 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000744 line = self.serv_file.readline() # first line
Guido van Rossum10e3f412002-08-07 19:02:49 +0000745 self.assertEqual(line, "A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000746 self.serv_file = self.cli_conn.makefile('rb', 0)
747 line = self.serv_file.readline() # second line
Guido van Rossum10e3f412002-08-07 19:02:49 +0000748 self.assertEqual(line, "B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000749
750 def _testUnbufferedReadline(self):
Guido van Rossum10e3f412002-08-07 19:02:49 +0000751 self.cli_file.write("A. " + MSG)
752 self.cli_file.write("B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000753 self.cli_file.flush()
754
Guido van Rossum8c943832002-08-08 01:00:28 +0000755class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
756
757 bufsize = 1 # Default-buffered for reading; line-buffered for writing
758
759
760class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
761
762 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000763
Raymond Hettinger11a35f52003-06-29 04:40:22 +0000764class TCPTimeoutTest(SocketTCPTest):
765
766 def testTCPTimeout(self):
767 def raise_timeout(*args, **kwargs):
768 self.serv.settimeout(1.0)
769 self.serv.accept()
770 self.failUnlessRaises(socket.timeout, raise_timeout,
771 "Error generating a timeout exception (TCP)")
772
773 def testTimeoutZero(self):
774 ok = False
775 try:
776 self.serv.settimeout(0.0)
777 foo = self.serv.accept()
778 except socket.timeout:
779 self.fail("caught timeout instead of error (TCP)")
780 except socket.error:
781 ok = True
782 except:
783 self.fail("caught unexpected exception (TCP)")
784 if not ok:
785 self.fail("accept() returned success when we did not expect it")
786
787class UDPTimeoutTest(SocketTCPTest):
788
789 def testUDPTimeout(self):
790 def raise_timeout(*args, **kwargs):
791 self.serv.settimeout(1.0)
792 self.serv.recv(1024)
793 self.failUnlessRaises(socket.timeout, raise_timeout,
794 "Error generating a timeout exception (UDP)")
795
796 def testTimeoutZero(self):
797 ok = False
798 try:
799 self.serv.settimeout(0.0)
800 foo = self.serv.recv(1024)
801 except socket.timeout:
802 self.fail("caught timeout instead of error (UDP)")
803 except socket.error:
804 ok = True
805 except:
806 self.fail("caught unexpected exception (UDP)")
807 if not ok:
808 self.fail("recv() returned success when we did not expect it")
809
810class TestExceptions(unittest.TestCase):
811
812 def testExceptionTree(self):
813 self.assert_(issubclass(socket.error, Exception))
814 self.assert_(issubclass(socket.herror, socket.error))
815 self.assert_(issubclass(socket.gaierror, socket.error))
816 self.assert_(issubclass(socket.timeout, socket.error))
817
818
Guido van Rossumb995eb72002-07-31 16:08:40 +0000819def test_main():
Raymond Hettinger11a35f52003-06-29 04:40:22 +0000820 tests = [GeneralModuleTests, BasicTCPTest, TCPTimeoutTest, TestExceptions]
Jack Jansen522e7692002-09-06 21:57:50 +0000821 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +0000822 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +0000823
824 tests.extend([
825 NonBlockingTCPTests,
826 FileObjectClassTestCase,
827 UnbufferedFileObjectClassTestCase,
828 LineBufferedFileObjectClassTestCase,
829 SmallBufferedFileObjectClassTestCase
830 ])
Dave Cole331708b2004-08-09 04:51:41 +0000831 if hasattr(socket, "socketpair"):
832 tests.append(BasicSocketPairTest)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000833 test_support.run_unittest(*tests)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000834
835if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +0000836 test_main()