blob: ea83cd1b4346b5373eecc8c7ecec4499a2a75915 [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
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test import support
Barry Warsawcf3d4b51997-01-03 20:03:32 +00005
Christian Heimes5e696852008-04-09 08:37:03 +00006import errno
Barry Warsawcf3d4b51997-01-03 20:03:32 +00007import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00008import select
Georg Brandl2067bfd2008-05-25 13:05:15 +00009import _thread as thread
10import threading
Christian Heimesbbe741d2008-03-28 10:53:29 +000011import time
12import traceback
Alexandre Vassalottif260e442008-05-11 19:59:59 +000013import queue
Jack Jansen522e7692002-09-06 21:57:50 +000014import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000015import os
16import array
Antoine Pitrou4d7979b2010-09-07 21:22:56 +000017import contextlib
Raymond Hettinger027bb632004-05-31 03:09:25 +000018from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019import signal
Antoine Pitrou08ae02f2010-09-27 18:14:43 +000020import math
Barry Warsawcf3d4b51997-01-03 20:03:32 +000021
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +000022def try_address(host, port=0, family=socket.AF_INET):
23 """Try to bind a socket on the given host:port and return True
24 if that has been possible."""
25 try:
26 sock = socket.socket(family, socket.SOCK_STREAM)
27 sock.bind((host, port))
28 except (socket.error, socket.gaierror):
29 return False
30 else:
31 sock.close()
32 return True
33
Benjamin Petersonee8712c2008-05-20 21:35:26 +000034HOST = support.HOST
Guido van Rossum7d0a8262007-05-21 23:13:11 +000035MSG = b'Michael Gilfix was here\n'
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +000036SUPPORTS_IPV6 = socket.has_ipv6 and try_address('::1', family=socket.AF_INET6)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000037
Guido van Rossum24e4af82002-06-12 19:18:08 +000038class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000039
Guido van Rossum24e4af82002-06-12 19:18:08 +000040 def setUp(self):
41 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000042 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000043 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000044
Guido van Rossum24e4af82002-06-12 19:18:08 +000045 def tearDown(self):
46 self.serv.close()
47 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000048
Guido van Rossum24e4af82002-06-12 19:18:08 +000049class SocketUDPTest(unittest.TestCase):
50
51 def setUp(self):
52 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000053 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000054
55 def tearDown(self):
56 self.serv.close()
57 self.serv = None
58
59class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000060 """Threadable Test class
61
62 The ThreadableTest class makes it easy to create a threaded
63 client/server pair from an existing unit test. To create a
64 new threaded class from an existing unit test, use multiple
65 inheritance:
66
67 class NewClass (OldClass, ThreadableTest):
68 pass
69
70 This class defines two new fixture functions with obvious
71 purposes for overriding:
72
73 clientSetUp ()
74 clientTearDown ()
75
76 Any new test functions within the class must then define
77 tests in pairs, where the test name is preceeded with a
78 '_' to indicate the client portion of the test. Ex:
79
80 def testFoo(self):
81 # Server portion
82
83 def _testFoo(self):
84 # Client portion
85
86 Any exceptions raised by the clients during their tests
87 are caught and transferred to the main thread to alert
88 the testing framework.
89
90 Note, the server setup function cannot call any blocking
91 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +000092 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000093 the blocking call (such as in setting up a client/server
94 connection and performing the accept() in setUp().
95 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000096
97 def __init__(self):
98 # Swap the true setup function
99 self.__setUp = self.setUp
100 self.__tearDown = self.tearDown
101 self.setUp = self._setUp
102 self.tearDown = self._tearDown
103
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000104 def serverExplicitReady(self):
105 """This method allows the server to explicitly indicate that
106 it wants the client thread to proceed. This is useful if the
107 server is about to execute a blocking routine that is
108 dependent upon the client thread during its setup routine."""
109 self.server_ready.set()
110
Guido van Rossum24e4af82002-06-12 19:18:08 +0000111 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000112 self.server_ready = threading.Event()
113 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000114 self.done = threading.Event()
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000115 self.queue = queue.Queue(1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000116
117 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000118 methodname = self.id()
119 i = methodname.rfind('.')
120 methodname = methodname[i+1:]
121 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000122 self.client_thread = thread.start_new_thread(
123 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000124
125 self.__setUp()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000126 if not self.server_ready.is_set():
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000127 self.server_ready.set()
128 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000129
130 def _tearDown(self):
131 self.__tearDown()
132 self.done.wait()
133
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000134 if self.queue.qsize():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000135 msg = self.queue.get()
136 self.fail(msg)
137
138 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000139 self.server_ready.wait()
140 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000141 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000142 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000143 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000144 try:
145 test_func()
Guido van Rossumb940e112007-01-10 16:19:56 +0000146 except Exception as strerror:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000147 self.queue.put(strerror)
148 self.clientTearDown()
149
150 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000151 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000152
153 def clientTearDown(self):
154 self.done.set()
155 thread.exit()
156
157class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
158
159 def __init__(self, methodName='runTest'):
160 SocketTCPTest.__init__(self, methodName=methodName)
161 ThreadableTest.__init__(self)
162
163 def clientSetUp(self):
164 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
165
166 def clientTearDown(self):
167 self.cli.close()
168 self.cli = None
169 ThreadableTest.clientTearDown(self)
170
171class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
172
173 def __init__(self, methodName='runTest'):
174 SocketUDPTest.__init__(self, methodName=methodName)
175 ThreadableTest.__init__(self)
176
177 def clientSetUp(self):
178 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
179
180class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000181 """Socket tests for client-server connection.
182
183 self.cli_conn is a client socket connected to the server. The
184 setUp() method guarantees that it is connected to the server.
185 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000186
187 def __init__(self, methodName='runTest'):
188 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
189
190 def setUp(self):
191 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000192 # Indicate explicitly we're ready for the client thread to
193 # proceed and then perform the blocking call to accept
194 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000195 conn, addr = self.serv.accept()
196 self.cli_conn = conn
197
198 def tearDown(self):
199 self.cli_conn.close()
200 self.cli_conn = None
201 ThreadedTCPSocketTest.tearDown(self)
202
203 def clientSetUp(self):
204 ThreadedTCPSocketTest.clientSetUp(self)
Christian Heimes5e696852008-04-09 08:37:03 +0000205 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000206 self.serv_conn = self.cli
207
208 def clientTearDown(self):
209 self.serv_conn.close()
210 self.serv_conn = None
211 ThreadedTCPSocketTest.clientTearDown(self)
212
Dave Cole331708b2004-08-09 04:51:41 +0000213class SocketPairTest(unittest.TestCase, ThreadableTest):
214
215 def __init__(self, methodName='runTest'):
216 unittest.TestCase.__init__(self, methodName=methodName)
217 ThreadableTest.__init__(self)
218
219 def setUp(self):
220 self.serv, self.cli = socket.socketpair()
221
222 def tearDown(self):
223 self.serv.close()
224 self.serv = None
225
226 def clientSetUp(self):
227 pass
228
229 def clientTearDown(self):
230 self.cli.close()
231 self.cli = None
232 ThreadableTest.clientTearDown(self)
233
Tim Peters494aaee2004-08-09 18:54:11 +0000234
Guido van Rossum24e4af82002-06-12 19:18:08 +0000235#######################################################################
236## Begin Tests
237
238class GeneralModuleTests(unittest.TestCase):
239
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000240 def test_repr(self):
241 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlab91fde2009-08-13 08:51:18 +0000242 self.assertTrue(repr(s).startswith("<socket.socket object"))
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000243
Raymond Hettinger027bb632004-05-31 03:09:25 +0000244 def test_weakref(self):
245 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
246 p = proxy(s)
247 self.assertEqual(p.fileno(), s.fileno())
248 s.close()
249 s = None
250 try:
251 p.fileno()
252 except ReferenceError:
253 pass
254 else:
255 self.fail('Socket proxy still exists')
256
Guido van Rossum24e4af82002-06-12 19:18:08 +0000257 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000258 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000259 def raise_error(*args, **kwargs):
260 raise socket.error
261 def raise_herror(*args, **kwargs):
262 raise socket.herror
263 def raise_gaierror(*args, **kwargs):
264 raise socket.gaierror
Georg Brandlab91fde2009-08-13 08:51:18 +0000265 self.assertRaises(socket.error, raise_error,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000266 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000267 self.assertRaises(socket.error, raise_herror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000268 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000269 self.assertRaises(socket.error, raise_gaierror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000270 "Error raising socket exception.")
271
272 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000273 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000274 socket.AF_INET
275 socket.SOCK_STREAM
276 socket.SOCK_DGRAM
277 socket.SOCK_RAW
278 socket.SOCK_RDM
279 socket.SOCK_SEQPACKET
280 socket.SOL_SOCKET
281 socket.SO_REUSEADDR
282
Guido van Rossum654c11e2002-06-13 20:24:17 +0000283 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000284 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000285 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000286 try:
287 ip = socket.gethostbyname(hostname)
288 except socket.error:
289 # Probably name lookup wasn't set up right; skip this test
290 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000291 self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000292 try:
293 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
294 except socket.error:
295 # Probably a similar problem as above; skip this test
296 return
Brett Cannon01668a12005-03-11 00:04:17 +0000297 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000298 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000299 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000300 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000301
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000302 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000303 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000304 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000305 try:
306 # On some versions, this loses a reference
307 orig = sys.getrefcount(__name__)
308 socket.getnameinfo(__name__,0)
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +0000309 except TypeError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000310 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000311 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000312
Guido van Rossum24e4af82002-06-12 19:18:08 +0000313 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000314 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000315 try:
316 # On some versions, this crashes the interpreter.
317 socket.getnameinfo(('x', 0, 0, 0), 0)
318 except socket.error:
319 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000320
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000321 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000322 # This just checks that htons etc. are their own inverse,
323 # when looking at the lower 16 or 32 bits.
324 sizes = {socket.htonl: 32, socket.ntohl: 32,
325 socket.htons: 16, socket.ntohs: 16}
326 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000327 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000328 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
329 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000330
Guido van Rossuma2627af2002-09-14 00:58:46 +0000331 swapped = func(mask)
332 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000333 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000334
Guido van Rossum018919a2007-01-15 00:07:32 +0000335 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000336 good_values = [ 1, 2, 3, 1, 2, 3 ]
337 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000338 for k in good_values:
339 socket.ntohl(k)
340 socket.ntohs(k)
341 socket.htonl(k)
342 socket.htons(k)
343 for k in bad_values:
344 self.assertRaises(OverflowError, socket.ntohl, k)
345 self.assertRaises(OverflowError, socket.ntohs, k)
346 self.assertRaises(OverflowError, socket.htonl, k)
347 self.assertRaises(OverflowError, socket.htons, k)
348
Barry Warsaw11b91a02004-06-28 00:50:43 +0000349 def testGetServBy(self):
350 eq = self.assertEqual
351 # Find one service that exists, then check all the related interfaces.
352 # I've ordered this by protocols that have both a tcp and udp
353 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000354 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000355 'freebsd7', 'freebsd8', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000356 # avoid the 'echo' service on this platform, as there is an
357 # assumption breaking non-standard port/protocol entry
358 services = ('daytime', 'qotd', 'domain')
359 else:
360 services = ('echo', 'daytime', 'domain')
361 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000362 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000363 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000364 break
365 except socket.error:
366 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000367 else:
368 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000369 # Try same call with optional protocol omitted
370 port2 = socket.getservbyname(service)
371 eq(port, port2)
372 # Try udp, but don't barf it it doesn't exist
373 try:
374 udpport = socket.getservbyname(service, 'udp')
375 except socket.error:
376 udpport = None
377 else:
378 eq(udpport, port)
379 # Now make sure the lookup by port returns the same service name
380 eq(socket.getservbyport(port2), service)
381 eq(socket.getservbyport(port, 'tcp'), service)
382 if udpport is not None:
383 eq(socket.getservbyport(udpport, 'udp'), service)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000384 # Make sure getservbyport does not accept out of range ports.
385 self.assertRaises(OverflowError, socket.getservbyport, -1)
386 self.assertRaises(OverflowError, socket.getservbyport, 65536)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000387
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000388 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000389 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000390 # The default timeout should initially be None
391 self.assertEqual(socket.getdefaulttimeout(), None)
392 s = socket.socket()
393 self.assertEqual(s.gettimeout(), None)
394 s.close()
395
396 # Set the default timeout to 10, and see if it propagates
397 socket.setdefaulttimeout(10)
398 self.assertEqual(socket.getdefaulttimeout(), 10)
399 s = socket.socket()
400 self.assertEqual(s.gettimeout(), 10)
401 s.close()
402
403 # Reset the default timeout to None, and see if it propagates
404 socket.setdefaulttimeout(None)
405 self.assertEqual(socket.getdefaulttimeout(), None)
406 s = socket.socket()
407 self.assertEqual(s.gettimeout(), None)
408 s.close()
409
410 # Check that setting it to an invalid value raises ValueError
411 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
412
413 # Check that setting it to an invalid type raises TypeError
414 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
415
Benjamin Petersonf91df042009-02-13 02:50:59 +0000416 def testIPv4_inet_aton_fourbytes(self):
417 if not hasattr(socket, 'inet_aton'):
418 return # No inet_aton, nothing to check
419 # Test that issue1008086 and issue767150 are fixed.
420 # It must return 4 bytes.
421 self.assertEquals(b'\x00'*4, socket.inet_aton('0.0.0.0'))
422 self.assertEquals(b'\xff'*4, socket.inet_aton('255.255.255.255'))
423
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000424 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000425 if not hasattr(socket, 'inet_pton'):
426 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000427 from socket import inet_aton as f, inet_pton, AF_INET
428 g = lambda a: inet_pton(AF_INET, a)
429
Guido van Rossumb5b22702007-05-18 18:55:53 +0000430 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
431 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
432 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
433 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
434 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000435
Guido van Rossumb5b22702007-05-18 18:55:53 +0000436 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
437 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
438 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
439 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000440
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000441 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000442 if not hasattr(socket, 'inet_pton'):
443 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000444 try:
445 from socket import inet_pton, AF_INET6, has_ipv6
446 if not has_ipv6:
447 return
448 except ImportError:
449 return
450 f = lambda a: inet_pton(AF_INET6, a)
451
Guido van Rossum540d9872007-08-17 03:51:09 +0000452 self.assertEquals(b'\x00' * 16, f('::'))
453 self.assertEquals(b'\x00' * 16, f('0::0'))
454 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000455 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000456 b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000457 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
458 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000459
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000460 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000461 if not hasattr(socket, 'inet_ntop'):
462 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000463 from socket import inet_ntoa as f, inet_ntop, AF_INET
464 g = lambda a: inet_ntop(AF_INET, a)
465
Guido van Rossumb5b22702007-05-18 18:55:53 +0000466 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
467 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
468 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
469 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000470
Guido van Rossumb5b22702007-05-18 18:55:53 +0000471 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
472 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
473 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000474
475 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000476 if not hasattr(socket, 'inet_ntop'):
477 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000478 try:
479 from socket import inet_ntop, AF_INET6, has_ipv6
480 if not has_ipv6:
481 return
482 except ImportError:
483 return
484 f = lambda a: inet_ntop(AF_INET6, a)
485
Guido van Rossum540d9872007-08-17 03:51:09 +0000486 self.assertEquals('::', f(b'\x00' * 16))
487 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000488 self.assertEquals(
489 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000490 f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000491 )
492
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000493 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000494
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000495 def _get_unused_port(self, bind_address='0.0.0.0'):
496 """Use a temporary socket to elicit an unused ephemeral port.
Christian Heimes5e696852008-04-09 08:37:03 +0000497
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000498 Args:
499 bind_address: Hostname or IP address to search for a port on.
500
501 Returns: A most likely to be unused port.
502 """
503 tempsock = socket.socket()
504 tempsock.bind((bind_address, 0))
505 host, port = tempsock.getsockname()
506 tempsock.close()
507 return port
508
509 def testSockName(self):
510 # Testing getsockname()
511 port = self._get_unused_port()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000512 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Christian Heimes5e696852008-04-09 08:37:03 +0000513 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000514 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000515 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
516 # it reasonable to get the host's addr in addition to 0.0.0.0.
517 # At least for eCos. This is required for the S/390 to pass.
518 my_ip_addr = socket.gethostbyname(socket.gethostname())
Georg Brandlab91fde2009-08-13 08:51:18 +0000519 self.assertTrue(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +0000520 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000521
522 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000523 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000524 # We know a socket should start without reuse==0
525 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
526 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000527 self.assertFalse(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000528
529 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000530 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000531 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
532 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
533 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000534 self.assertFalse(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000535
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000536 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000537 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000538 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
539 sock.settimeout(1)
540 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000541 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000542
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000543 def testNewAttributes(self):
544 # testing .family, .type and .protocol
545 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
546 self.assertEqual(sock.family, socket.AF_INET)
547 self.assertEqual(sock.type, socket.SOCK_STREAM)
548 self.assertEqual(sock.proto, 0)
549 sock.close()
550
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000551 def test_getsockaddrarg(self):
552 host = '0.0.0.0'
553 port = self._get_unused_port(bind_address=host)
554 big_port = port + 65536
555 neg_port = port - 65536
556 sock = socket.socket()
557 try:
558 self.assertRaises(OverflowError, sock.bind, (host, big_port))
559 self.assertRaises(OverflowError, sock.bind, (host, neg_port))
560 sock.bind((host, port))
561 finally:
562 sock.close()
563
Christian Heimesfaf2f632008-01-06 16:59:19 +0000564 def test_sock_ioctl(self):
565 if os.name != "nt":
566 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000567 self.assertTrue(hasattr(socket.socket, 'ioctl'))
568 self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
569 self.assertTrue(hasattr(socket, 'RCVALL_ON'))
570 self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
Christian Heimesfaf2f632008-01-06 16:59:19 +0000571
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000572 def testGetaddrinfo(self):
573 try:
574 socket.getaddrinfo('localhost', 80)
575 except socket.gaierror as err:
576 if err.errno == socket.EAI_SERVICE:
577 # see http://bugs.python.org/issue1282647
578 self.skipTest("buggy libc version")
579 raise
580 # len of every sequence is supposed to be == 5
581 for info in socket.getaddrinfo(HOST, None):
582 self.assertEqual(len(info), 5)
583 # host can be a domain name, a string representation of an
584 # IPv4/v6 address or None
585 socket.getaddrinfo('localhost', 80)
586 socket.getaddrinfo('127.0.0.1', 80)
587 socket.getaddrinfo(None, 80)
588 if SUPPORTS_IPV6:
589 socket.getaddrinfo('::1', 80)
590 # port can be a string service name such as "http", a numeric
591 # port number or None
592 socket.getaddrinfo(HOST, "http")
593 socket.getaddrinfo(HOST, 80)
594 socket.getaddrinfo(HOST, None)
595 # test family and socktype filters
596 infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
597 for family, _, _, _, _ in infos:
598 self.assertEqual(family, socket.AF_INET)
599 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
600 for _, socktype, _, _, _ in infos:
601 self.assertEqual(socktype, socket.SOCK_STREAM)
602 # test proto and flags arguments
Giampaolo Rodolà5b37ce62010-08-16 05:09:31 +0000603 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000604 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
605 # a server willing to support both IPv4 and IPv6 will
606 # usually do this
607 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
608 socket.AI_PASSIVE)
609
Christian Heimesfaf2f632008-01-06 16:59:19 +0000610
Antoine Pitrou08ae02f2010-09-27 18:14:43 +0000611 def check_sendall_interrupted(self, with_timeout):
612 # socketpair() is not stricly required, but it makes things easier.
613 if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
614 self.skipTest("signal.alarm and socket.socketpair required for this test")
615 # Our signal handlers clobber the C errno by calling a math function
616 # with an invalid domain value.
617 def ok_handler(*args):
618 self.assertRaises(ValueError, math.acosh, 0)
619 def raising_handler(*args):
620 self.assertRaises(ValueError, math.acosh, 0)
621 1 // 0
622 c, s = socket.socketpair()
623 old_alarm = signal.signal(signal.SIGALRM, raising_handler)
624 try:
625 if with_timeout:
626 # Just above the one second minimum for signal.alarm
627 c.settimeout(1.5)
628 with self.assertRaises(ZeroDivisionError):
629 signal.alarm(1)
630 c.sendall(b"x" * (1024**2))
631 if with_timeout:
632 signal.signal(signal.SIGALRM, ok_handler)
633 signal.alarm(1)
634 self.assertRaises(socket.timeout, c.sendall, b"x" * (1024**2))
635 finally:
636 signal.signal(signal.SIGALRM, old_alarm)
637 c.close()
638 s.close()
639
640 def test_sendall_interrupted(self):
641 self.check_sendall_interrupted(False)
642
643 def test_sendall_interrupted_with_timeout(self):
644 self.check_sendall_interrupted(True)
645
646
Guido van Rossum24e4af82002-06-12 19:18:08 +0000647class BasicTCPTest(SocketConnectedTest):
648
649 def __init__(self, methodName='runTest'):
650 SocketConnectedTest.__init__(self, methodName=methodName)
651
652 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000653 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000654 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000655 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000656
657 def _testRecv(self):
658 self.serv_conn.send(MSG)
659
660 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000661 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000662 seg1 = self.cli_conn.recv(len(MSG) - 3)
663 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000664 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000665 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000666
667 def _testOverFlowRecv(self):
668 self.serv_conn.send(MSG)
669
670 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000671 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000672 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000673 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000674
675 def _testRecvFrom(self):
676 self.serv_conn.send(MSG)
677
678 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000679 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000680 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
681 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000682 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000683 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000684
685 def _testOverFlowRecvFrom(self):
686 self.serv_conn.send(MSG)
687
688 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000689 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000690 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000691 while 1:
692 read = self.cli_conn.recv(1024)
693 if not read:
694 break
Guido van Rossume531e292002-08-08 20:28:34 +0000695 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000696 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000697
698 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000699 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000700 self.serv_conn.sendall(big_chunk)
701
702 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000703 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000704 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000705 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000706 fd = self.cli_conn.fileno()
707 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
708 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000709 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000710
711 def _testFromFd(self):
712 self.serv_conn.send(MSG)
713
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000714 def testDup(self):
715 # Testing dup()
716 sock = self.cli_conn.dup()
717 msg = sock.recv(1024)
718 self.assertEqual(msg, MSG)
719
720 def _testDup(self):
721 self.serv_conn.send(MSG)
722
Guido van Rossum24e4af82002-06-12 19:18:08 +0000723 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000724 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000725 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000726 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +0000727 # wait for _testShutdown to finish: on OS X, when the server
728 # closes the connection the client also becomes disconnected,
729 # and the client's shutdown call will fail. (Issue #4397.)
730 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000731
732 def _testShutdown(self):
733 self.serv_conn.send(MSG)
734 self.serv_conn.shutdown(2)
735
736class BasicUDPTest(ThreadedUDPSocketTest):
737
738 def __init__(self, methodName='runTest'):
739 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
740
741 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000742 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000743 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000744 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000745
746 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000747 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000748
Guido van Rossum1c938012002-06-12 21:17:20 +0000749 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000750 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000751 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000752 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000753
Guido van Rossum1c938012002-06-12 21:17:20 +0000754 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000755 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000756
Guido van Rossumd8faa362007-04-27 19:54:29 +0000757 def testRecvFromNegative(self):
758 # Negative lengths passed to recvfrom should give ValueError.
759 self.assertRaises(ValueError, self.serv.recvfrom, -1)
760
761 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000762 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000764class TCPCloserTest(ThreadedTCPSocketTest):
765
766 def testClose(self):
767 conn, addr = self.serv.accept()
768 conn.close()
769
770 sd = self.cli
771 read, write, err = select.select([sd], [], [], 1.0)
772 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000773 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000774
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000775 # Calling close() many times should be safe.
776 conn.close()
777 conn.close()
778
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000779 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000780 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000781 time.sleep(1.0)
782
Dave Cole331708b2004-08-09 04:51:41 +0000783class BasicSocketPairTest(SocketPairTest):
784
785 def __init__(self, methodName='runTest'):
786 SocketPairTest.__init__(self, methodName=methodName)
787
788 def testRecv(self):
789 msg = self.serv.recv(1024)
790 self.assertEqual(msg, MSG)
791
792 def _testRecv(self):
793 self.cli.send(MSG)
794
795 def testSend(self):
796 self.serv.send(MSG)
797
798 def _testSend(self):
799 msg = self.cli.recv(1024)
800 self.assertEqual(msg, MSG)
801
Guido van Rossum24e4af82002-06-12 19:18:08 +0000802class NonBlockingTCPTests(ThreadedTCPSocketTest):
803
804 def __init__(self, methodName='runTest'):
805 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
806
807 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000808 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000809 self.serv.setblocking(0)
810 start = time.time()
811 try:
812 self.serv.accept()
813 except socket.error:
814 pass
815 end = time.time()
Georg Brandlab91fde2009-08-13 08:51:18 +0000816 self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000817
818 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000819 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000820
Guido van Rossum24e4af82002-06-12 19:18:08 +0000821 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000822 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000823 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000824 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000825 conn, addr = self.serv.accept()
826 except socket.error:
827 pass
828 else:
829 self.fail("Error trying to do non-blocking accept.")
830 read, write, err = select.select([self.serv], [], [])
831 if self.serv in read:
832 conn, addr = self.serv.accept()
833 else:
834 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000835
Guido van Rossum24e4af82002-06-12 19:18:08 +0000836 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000837 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +0000838 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000839
840 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000841 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000842 conn, addr = self.serv.accept()
843
844 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000845 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +0000846 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000847
848 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000849 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000850 conn, addr = self.serv.accept()
851 conn.setblocking(0)
852 try:
853 msg = conn.recv(len(MSG))
854 except socket.error:
855 pass
856 else:
857 self.fail("Error trying to do non-blocking recv.")
858 read, write, err = select.select([conn], [], [])
859 if conn in read:
860 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000861 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000862 else:
863 self.fail("Error during select call to non-blocking socket.")
864
865 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000866 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000867 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000868 self.cli.send(MSG)
869
870class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000871 """Unit tests for the object returned by socket.makefile()
872
873 self.serv_file is the io object returned by makefile() on
874 the client connection. You can read from this file to
875 get output from the server.
876
877 self.cli_file is the io object returned by makefile() on the
878 server connection. You can write to this file to send output
879 to the client.
880 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000881
Guido van Rossume9f66142002-08-07 15:46:19 +0000882 bufsize = -1 # Use default buffer size
883
Guido van Rossum24e4af82002-06-12 19:18:08 +0000884 def __init__(self, methodName='runTest'):
885 SocketConnectedTest.__init__(self, methodName=methodName)
886
887 def setUp(self):
888 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000889 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000890
891 def tearDown(self):
892 self.serv_file.close()
Georg Brandlab91fde2009-08-13 08:51:18 +0000893 self.assertTrue(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000894 self.serv_file = None
895 SocketConnectedTest.tearDown(self)
896
897 def clientSetUp(self):
898 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000899 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000900
901 def clientTearDown(self):
902 self.cli_file.close()
Georg Brandlab91fde2009-08-13 08:51:18 +0000903 self.assertTrue(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000904 self.cli_file = None
905 SocketConnectedTest.clientTearDown(self)
906
907 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000908 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000909 first_seg = self.serv_file.read(len(MSG)-3)
910 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000911 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000912 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000913
914 def _testSmallRead(self):
915 self.cli_file.write(MSG)
916 self.cli_file.flush()
917
Guido van Rossum8c943832002-08-08 01:00:28 +0000918 def testFullRead(self):
919 # read until EOF
920 msg = self.serv_file.read()
921 self.assertEqual(msg, MSG)
922
923 def _testFullRead(self):
924 self.cli_file.write(MSG)
925 self.cli_file.close()
926
Guido van Rossum24e4af82002-06-12 19:18:08 +0000927 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000928 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000929 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000930 while 1:
931 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000932 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000933 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000934 buf += char
935 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000936
937 def _testUnbufferedRead(self):
938 self.cli_file.write(MSG)
939 self.cli_file.flush()
940
941 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000942 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000943 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000944 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000945
946 def _testReadline(self):
947 self.cli_file.write(MSG)
948 self.cli_file.flush()
949
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000950 def testCloseAfterMakefile(self):
951 # The file returned by makefile should keep the socket open.
952 self.cli_conn.close()
953 # read until EOF
954 msg = self.serv_file.read()
955 self.assertEqual(msg, MSG)
956
957 def _testCloseAfterMakefile(self):
958 self.cli_file.write(MSG)
959 self.cli_file.flush()
960
961 def testMakefileAfterMakefileClose(self):
962 self.serv_file.close()
963 msg = self.cli_conn.recv(len(MSG))
964 self.assertEqual(msg, MSG)
965
966 def _testMakefileAfterMakefileClose(self):
967 self.cli_file.write(MSG)
968 self.cli_file.flush()
969
Tim Peters116d83c2004-03-28 02:20:45 +0000970 def testClosedAttr(self):
Georg Brandlab91fde2009-08-13 08:51:18 +0000971 self.assertTrue(not self.serv_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +0000972
973 def _testClosedAttr(self):
Georg Brandlab91fde2009-08-13 08:51:18 +0000974 self.assertTrue(not self.cli_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +0000975
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000976 def testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +0000977 self.assertEqual(self.serv_file.mode, 'rb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000978 self.assertEqual(self.serv_file.name, self.cli_conn.fileno())
979
980 def _testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +0000981 self.assertEqual(self.cli_file.mode, 'wb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000982 self.assertEqual(self.cli_file.name, self.serv_conn.fileno())
983
Gregory P. Smithde3369f2009-01-12 04:50:11 +0000984 def testRealClose(self):
985 self.serv_file.close()
986 self.assertRaises(ValueError, self.serv_file.fileno)
987 self.cli_conn.close()
988 self.assertRaises(socket.error, self.cli_conn.getsockname)
989
990 def _testRealClose(self):
991 pass
992
993
Guido van Rossume9f66142002-08-07 15:46:19 +0000994class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
995
996 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000997
Guido van Rossume9f66142002-08-07 15:46:19 +0000998 In this case (and in this case only), it should be possible to
999 create a file object, read a line from it, create another file
1000 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +00001001 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +00001002 when reading multiple requests from the same socket."""
1003
1004 bufsize = 0 # Use unbuffered mode
1005
1006 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001007 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +00001008 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001009 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +00001010 self.serv_file = self.cli_conn.makefile('rb', 0)
1011 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001012 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +00001013
1014 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001015 self.cli_file.write(b"A. " + MSG)
1016 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +00001017 self.cli_file.flush()
1018
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001019 def testMakefileClose(self):
1020 # The file returned by makefile should keep the socket open...
1021 self.cli_conn.close()
1022 msg = self.cli_conn.recv(1024)
1023 self.assertEqual(msg, MSG)
1024 # ...until the file is itself closed
1025 self.serv_file.close()
1026 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
1027
1028 def _testMakefileClose(self):
1029 self.cli_file.write(MSG)
1030 self.cli_file.flush()
1031
1032 def testMakefileCloseSocketDestroy(self):
1033 refcount_before = sys.getrefcount(self.cli_conn)
1034 self.serv_file.close()
1035 refcount_after = sys.getrefcount(self.cli_conn)
1036 self.assertEqual(refcount_before - 1, refcount_after)
1037
1038 def _testMakefileCloseSocketDestroy(self):
1039 pass
1040
1041
Guido van Rossum8c943832002-08-08 01:00:28 +00001042class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1043
1044 bufsize = 1 # Default-buffered for reading; line-buffered for writing
1045
1046
1047class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1048
1049 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +00001050
Thomas Woutersb2137042007-02-01 18:02:27 +00001051
Guido van Rossumd8faa362007-04-27 19:54:29 +00001052class NetworkConnectionTest(object):
1053 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001054
Guido van Rossumd8faa362007-04-27 19:54:29 +00001055 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001056 # We're inherited below by BasicTCPTest2, which also inherits
1057 # BasicTCPTest, which defines self.port referenced below.
1058 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001059 self.serv_conn = self.cli
1060
1061class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
1062 """Tests that NetworkConnection does not break existing TCP functionality.
1063 """
1064
1065class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001066
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001067 class MockSocket(socket.socket):
1068 def connect(self, *args):
1069 raise socket.timeout('timed out')
1070
1071 @contextlib.contextmanager
1072 def mocked_socket_module(self):
1073 """Return a socket which times out on connect"""
1074 old_socket = socket.socket
1075 socket.socket = self.MockSocket
1076 try:
1077 yield
1078 finally:
1079 socket.socket = old_socket
1080
1081 def test_connect(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001082 port = support.find_unused_port()
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001083 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1084 try:
1085 cli.connect((HOST, port))
1086 except socket.error as err:
1087 self.assertEqual(err.errno, errno.ECONNREFUSED)
1088 else:
1089 self.fail("socket.error not raised")
1090
1091 def test_create_connection(self):
1092 # Issue #9792: errors raised by create_connection() should have
1093 # a proper errno attribute.
1094 port = support.find_unused_port()
1095 try:
1096 socket.create_connection((HOST, port))
1097 except socket.error as err:
1098 self.assertEqual(err.errno, errno.ECONNREFUSED)
1099 else:
1100 self.fail("socket.error not raised")
1101
1102 def test_create_connection_timeout(self):
1103 # Issue #9792: create_connection() should not recast timeout errors
1104 # as generic socket errors.
1105 with self.mocked_socket_module():
1106 with self.assertRaises(socket.timeout):
1107 socket.create_connection((HOST, 1234))
1108
Guido van Rossumd8faa362007-04-27 19:54:29 +00001109
1110class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
1111
1112 def __init__(self, methodName='runTest'):
1113 SocketTCPTest.__init__(self, methodName=methodName)
1114 ThreadableTest.__init__(self)
1115
1116 def clientSetUp(self):
1117 pass
1118
1119 def clientTearDown(self):
1120 self.cli.close()
1121 self.cli = None
1122 ThreadableTest.clientTearDown(self)
1123
1124 def _justAccept(self):
1125 conn, addr = self.serv.accept()
1126
1127 testFamily = _justAccept
1128 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001129 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001130 self.assertEqual(self.cli.family, 2)
1131
1132 testTimeoutDefault = _justAccept
1133 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001134 # passing no explicit timeout uses socket's global default
Georg Brandlab91fde2009-08-13 08:51:18 +00001135 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001136 socket.setdefaulttimeout(42)
1137 try:
1138 self.cli = socket.create_connection((HOST, self.port))
1139 finally:
1140 socket.setdefaulttimeout(None)
1141 self.assertEquals(self.cli.gettimeout(), 42)
1142
1143 testTimeoutNone = _justAccept
1144 def _testTimeoutNone(self):
1145 # None timeout means the same as sock.settimeout(None)
Georg Brandlab91fde2009-08-13 08:51:18 +00001146 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001147 socket.setdefaulttimeout(30)
1148 try:
1149 self.cli = socket.create_connection((HOST, self.port), timeout=None)
1150 finally:
1151 socket.setdefaulttimeout(None)
1152 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001153
1154 testTimeoutValueNamed = _justAccept
1155 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001156 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001157 self.assertEqual(self.cli.gettimeout(), 30)
1158
1159 testTimeoutValueNonamed = _justAccept
1160 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001161 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001162 self.assertEqual(self.cli.gettimeout(), 30)
1163
Guido van Rossumd8faa362007-04-27 19:54:29 +00001164class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1165
1166 def __init__(self, methodName='runTest'):
1167 SocketTCPTest.__init__(self, methodName=methodName)
1168 ThreadableTest.__init__(self)
1169
1170 def clientSetUp(self):
1171 pass
1172
1173 def clientTearDown(self):
1174 self.cli.close()
1175 self.cli = None
1176 ThreadableTest.clientTearDown(self)
1177
1178 def testInsideTimeout(self):
1179 conn, addr = self.serv.accept()
1180 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001181 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001182 testOutsideTimeout = testInsideTimeout
1183
1184 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001185 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001186 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001187 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001188
1189 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001190 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Georg Brandlab91fde2009-08-13 08:51:18 +00001191 self.assertRaises(socket.timeout, lambda: sock.recv(5))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001192
1193
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001194class TCPTimeoutTest(SocketTCPTest):
1195
1196 def testTCPTimeout(self):
1197 def raise_timeout(*args, **kwargs):
1198 self.serv.settimeout(1.0)
1199 self.serv.accept()
Georg Brandlab91fde2009-08-13 08:51:18 +00001200 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001201 "Error generating a timeout exception (TCP)")
1202
1203 def testTimeoutZero(self):
1204 ok = False
1205 try:
1206 self.serv.settimeout(0.0)
1207 foo = self.serv.accept()
1208 except socket.timeout:
1209 self.fail("caught timeout instead of error (TCP)")
1210 except socket.error:
1211 ok = True
1212 except:
1213 self.fail("caught unexpected exception (TCP)")
1214 if not ok:
1215 self.fail("accept() returned success when we did not expect it")
1216
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001217 def testInterruptedTimeout(self):
1218 # XXX I don't know how to do this test on MSWindows or any other
1219 # plaform that doesn't support signal.alarm() or os.kill(), though
1220 # the bug should have existed on all platforms.
1221 if not hasattr(signal, "alarm"):
1222 return # can only test on *nix
1223 self.serv.settimeout(5.0) # must be longer than alarm
1224 class Alarm(Exception):
1225 pass
1226 def alarm_handler(signal, frame):
1227 raise Alarm
1228 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1229 try:
1230 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1231 try:
1232 foo = self.serv.accept()
1233 except socket.timeout:
1234 self.fail("caught timeout instead of Alarm")
1235 except Alarm:
1236 pass
1237 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001238 self.fail("caught other exception instead of Alarm:"
1239 " %s(%s):\n%s" %
1240 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001241 else:
1242 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001243 finally:
1244 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001245 except Alarm:
1246 self.fail("got Alarm in wrong place")
1247 finally:
1248 # no alarm can be pending. Safe to restore old handler.
1249 signal.signal(signal.SIGALRM, old_alarm)
1250
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001251class UDPTimeoutTest(SocketTCPTest):
1252
1253 def testUDPTimeout(self):
1254 def raise_timeout(*args, **kwargs):
1255 self.serv.settimeout(1.0)
1256 self.serv.recv(1024)
Georg Brandlab91fde2009-08-13 08:51:18 +00001257 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001258 "Error generating a timeout exception (UDP)")
1259
1260 def testTimeoutZero(self):
1261 ok = False
1262 try:
1263 self.serv.settimeout(0.0)
1264 foo = self.serv.recv(1024)
1265 except socket.timeout:
1266 self.fail("caught timeout instead of error (UDP)")
1267 except socket.error:
1268 ok = True
1269 except:
1270 self.fail("caught unexpected exception (UDP)")
1271 if not ok:
1272 self.fail("recv() returned success when we did not expect it")
1273
1274class TestExceptions(unittest.TestCase):
1275
1276 def testExceptionTree(self):
Georg Brandlab91fde2009-08-13 08:51:18 +00001277 self.assertTrue(issubclass(socket.error, Exception))
1278 self.assertTrue(issubclass(socket.herror, socket.error))
1279 self.assertTrue(issubclass(socket.gaierror, socket.error))
1280 self.assertTrue(issubclass(socket.timeout, socket.error))
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001281
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001282class TestLinuxAbstractNamespace(unittest.TestCase):
1283
1284 UNIX_PATH_MAX = 108
1285
1286 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001287 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001288 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1289 s1.bind(address)
1290 s1.listen(1)
1291 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1292 s2.connect(s1.getsockname())
1293 s1.accept()
1294 self.assertEqual(s1.getsockname(), address)
1295 self.assertEqual(s2.getpeername(), address)
1296
1297 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001298 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001299 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1300 s.bind(address)
1301 self.assertEqual(s.getsockname(), address)
1302
1303 def testNameOverflow(self):
1304 address = "\x00" + "h" * self.UNIX_PATH_MAX
1305 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1306 self.assertRaises(socket.error, s.bind, address)
1307
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001308
Thomas Wouters477c8d52006-05-27 19:21:47 +00001309class BufferIOTest(SocketConnectedTest):
1310 """
1311 Test the buffer versions of socket.recv() and socket.send().
1312 """
1313 def __init__(self, methodName='runTest'):
1314 SocketConnectedTest.__init__(self, methodName=methodName)
1315
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001316 def testRecvInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001317 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001318 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001319 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001320 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001321 self.assertEqual(msg, MSG)
1322
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001323 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001324 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001325 self.serv_conn.send(buf)
1326
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001327 def testRecvFromInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001328 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001329 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001330 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001331 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001332 self.assertEqual(msg, MSG)
1333
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001334 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001335 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001336 self.serv_conn.send(buf)
1337
Christian Heimes043d6f62008-01-07 17:19:16 +00001338
1339TIPC_STYPE = 2000
1340TIPC_LOWER = 200
1341TIPC_UPPER = 210
1342
1343def isTipcAvailable():
1344 """Check if the TIPC module is loaded
1345
1346 The TIPC module is not loaded automatically on Ubuntu and probably
1347 other Linux distros.
1348 """
1349 if not hasattr(socket, "AF_TIPC"):
1350 return False
1351 if not os.path.isfile("/proc/modules"):
1352 return False
1353 with open("/proc/modules") as f:
1354 for line in f:
1355 if line.startswith("tipc "):
1356 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001357 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001358 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1359 return False
1360
1361class TIPCTest (unittest.TestCase):
1362 def testRDM(self):
1363 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1364 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1365
1366 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1367 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1368 TIPC_LOWER, TIPC_UPPER)
1369 srv.bind(srvaddr)
1370
1371 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1372 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1373 cli.sendto(MSG, sendaddr)
1374
1375 msg, recvaddr = srv.recvfrom(1024)
1376
1377 self.assertEqual(cli.getsockname(), recvaddr)
1378 self.assertEqual(msg, MSG)
1379
1380
1381class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1382 def __init__(self, methodName = 'runTest'):
1383 unittest.TestCase.__init__(self, methodName = methodName)
1384 ThreadableTest.__init__(self)
1385
1386 def setUp(self):
1387 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1388 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1389 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1390 TIPC_LOWER, TIPC_UPPER)
1391 self.srv.bind(srvaddr)
1392 self.srv.listen(5)
1393 self.serverExplicitReady()
1394 self.conn, self.connaddr = self.srv.accept()
1395
1396 def clientSetUp(self):
1397 # The is a hittable race between serverExplicitReady() and the
1398 # accept() call; sleep a little while to avoid it, otherwise
1399 # we could get an exception
1400 time.sleep(0.1)
1401 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1402 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1403 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1404 self.cli.connect(addr)
1405 self.cliaddr = self.cli.getsockname()
1406
1407 def testStream(self):
1408 msg = self.conn.recv(1024)
1409 self.assertEqual(msg, MSG)
1410 self.assertEqual(self.cliaddr, self.connaddr)
1411
1412 def _testStream(self):
1413 self.cli.send(MSG)
1414 self.cli.close()
1415
1416
Guido van Rossumb995eb72002-07-31 16:08:40 +00001417def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001418 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001419 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001420 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001421 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001422
1423 tests.extend([
1424 NonBlockingTCPTests,
1425 FileObjectClassTestCase,
1426 UnbufferedFileObjectClassTestCase,
1427 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001428 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001429 NetworkConnectionNoServer,
1430 NetworkConnectionAttributesTest,
1431 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001432 ])
Dave Cole331708b2004-08-09 04:51:41 +00001433 if hasattr(socket, "socketpair"):
1434 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001435 if sys.platform == 'linux2':
1436 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001437 if isTipcAvailable():
1438 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001439 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001440
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001441 thread_info = support.threading_setup()
1442 support.run_unittest(*tests)
1443 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001444
1445if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001446 test_main()