blob: 48c9346e0c158c19cccc269688eb8267afbf4062 [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
Trent Nelsone41b0062008-04-08 23:47:30 +00006import errno
Barry Warsawcf3d4b51997-01-03 20:03:32 +00007import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00008import select
Guido van Rossum24e4af82002-06-12 19:18:08 +00009import thread, threading
Jeffrey Yasskin36550bd2008-03-28 04:53:10 +000010import time
11import traceback
Guido van Rossum24e4af82002-06-12 19:18:08 +000012import Queue
Jack Jansen522e7692002-09-06 21:57:50 +000013import sys
Christian Heimesa47b75b2008-01-04 15:48:06 +000014import os
Martin Blais2856e5f2006-05-26 12:03:27 +000015import array
Raymond Hettinger027bb632004-05-31 03:09:25 +000016from weakref import proxy
Neal Norwitz9b0ca792006-08-02 06:46:21 +000017import signal
Barry Warsawcf3d4b51997-01-03 20:03:32 +000018
Trent Nelsone41b0062008-04-08 23:47:30 +000019HOST = test_support.HOST
Guido van Rossum24e4af82002-06-12 19:18:08 +000020MSG = 'Michael Gilfix was here\n'
Barry Warsawcf3d4b51997-01-03 20:03:32 +000021
Guido van Rossum24e4af82002-06-12 19:18:08 +000022class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000023
Guido van Rossum24e4af82002-06-12 19:18:08 +000024 def setUp(self):
25 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Trent Nelsone41b0062008-04-08 23:47:30 +000026 self.port = test_support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000027 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000028
Guido van Rossum24e4af82002-06-12 19:18:08 +000029 def tearDown(self):
30 self.serv.close()
31 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000032
Guido van Rossum24e4af82002-06-12 19:18:08 +000033class SocketUDPTest(unittest.TestCase):
34
35 def setUp(self):
36 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Trent Nelsone41b0062008-04-08 23:47:30 +000037 self.port = test_support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000038
39 def tearDown(self):
40 self.serv.close()
41 self.serv = None
42
43class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000044 """Threadable Test class
45
46 The ThreadableTest class makes it easy to create a threaded
47 client/server pair from an existing unit test. To create a
48 new threaded class from an existing unit test, use multiple
49 inheritance:
50
51 class NewClass (OldClass, ThreadableTest):
52 pass
53
54 This class defines two new fixture functions with obvious
55 purposes for overriding:
56
57 clientSetUp ()
58 clientTearDown ()
59
60 Any new test functions within the class must then define
61 tests in pairs, where the test name is preceeded with a
62 '_' to indicate the client portion of the test. Ex:
63
64 def testFoo(self):
65 # Server portion
66
67 def _testFoo(self):
68 # Client portion
69
70 Any exceptions raised by the clients during their tests
71 are caught and transferred to the main thread to alert
72 the testing framework.
73
74 Note, the server setup function cannot call any blocking
75 functions that rely on the client thread during setup,
Facundo Batista07c78be2007-03-23 18:54:07 +000076 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000077 the blocking call (such as in setting up a client/server
78 connection and performing the accept() in setUp().
79 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000080
81 def __init__(self):
82 # Swap the true setup function
83 self.__setUp = self.setUp
84 self.__tearDown = self.tearDown
85 self.setUp = self._setUp
86 self.tearDown = self._tearDown
87
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000088 def serverExplicitReady(self):
89 """This method allows the server to explicitly indicate that
90 it wants the client thread to proceed. This is useful if the
91 server is about to execute a blocking routine that is
92 dependent upon the client thread during its setup routine."""
93 self.server_ready.set()
94
Guido van Rossum24e4af82002-06-12 19:18:08 +000095 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000096 self.server_ready = threading.Event()
97 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +000098 self.done = threading.Event()
99 self.queue = Queue.Queue(1)
100
101 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000102 methodname = self.id()
103 i = methodname.rfind('.')
104 methodname = methodname[i+1:]
105 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000106 self.client_thread = thread.start_new_thread(
107 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000108
109 self.__setUp()
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000110 if not self.server_ready.isSet():
111 self.server_ready.set()
112 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000113
114 def _tearDown(self):
115 self.__tearDown()
116 self.done.wait()
117
118 if not self.queue.empty():
119 msg = self.queue.get()
120 self.fail(msg)
121
122 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000123 self.server_ready.wait()
124 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000125 self.clientSetUp()
126 if not callable(test_func):
127 raise TypeError, "test_func must be a callable function"
128 try:
129 test_func()
130 except Exception, strerror:
131 self.queue.put(strerror)
132 self.clientTearDown()
133
134 def clientSetUp(self):
135 raise NotImplementedError, "clientSetUp must be implemented."
136
137 def clientTearDown(self):
138 self.done.set()
139 thread.exit()
140
141class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
142
143 def __init__(self, methodName='runTest'):
144 SocketTCPTest.__init__(self, methodName=methodName)
145 ThreadableTest.__init__(self)
146
147 def clientSetUp(self):
148 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
149
150 def clientTearDown(self):
151 self.cli.close()
152 self.cli = None
153 ThreadableTest.clientTearDown(self)
154
155class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
156
157 def __init__(self, methodName='runTest'):
158 SocketUDPTest.__init__(self, methodName=methodName)
159 ThreadableTest.__init__(self)
160
161 def clientSetUp(self):
162 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
163
164class SocketConnectedTest(ThreadedTCPSocketTest):
165
166 def __init__(self, methodName='runTest'):
167 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
168
169 def setUp(self):
170 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000171 # Indicate explicitly we're ready for the client thread to
172 # proceed and then perform the blocking call to accept
173 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000174 conn, addr = self.serv.accept()
175 self.cli_conn = conn
176
177 def tearDown(self):
178 self.cli_conn.close()
179 self.cli_conn = None
180 ThreadedTCPSocketTest.tearDown(self)
181
182 def clientSetUp(self):
183 ThreadedTCPSocketTest.clientSetUp(self)
Trent Nelsone41b0062008-04-08 23:47:30 +0000184 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000185 self.serv_conn = self.cli
186
187 def clientTearDown(self):
188 self.serv_conn.close()
189 self.serv_conn = None
190 ThreadedTCPSocketTest.clientTearDown(self)
191
Dave Cole331708b2004-08-09 04:51:41 +0000192class SocketPairTest(unittest.TestCase, ThreadableTest):
193
194 def __init__(self, methodName='runTest'):
195 unittest.TestCase.__init__(self, methodName=methodName)
196 ThreadableTest.__init__(self)
197
198 def setUp(self):
199 self.serv, self.cli = socket.socketpair()
200
201 def tearDown(self):
202 self.serv.close()
203 self.serv = None
204
205 def clientSetUp(self):
206 pass
207
208 def clientTearDown(self):
209 self.cli.close()
210 self.cli = None
211 ThreadableTest.clientTearDown(self)
212
Tim Peters494aaee2004-08-09 18:54:11 +0000213
Guido van Rossum24e4af82002-06-12 19:18:08 +0000214#######################################################################
215## Begin Tests
216
217class GeneralModuleTests(unittest.TestCase):
218
Raymond Hettinger027bb632004-05-31 03:09:25 +0000219 def test_weakref(self):
220 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
221 p = proxy(s)
222 self.assertEqual(p.fileno(), s.fileno())
223 s.close()
224 s = None
225 try:
226 p.fileno()
227 except ReferenceError:
228 pass
229 else:
230 self.fail('Socket proxy still exists')
231
Guido van Rossum24e4af82002-06-12 19:18:08 +0000232 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000233 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000234 def raise_error(*args, **kwargs):
235 raise socket.error
236 def raise_herror(*args, **kwargs):
237 raise socket.herror
238 def raise_gaierror(*args, **kwargs):
239 raise socket.gaierror
240 self.failUnlessRaises(socket.error, raise_error,
241 "Error raising socket exception.")
242 self.failUnlessRaises(socket.error, raise_herror,
243 "Error raising socket exception.")
244 self.failUnlessRaises(socket.error, raise_gaierror,
245 "Error raising socket exception.")
246
247 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000248 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000249 socket.AF_INET
250 socket.SOCK_STREAM
251 socket.SOCK_DGRAM
252 socket.SOCK_RAW
253 socket.SOCK_RDM
254 socket.SOCK_SEQPACKET
255 socket.SOL_SOCKET
256 socket.SO_REUSEADDR
257
Guido van Rossum654c11e2002-06-13 20:24:17 +0000258 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000259 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000260 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000261 try:
262 ip = socket.gethostbyname(hostname)
263 except socket.error:
264 # Probably name lookup wasn't set up right; skip this test
265 return
Guido van Rossum654c11e2002-06-13 20:24:17 +0000266 self.assert_(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000267 try:
268 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
269 except socket.error:
270 # Probably a similar problem as above; skip this test
271 return
Brett Cannon01668a12005-03-11 00:04:17 +0000272 all_host_names = [hostname, hname] + aliases
Anthony Baxtercf0a2a82006-04-03 08:10:33 +0000273 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000274 if not fqhn in all_host_names:
Martin v. Löwis04855cc2006-03-26 16:40:47 +0000275 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000276
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000277 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000278 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000279 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000280 try:
281 # On some versions, this loses a reference
282 orig = sys.getrefcount(__name__)
283 socket.getnameinfo(__name__,0)
284 except SystemError:
285 if sys.getrefcount(__name__) <> orig:
286 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000287
Guido van Rossum24e4af82002-06-12 19:18:08 +0000288 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000289 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000290 try:
291 # On some versions, this crashes the interpreter.
292 socket.getnameinfo(('x', 0, 0, 0), 0)
293 except socket.error:
294 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000295
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000296 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000297 # This just checks that htons etc. are their own inverse,
298 # when looking at the lower 16 or 32 bits.
299 sizes = {socket.htonl: 32, socket.ntohl: 32,
300 socket.htons: 16, socket.ntohs: 16}
301 for func, size in sizes.items():
302 mask = (1L<<size) - 1
303 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
304 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000305
Guido van Rossuma2627af2002-09-14 00:58:46 +0000306 swapped = func(mask)
307 self.assertEqual(swapped & mask, mask)
308 self.assertRaises(OverflowError, func, 1L<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000309
Guido van Rossumbb2cc692007-01-14 17:03:32 +0000310 def testNtoHErrors(self):
311 good_values = [ 1, 2, 3, 1L, 2L, 3L ]
312 bad_values = [ -1, -2, -3, -1L, -2L, -3L ]
313 for k in good_values:
314 socket.ntohl(k)
315 socket.ntohs(k)
316 socket.htonl(k)
317 socket.htons(k)
318 for k in bad_values:
319 self.assertRaises(OverflowError, socket.ntohl, k)
320 self.assertRaises(OverflowError, socket.ntohs, k)
321 self.assertRaises(OverflowError, socket.htonl, k)
322 self.assertRaises(OverflowError, socket.htons, k)
323
Barry Warsaw11b91a02004-06-28 00:50:43 +0000324 def testGetServBy(self):
325 eq = self.assertEqual
326 # Find one service that exists, then check all the related interfaces.
327 # I've ordered this by protocols that have both a tcp and udp
328 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000329 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Hye-Shik Changea684742007-10-28 12:38:09 +0000330 'freebsd7', 'freebsd8', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000331 # avoid the 'echo' service on this platform, as there is an
332 # assumption breaking non-standard port/protocol entry
333 services = ('daytime', 'qotd', 'domain')
334 else:
335 services = ('echo', 'daytime', 'domain')
336 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000337 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000338 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000339 break
340 except socket.error:
341 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000342 else:
343 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000344 # Try same call with optional protocol omitted
345 port2 = socket.getservbyname(service)
346 eq(port, port2)
347 # Try udp, but don't barf it it doesn't exist
348 try:
349 udpport = socket.getservbyname(service, 'udp')
350 except socket.error:
351 udpport = None
352 else:
353 eq(udpport, port)
354 # Now make sure the lookup by port returns the same service name
355 eq(socket.getservbyport(port2), service)
356 eq(socket.getservbyport(port, 'tcp'), service)
357 if udpport is not None:
358 eq(socket.getservbyport(udpport, 'udp'), service)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000359
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000360 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000361 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000362 # The default timeout should initially be None
363 self.assertEqual(socket.getdefaulttimeout(), None)
364 s = socket.socket()
365 self.assertEqual(s.gettimeout(), None)
366 s.close()
367
368 # Set the default timeout to 10, and see if it propagates
369 socket.setdefaulttimeout(10)
370 self.assertEqual(socket.getdefaulttimeout(), 10)
371 s = socket.socket()
372 self.assertEqual(s.gettimeout(), 10)
373 s.close()
374
375 # Reset the default timeout to None, and see if it propagates
376 socket.setdefaulttimeout(None)
377 self.assertEqual(socket.getdefaulttimeout(), None)
378 s = socket.socket()
379 self.assertEqual(s.gettimeout(), None)
380 s.close()
381
382 # Check that setting it to an invalid value raises ValueError
383 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
384
385 # Check that setting it to an invalid type raises TypeError
386 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
387
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000388 def testIPv4toString(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 from socket import inet_aton as f, inet_pton, AF_INET
392 g = lambda a: inet_pton(AF_INET, a)
393
394 self.assertEquals('\x00\x00\x00\x00', f('0.0.0.0'))
395 self.assertEquals('\xff\x00\xff\x00', f('255.0.255.0'))
396 self.assertEquals('\xaa\xaa\xaa\xaa', f('170.170.170.170'))
397 self.assertEquals('\x01\x02\x03\x04', f('1.2.3.4'))
Georg Brandld2e3ba72005-08-26 08:34:00 +0000398 self.assertEquals('\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000399
400 self.assertEquals('\x00\x00\x00\x00', g('0.0.0.0'))
401 self.assertEquals('\xff\x00\xff\x00', g('255.0.255.0'))
402 self.assertEquals('\xaa\xaa\xaa\xaa', g('170.170.170.170'))
Georg Brandld2e3ba72005-08-26 08:34:00 +0000403 self.assertEquals('\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000404
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000405 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000406 if not hasattr(socket, 'inet_pton'):
407 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000408 try:
409 from socket import inet_pton, AF_INET6, has_ipv6
410 if not has_ipv6:
411 return
412 except ImportError:
413 return
414 f = lambda a: inet_pton(AF_INET6, a)
415
416 self.assertEquals('\x00' * 16, f('::'))
417 self.assertEquals('\x00' * 16, f('0::0'))
418 self.assertEquals('\x00\x01' + '\x00' * 14, f('1::'))
419 self.assertEquals(
420 '\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
421 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
422 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000423
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000424 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000425 if not hasattr(socket, 'inet_ntop'):
426 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000427 from socket import inet_ntoa as f, inet_ntop, AF_INET
428 g = lambda a: inet_ntop(AF_INET, a)
429
430 self.assertEquals('1.0.1.0', f('\x01\x00\x01\x00'))
431 self.assertEquals('170.85.170.85', f('\xaa\x55\xaa\x55'))
432 self.assertEquals('255.255.255.255', f('\xff\xff\xff\xff'))
433 self.assertEquals('1.2.3.4', f('\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000434
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000435 self.assertEquals('1.0.1.0', g('\x01\x00\x01\x00'))
436 self.assertEquals('170.85.170.85', g('\xaa\x55\xaa\x55'))
437 self.assertEquals('255.255.255.255', g('\xff\xff\xff\xff'))
438
439 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000440 if not hasattr(socket, 'inet_ntop'):
441 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000442 try:
443 from socket import inet_ntop, AF_INET6, has_ipv6
444 if not has_ipv6:
445 return
446 except ImportError:
447 return
448 f = lambda a: inet_ntop(AF_INET6, a)
449
450 self.assertEquals('::', f('\x00' * 16))
451 self.assertEquals('::1', f('\x00' * 15 + '\x01'))
452 self.assertEquals(
453 'aef:b01:506:1001:ffff:9997:55:170',
454 f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
455 )
456
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000457 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000458
Guido van Rossum24e4af82002-06-12 19:18:08 +0000459 def testSockName(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000460 # Testing getsockname(). Use a temporary socket to elicit an unused
461 # ephemeral port that we can use later in the test.
462 tempsock = socket.socket()
463 tempsock.bind(("0.0.0.0", 0))
464 (host, port) = tempsock.getsockname()
465 tempsock.close()
466 del tempsock
467
Guido van Rossum24e4af82002-06-12 19:18:08 +0000468 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Trent Nelsone41b0062008-04-08 23:47:30 +0000469 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000470 name = sock.getsockname()
Neal Norwitz4a9ff162006-06-11 21:38:38 +0000471 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
472 # it reasonable to get the host's addr in addition to 0.0.0.0.
473 # At least for eCos. This is required for the S/390 to pass.
474 my_ip_addr = socket.gethostbyname(socket.gethostname())
475 self.assert_(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Trent Nelsone41b0062008-04-08 23:47:30 +0000476 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000477
478 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000479 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000480 # We know a socket should start without reuse==0
481 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
482 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000483 self.failIf(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000484
485 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000486 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000487 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
488 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
489 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000490 self.failIf(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000491
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000492 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000493 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000494 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
495 sock.settimeout(1)
496 sock.close()
497 self.assertRaises(socket.error, sock.send, "spam")
498
Georg Brandlbb03ac02006-03-21 18:17:25 +0000499 def testNewAttributes(self):
500 # testing .family, .type and .protocol
Georg Brandlbc45a3f2006-03-17 19:17:34 +0000501 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlbb03ac02006-03-21 18:17:25 +0000502 self.assertEqual(sock.family, socket.AF_INET)
503 self.assertEqual(sock.type, socket.SOCK_STREAM)
504 self.assertEqual(sock.proto, 0)
Georg Brandlbc45a3f2006-03-17 19:17:34 +0000505 sock.close()
506
Christian Heimesa47b75b2008-01-04 15:48:06 +0000507 def test_sock_ioctl(self):
508 if os.name != "nt":
509 return
510 self.assert_(hasattr(socket.socket, 'ioctl'))
511 self.assert_(hasattr(socket, 'SIO_RCVALL'))
512 self.assert_(hasattr(socket, 'RCVALL_ON'))
513 self.assert_(hasattr(socket, 'RCVALL_OFF'))
514
515
Guido van Rossum24e4af82002-06-12 19:18:08 +0000516class BasicTCPTest(SocketConnectedTest):
517
518 def __init__(self, methodName='runTest'):
519 SocketConnectedTest.__init__(self, methodName=methodName)
520
521 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000522 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000523 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000524 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000525
526 def _testRecv(self):
527 self.serv_conn.send(MSG)
528
529 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000530 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000531 seg1 = self.cli_conn.recv(len(MSG) - 3)
532 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000533 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000534 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000535
536 def _testOverFlowRecv(self):
537 self.serv_conn.send(MSG)
538
539 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000540 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000541 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000542 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000543
544 def _testRecvFrom(self):
545 self.serv_conn.send(MSG)
546
547 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000548 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000549 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
550 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000551 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000552 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000553
554 def _testOverFlowRecvFrom(self):
555 self.serv_conn.send(MSG)
556
557 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000558 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossume531e292002-08-08 20:28:34 +0000559 msg = ''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000560 while 1:
561 read = self.cli_conn.recv(1024)
562 if not read:
563 break
Guido van Rossume531e292002-08-08 20:28:34 +0000564 msg += read
565 self.assertEqual(msg, 'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000566
567 def _testSendAll(self):
Guido van Rossumab659962002-06-12 21:29:43 +0000568 big_chunk = 'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000569 self.serv_conn.sendall(big_chunk)
570
571 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000572 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000573 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000574 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000575 fd = self.cli_conn.fileno()
576 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
577 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000578 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000579
580 def _testFromFd(self):
581 self.serv_conn.send(MSG)
582
583 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000584 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000585 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000586 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000587
588 def _testShutdown(self):
589 self.serv_conn.send(MSG)
590 self.serv_conn.shutdown(2)
591
592class BasicUDPTest(ThreadedUDPSocketTest):
593
594 def __init__(self, methodName='runTest'):
595 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
596
597 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000598 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000599 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000600 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000601
602 def _testSendtoAndRecv(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000603 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000604
Guido van Rossum1c938012002-06-12 21:17:20 +0000605 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000606 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000607 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000608 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000609
Guido van Rossum1c938012002-06-12 21:17:20 +0000610 def _testRecvFrom(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000611 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000612
Facundo Batista1fe9f962007-03-28 03:45:20 +0000613 def testRecvFromNegative(self):
614 # Negative lengths passed to recvfrom should give ValueError.
615 self.assertRaises(ValueError, self.serv.recvfrom, -1)
616
617 def _testRecvFromNegative(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000618 self.cli.sendto(MSG, 0, (HOST, self.port))
Facundo Batista1fe9f962007-03-28 03:45:20 +0000619
Martin v. Löwis7596e832006-07-01 15:33:37 +0000620class TCPCloserTest(ThreadedTCPSocketTest):
621
622 def testClose(self):
623 conn, addr = self.serv.accept()
624 conn.close()
625
626 sd = self.cli
627 read, write, err = select.select([sd], [], [], 1.0)
628 self.assertEqual(read, [sd])
629 self.assertEqual(sd.recv(1), '')
630
631 def _testClose(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000632 self.cli.connect((HOST, self.port))
Martin v. Löwis7596e832006-07-01 15:33:37 +0000633 time.sleep(1.0)
634
Dave Cole331708b2004-08-09 04:51:41 +0000635class BasicSocketPairTest(SocketPairTest):
636
637 def __init__(self, methodName='runTest'):
638 SocketPairTest.__init__(self, methodName=methodName)
639
640 def testRecv(self):
641 msg = self.serv.recv(1024)
642 self.assertEqual(msg, MSG)
643
644 def _testRecv(self):
645 self.cli.send(MSG)
646
647 def testSend(self):
648 self.serv.send(MSG)
649
650 def _testSend(self):
651 msg = self.cli.recv(1024)
652 self.assertEqual(msg, MSG)
653
Guido van Rossum24e4af82002-06-12 19:18:08 +0000654class NonBlockingTCPTests(ThreadedTCPSocketTest):
655
656 def __init__(self, methodName='runTest'):
657 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
658
659 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000660 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000661 self.serv.setblocking(0)
662 start = time.time()
663 try:
664 self.serv.accept()
665 except socket.error:
666 pass
667 end = time.time()
668 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
669
670 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000671 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000672
Guido van Rossum24e4af82002-06-12 19:18:08 +0000673 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000674 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000675 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000676 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000677 conn, addr = self.serv.accept()
678 except socket.error:
679 pass
680 else:
681 self.fail("Error trying to do non-blocking accept.")
682 read, write, err = select.select([self.serv], [], [])
683 if self.serv in read:
684 conn, addr = self.serv.accept()
685 else:
686 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000687
Guido van Rossum24e4af82002-06-12 19:18:08 +0000688 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000689 time.sleep(0.1)
Trent Nelsone41b0062008-04-08 23:47:30 +0000690 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000691
692 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000693 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000694 conn, addr = self.serv.accept()
695
696 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000697 self.cli.settimeout(10)
Trent Nelsone41b0062008-04-08 23:47:30 +0000698 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000699
700 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000701 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000702 conn, addr = self.serv.accept()
703 conn.setblocking(0)
704 try:
705 msg = conn.recv(len(MSG))
706 except socket.error:
707 pass
708 else:
709 self.fail("Error trying to do non-blocking recv.")
710 read, write, err = select.select([conn], [], [])
711 if conn in read:
712 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000713 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000714 else:
715 self.fail("Error during select call to non-blocking socket.")
716
717 def _testRecv(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000718 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000719 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000720 self.cli.send(MSG)
721
722class FileObjectClassTestCase(SocketConnectedTest):
723
Guido van Rossume9f66142002-08-07 15:46:19 +0000724 bufsize = -1 # Use default buffer size
725
Guido van Rossum24e4af82002-06-12 19:18:08 +0000726 def __init__(self, methodName='runTest'):
727 SocketConnectedTest.__init__(self, methodName=methodName)
728
729 def setUp(self):
730 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000731 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000732
733 def tearDown(self):
734 self.serv_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000735 self.assert_(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000736 self.serv_file = None
737 SocketConnectedTest.tearDown(self)
738
739 def clientSetUp(self):
740 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000741 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000742
743 def clientTearDown(self):
744 self.cli_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000745 self.assert_(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000746 self.cli_file = None
747 SocketConnectedTest.clientTearDown(self)
748
749 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000750 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000751 first_seg = self.serv_file.read(len(MSG)-3)
752 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000753 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000754 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000755
756 def _testSmallRead(self):
757 self.cli_file.write(MSG)
758 self.cli_file.flush()
759
Guido van Rossum8c943832002-08-08 01:00:28 +0000760 def testFullRead(self):
761 # read until EOF
762 msg = self.serv_file.read()
763 self.assertEqual(msg, MSG)
764
765 def _testFullRead(self):
766 self.cli_file.write(MSG)
767 self.cli_file.close()
768
Guido van Rossum24e4af82002-06-12 19:18:08 +0000769 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000770 # Performing unbuffered file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000771 buf = ''
772 while 1:
773 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000774 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000775 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000776 buf += char
777 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000778
779 def _testUnbufferedRead(self):
780 self.cli_file.write(MSG)
781 self.cli_file.flush()
782
783 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000784 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000785 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000786 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000787
788 def _testReadline(self):
789 self.cli_file.write(MSG)
790 self.cli_file.flush()
791
Gregory P. Smith24237ea2008-05-05 21:53:45 +0000792 def testReadlineAfterRead(self):
793 a_baloo_is = self.serv_file.read(len("A baloo is"))
794 self.assertEqual("A baloo is", a_baloo_is)
795 _a_bear = self.serv_file.read(len(" a bear"))
796 self.assertEqual(" a bear", _a_bear)
797 line = self.serv_file.readline()
798 self.assertEqual("\n", line)
799 line = self.serv_file.readline()
800 self.assertEqual("A BALOO IS A BEAR.\n", line)
801 line = self.serv_file.readline()
802 self.assertEqual(MSG, line)
803
804 def _testReadlineAfterRead(self):
805 self.cli_file.write("A baloo is a bear\n")
806 self.cli_file.write("A BALOO IS A BEAR.\n")
807 self.cli_file.write(MSG)
808 self.cli_file.flush()
809
810 def testReadlineAfterReadNoNewline(self):
811 end_of_ = self.serv_file.read(len("End Of "))
812 self.assertEqual("End Of ", end_of_)
813 line = self.serv_file.readline()
814 self.assertEqual("Line", line)
815
816 def _testReadlineAfterReadNoNewline(self):
817 self.cli_file.write("End Of Line")
818
Tim Peters116d83c2004-03-28 02:20:45 +0000819 def testClosedAttr(self):
820 self.assert_(not self.serv_file.closed)
821
822 def _testClosedAttr(self):
823 self.assert_(not self.cli_file.closed)
824
Guido van Rossume9f66142002-08-07 15:46:19 +0000825class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
826
827 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000828
Guido van Rossume9f66142002-08-07 15:46:19 +0000829 In this case (and in this case only), it should be possible to
830 create a file object, read a line from it, create another file
831 object, read another line from it, without loss of data in the
832 first file object's buffer. Note that httplib relies on this
833 when reading multiple requests from the same socket."""
834
835 bufsize = 0 # Use unbuffered mode
836
837 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000838 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000839 line = self.serv_file.readline() # first line
Guido van Rossum10e3f412002-08-07 19:02:49 +0000840 self.assertEqual(line, "A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000841 self.serv_file = self.cli_conn.makefile('rb', 0)
842 line = self.serv_file.readline() # second line
Guido van Rossum10e3f412002-08-07 19:02:49 +0000843 self.assertEqual(line, "B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000844
845 def _testUnbufferedReadline(self):
Guido van Rossum10e3f412002-08-07 19:02:49 +0000846 self.cli_file.write("A. " + MSG)
847 self.cli_file.write("B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000848 self.cli_file.flush()
849
Guido van Rossum8c943832002-08-08 01:00:28 +0000850class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
851
852 bufsize = 1 # Default-buffered for reading; line-buffered for writing
853
854
855class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
856
857 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000858
Georg Brandldd7b0522007-01-21 10:35:10 +0000859
Facundo Batista07c78be2007-03-23 18:54:07 +0000860class NetworkConnectionTest(object):
861 """Prove network connection."""
862 def clientSetUp(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000863 # We're inherited below by BasicTCPTest2, which also inherits
864 # BasicTCPTest, which defines self.port referenced below.
865 self.cli = socket.create_connection((HOST, self.port))
Facundo Batista07c78be2007-03-23 18:54:07 +0000866 self.serv_conn = self.cli
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000867
Facundo Batista07c78be2007-03-23 18:54:07 +0000868class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
869 """Tests that NetworkConnection does not break existing TCP functionality.
870 """
871
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000872class NetworkConnectionNoServer(unittest.TestCase):
Facundo Batista07c78be2007-03-23 18:54:07 +0000873 def testWithoutServer(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000874 port = test_support.find_unused_port()
875 self.failUnlessRaises(
876 socket.error,
877 lambda: socket.create_connection((HOST, port))
878 )
Facundo Batista07c78be2007-03-23 18:54:07 +0000879
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000880class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
881
882 def __init__(self, methodName='runTest'):
883 SocketTCPTest.__init__(self, methodName=methodName)
884 ThreadableTest.__init__(self)
885
886 def clientSetUp(self):
887 pass
888
889 def clientTearDown(self):
890 self.cli.close()
891 self.cli = None
892 ThreadableTest.clientTearDown(self)
893
894 def _justAccept(self):
895 conn, addr = self.serv.accept()
896
897 testFamily = _justAccept
898 def _testFamily(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000899 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000900 self.assertEqual(self.cli.family, 2)
901
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000902 testTimeoutDefault = _justAccept
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000903 def _testTimeoutDefault(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000904 self.cli = socket.create_connection((HOST, self.port))
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000905 self.assertTrue(self.cli.gettimeout() is None)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000906
907 testTimeoutValueNamed = _justAccept
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000908 def _testTimeoutValueNamed(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000909 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000910 self.assertEqual(self.cli.gettimeout(), 30)
Facundo Batista07c78be2007-03-23 18:54:07 +0000911
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000912 testTimeoutValueNonamed = _justAccept
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000913 def _testTimeoutValueNonamed(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000914 self.cli = socket.create_connection((HOST, self.port), 30)
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000915 self.assertEqual(self.cli.gettimeout(), 30)
Facundo Batista07c78be2007-03-23 18:54:07 +0000916
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000917 testTimeoutNone = _justAccept
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000918 def _testTimeoutNone(self):
Facundo Batista07c78be2007-03-23 18:54:07 +0000919 previous = socket.getdefaulttimeout()
Facundo Batista14553b02007-03-23 20:23:08 +0000920 socket.setdefaulttimeout(30)
921 try:
Trent Nelsone41b0062008-04-08 23:47:30 +0000922 self.cli = socket.create_connection((HOST, self.port), timeout=None)
Facundo Batista14553b02007-03-23 20:23:08 +0000923 finally:
924 socket.setdefaulttimeout(previous)
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000925 self.assertEqual(self.cli.gettimeout(), 30)
Facundo Batista07c78be2007-03-23 18:54:07 +0000926
927
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000928class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
929
930 def __init__(self, methodName='runTest'):
931 SocketTCPTest.__init__(self, methodName=methodName)
932 ThreadableTest.__init__(self)
933
934 def clientSetUp(self):
935 pass
936
937 def clientTearDown(self):
938 self.cli.close()
939 self.cli = None
940 ThreadableTest.clientTearDown(self)
941
Facundo Batista07c78be2007-03-23 18:54:07 +0000942 def testInsideTimeout(self):
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000943 conn, addr = self.serv.accept()
944 time.sleep(3)
945 conn.send("done!")
946 testOutsideTimeout = testInsideTimeout
947
948 def _testInsideTimeout(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000949 self.cli = sock = socket.create_connection((HOST, self.port))
Facundo Batista07c78be2007-03-23 18:54:07 +0000950 data = sock.recv(5)
951 self.assertEqual(data, "done!")
952
Facundo Batistab8af7bc2007-03-25 01:53:21 +0000953 def _testOutsideTimeout(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000954 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Facundo Batista07c78be2007-03-23 18:54:07 +0000955 self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
956
957
Georg Brandldd7b0522007-01-21 10:35:10 +0000958class Urllib2FileobjectTest(unittest.TestCase):
959
960 # urllib2.HTTPHandler has "borrowed" socket._fileobject, and requires that
961 # it close the socket if the close c'tor argument is true
962
963 def testClose(self):
964 class MockSocket:
965 closed = False
966 def flush(self): pass
967 def close(self): self.closed = True
968
969 # must not close unless we request it: the original use of _fileobject
970 # by module socket requires that the underlying socket not be closed until
971 # the _socketobject that created the _fileobject is closed
972 s = MockSocket()
973 f = socket._fileobject(s)
974 f.close()
975 self.assert_(not s.closed)
976
977 s = MockSocket()
978 f = socket._fileobject(s, close=True)
979 f.close()
980 self.assert_(s.closed)
981
Raymond Hettinger11a35f52003-06-29 04:40:22 +0000982class TCPTimeoutTest(SocketTCPTest):
983
984 def testTCPTimeout(self):
985 def raise_timeout(*args, **kwargs):
986 self.serv.settimeout(1.0)
987 self.serv.accept()
988 self.failUnlessRaises(socket.timeout, raise_timeout,
989 "Error generating a timeout exception (TCP)")
990
991 def testTimeoutZero(self):
992 ok = False
993 try:
994 self.serv.settimeout(0.0)
995 foo = self.serv.accept()
996 except socket.timeout:
997 self.fail("caught timeout instead of error (TCP)")
998 except socket.error:
999 ok = True
1000 except:
1001 self.fail("caught unexpected exception (TCP)")
1002 if not ok:
1003 self.fail("accept() returned success when we did not expect it")
1004
Neal Norwitz9b0ca792006-08-02 06:46:21 +00001005 def testInterruptedTimeout(self):
1006 # XXX I don't know how to do this test on MSWindows or any other
1007 # plaform that doesn't support signal.alarm() or os.kill(), though
1008 # the bug should have existed on all platforms.
1009 if not hasattr(signal, "alarm"):
1010 return # can only test on *nix
1011 self.serv.settimeout(5.0) # must be longer than alarm
1012 class Alarm(Exception):
1013 pass
1014 def alarm_handler(signal, frame):
1015 raise Alarm
1016 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1017 try:
1018 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1019 try:
1020 foo = self.serv.accept()
1021 except socket.timeout:
1022 self.fail("caught timeout instead of Alarm")
1023 except Alarm:
1024 pass
1025 except:
Jeffrey Yasskin36550bd2008-03-28 04:53:10 +00001026 self.fail("caught other exception instead of Alarm:"
1027 " %s(%s):\n%s" %
1028 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Neal Norwitz9b0ca792006-08-02 06:46:21 +00001029 else:
1030 self.fail("nothing caught")
Jeffrey Yasskin36550bd2008-03-28 04:53:10 +00001031 finally:
1032 signal.alarm(0) # shut off alarm
Neal Norwitz9b0ca792006-08-02 06:46:21 +00001033 except Alarm:
1034 self.fail("got Alarm in wrong place")
1035 finally:
1036 # no alarm can be pending. Safe to restore old handler.
1037 signal.signal(signal.SIGALRM, old_alarm)
1038
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001039class UDPTimeoutTest(SocketTCPTest):
1040
1041 def testUDPTimeout(self):
1042 def raise_timeout(*args, **kwargs):
1043 self.serv.settimeout(1.0)
1044 self.serv.recv(1024)
1045 self.failUnlessRaises(socket.timeout, raise_timeout,
1046 "Error generating a timeout exception (UDP)")
1047
1048 def testTimeoutZero(self):
1049 ok = False
1050 try:
1051 self.serv.settimeout(0.0)
1052 foo = self.serv.recv(1024)
1053 except socket.timeout:
1054 self.fail("caught timeout instead of error (UDP)")
1055 except socket.error:
1056 ok = True
1057 except:
1058 self.fail("caught unexpected exception (UDP)")
1059 if not ok:
1060 self.fail("recv() returned success when we did not expect it")
1061
1062class TestExceptions(unittest.TestCase):
1063
1064 def testExceptionTree(self):
1065 self.assert_(issubclass(socket.error, Exception))
1066 self.assert_(issubclass(socket.herror, socket.error))
1067 self.assert_(issubclass(socket.gaierror, socket.error))
1068 self.assert_(issubclass(socket.timeout, socket.error))
1069
Armin Rigoa9017c32006-04-19 11:50:27 +00001070class TestLinuxAbstractNamespace(unittest.TestCase):
1071
1072 UNIX_PATH_MAX = 108
1073
1074 def testLinuxAbstractNamespace(self):
1075 address = "\x00python-test-hello\x00\xff"
1076 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1077 s1.bind(address)
1078 s1.listen(1)
1079 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1080 s2.connect(s1.getsockname())
1081 s1.accept()
1082 self.assertEqual(s1.getsockname(), address)
1083 self.assertEqual(s2.getpeername(), address)
1084
1085 def testMaxName(self):
1086 address = "\x00" + "h" * (self.UNIX_PATH_MAX - 1)
1087 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1088 s.bind(address)
1089 self.assertEqual(s.getsockname(), address)
1090
1091 def testNameOverflow(self):
1092 address = "\x00" + "h" * self.UNIX_PATH_MAX
1093 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1094 self.assertRaises(socket.error, s.bind, address)
1095
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001096
Martin Blais2856e5f2006-05-26 12:03:27 +00001097class BufferIOTest(SocketConnectedTest):
1098 """
1099 Test the buffer versions of socket.recv() and socket.send().
1100 """
1101 def __init__(self, methodName='runTest'):
1102 SocketConnectedTest.__init__(self, methodName=methodName)
1103
Martin Blaisaf2ae722006-06-04 13:49:49 +00001104 def testRecvInto(self):
Martin Blais2856e5f2006-05-26 12:03:27 +00001105 buf = array.array('c', ' '*1024)
Martin Blaisaf2ae722006-06-04 13:49:49 +00001106 nbytes = self.cli_conn.recv_into(buf)
Martin Blais2856e5f2006-05-26 12:03:27 +00001107 self.assertEqual(nbytes, len(MSG))
1108 msg = buf.tostring()[:len(MSG)]
1109 self.assertEqual(msg, MSG)
1110
Martin Blaisaf2ae722006-06-04 13:49:49 +00001111 def _testRecvInto(self):
Martin Blais2856e5f2006-05-26 12:03:27 +00001112 buf = buffer(MSG)
1113 self.serv_conn.send(buf)
1114
Martin Blaisaf2ae722006-06-04 13:49:49 +00001115 def testRecvFromInto(self):
Martin Blais2856e5f2006-05-26 12:03:27 +00001116 buf = array.array('c', ' '*1024)
Martin Blaisaf2ae722006-06-04 13:49:49 +00001117 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Martin Blais2856e5f2006-05-26 12:03:27 +00001118 self.assertEqual(nbytes, len(MSG))
1119 msg = buf.tostring()[:len(MSG)]
1120 self.assertEqual(msg, MSG)
1121
Martin Blaisaf2ae722006-06-04 13:49:49 +00001122 def _testRecvFromInto(self):
Martin Blais2856e5f2006-05-26 12:03:27 +00001123 buf = buffer(MSG)
1124 self.serv_conn.send(buf)
1125
Christian Heimesfb2d25a2008-01-07 16:12:44 +00001126
1127TIPC_STYPE = 2000
1128TIPC_LOWER = 200
1129TIPC_UPPER = 210
1130
1131def isTipcAvailable():
1132 """Check if the TIPC module is loaded
1133
1134 The TIPC module is not loaded automatically on Ubuntu and probably
1135 other Linux distros.
1136 """
1137 if not hasattr(socket, "AF_TIPC"):
1138 return False
1139 if not os.path.isfile("/proc/modules"):
1140 return False
1141 with open("/proc/modules") as f:
1142 for line in f:
1143 if line.startswith("tipc "):
1144 return True
Christian Heimesf66f95d2008-01-08 03:40:04 +00001145 if test_support.verbose:
Christian Heimesfb2d25a2008-01-07 16:12:44 +00001146 print "TIPC module is not loaded, please 'sudo modprobe tipc'"
1147 return False
1148
1149class TIPCTest (unittest.TestCase):
1150 def testRDM(self):
1151 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1152 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1153
1154 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1155 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1156 TIPC_LOWER, TIPC_UPPER)
1157 srv.bind(srvaddr)
1158
1159 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1160 TIPC_LOWER + (TIPC_UPPER - TIPC_LOWER) / 2, 0)
1161 cli.sendto(MSG, sendaddr)
1162
1163 msg, recvaddr = srv.recvfrom(1024)
1164
1165 self.assertEqual(cli.getsockname(), recvaddr)
1166 self.assertEqual(msg, MSG)
1167
1168
1169class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1170 def __init__(self, methodName = 'runTest'):
1171 unittest.TestCase.__init__(self, methodName = methodName)
1172 ThreadableTest.__init__(self)
1173
1174 def setUp(self):
1175 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1176 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1177 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1178 TIPC_LOWER, TIPC_UPPER)
1179 self.srv.bind(srvaddr)
1180 self.srv.listen(5)
1181 self.serverExplicitReady()
1182 self.conn, self.connaddr = self.srv.accept()
1183
1184 def clientSetUp(self):
1185 # The is a hittable race between serverExplicitReady() and the
1186 # accept() call; sleep a little while to avoid it, otherwise
1187 # we could get an exception
1188 time.sleep(0.1)
1189 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1190 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1191 TIPC_LOWER + (TIPC_UPPER - TIPC_LOWER) / 2, 0)
1192 self.cli.connect(addr)
1193 self.cliaddr = self.cli.getsockname()
1194
1195 def testStream(self):
1196 msg = self.conn.recv(1024)
1197 self.assertEqual(msg, MSG)
1198 self.assertEqual(self.cliaddr, self.connaddr)
1199
1200 def _testStream(self):
1201 self.cli.send(MSG)
1202 self.cli.close()
1203
1204
Guido van Rossumb995eb72002-07-31 16:08:40 +00001205def test_main():
Martin v. Löwis7596e832006-07-01 15:33:37 +00001206 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Facundo Batista07c78be2007-03-23 18:54:07 +00001207 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001208 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001209 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001210
1211 tests.extend([
1212 NonBlockingTCPTests,
1213 FileObjectClassTestCase,
1214 UnbufferedFileObjectClassTestCase,
1215 LineBufferedFileObjectClassTestCase,
Georg Brandldd7b0522007-01-21 10:35:10 +00001216 SmallBufferedFileObjectClassTestCase,
1217 Urllib2FileobjectTest,
Facundo Batistab8af7bc2007-03-25 01:53:21 +00001218 NetworkConnectionNoServer,
Facundo Batista07c78be2007-03-23 18:54:07 +00001219 NetworkConnectionAttributesTest,
1220 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001221 ])
Dave Cole331708b2004-08-09 04:51:41 +00001222 if hasattr(socket, "socketpair"):
1223 tests.append(BasicSocketPairTest)
Armin Rigoa9017c32006-04-19 11:50:27 +00001224 if sys.platform == 'linux2':
1225 tests.append(TestLinuxAbstractNamespace)
Christian Heimesfb2d25a2008-01-07 16:12:44 +00001226 if isTipcAvailable():
1227 tests.append(TIPCTest)
Christian Heimes4d7e6702008-01-07 19:58:41 +00001228 tests.append(TIPCThreadableTest)
Neal Norwitz9602cc22006-06-18 19:35:01 +00001229
1230 thread_info = test_support.threading_setup()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001231 test_support.run_unittest(*tests)
Neal Norwitz9602cc22006-06-18 19:35:01 +00001232 test_support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001233
1234if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001235 test_main()