blob: 2415d539abcd5148ba10ce0537d369b2ecfc1ffb [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
Barry Warsawcf3d4b51997-01-03 20:03:32 +000020
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +000021def try_address(host, port=0, family=socket.AF_INET):
22 """Try to bind a socket on the given host:port and return True
23 if that has been possible."""
24 try:
25 sock = socket.socket(family, socket.SOCK_STREAM)
26 sock.bind((host, port))
27 except (socket.error, socket.gaierror):
28 return False
29 else:
30 sock.close()
31 return True
32
Benjamin Petersonee8712c2008-05-20 21:35:26 +000033HOST = support.HOST
Guido van Rossum7d0a8262007-05-21 23:13:11 +000034MSG = b'Michael Gilfix was here\n'
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +000035SUPPORTS_IPV6 = socket.has_ipv6 and try_address('::1', family=socket.AF_INET6)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000036
Guido van Rossum24e4af82002-06-12 19:18:08 +000037class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000038
Guido van Rossum24e4af82002-06-12 19:18:08 +000039 def setUp(self):
40 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000041 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000042 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000043
Guido van Rossum24e4af82002-06-12 19:18:08 +000044 def tearDown(self):
45 self.serv.close()
46 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000047
Guido van Rossum24e4af82002-06-12 19:18:08 +000048class SocketUDPTest(unittest.TestCase):
49
50 def setUp(self):
51 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000052 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000053
54 def tearDown(self):
55 self.serv.close()
56 self.serv = None
57
58class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000059 """Threadable Test class
60
61 The ThreadableTest class makes it easy to create a threaded
62 client/server pair from an existing unit test. To create a
63 new threaded class from an existing unit test, use multiple
64 inheritance:
65
66 class NewClass (OldClass, ThreadableTest):
67 pass
68
69 This class defines two new fixture functions with obvious
70 purposes for overriding:
71
72 clientSetUp ()
73 clientTearDown ()
74
75 Any new test functions within the class must then define
76 tests in pairs, where the test name is preceeded with a
77 '_' to indicate the client portion of the test. Ex:
78
79 def testFoo(self):
80 # Server portion
81
82 def _testFoo(self):
83 # Client portion
84
85 Any exceptions raised by the clients during their tests
86 are caught and transferred to the main thread to alert
87 the testing framework.
88
89 Note, the server setup function cannot call any blocking
90 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +000091 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000092 the blocking call (such as in setting up a client/server
93 connection and performing the accept() in setUp().
94 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000095
96 def __init__(self):
97 # Swap the true setup function
98 self.__setUp = self.setUp
99 self.__tearDown = self.tearDown
100 self.setUp = self._setUp
101 self.tearDown = self._tearDown
102
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000103 def serverExplicitReady(self):
104 """This method allows the server to explicitly indicate that
105 it wants the client thread to proceed. This is useful if the
106 server is about to execute a blocking routine that is
107 dependent upon the client thread during its setup routine."""
108 self.server_ready.set()
109
Guido van Rossum24e4af82002-06-12 19:18:08 +0000110 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000111 self.server_ready = threading.Event()
112 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000113 self.done = threading.Event()
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000114 self.queue = queue.Queue(1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000115
116 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000117 methodname = self.id()
118 i = methodname.rfind('.')
119 methodname = methodname[i+1:]
120 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000121 self.client_thread = thread.start_new_thread(
122 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000123
124 self.__setUp()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000125 if not self.server_ready.is_set():
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000126 self.server_ready.set()
127 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000128
129 def _tearDown(self):
130 self.__tearDown()
131 self.done.wait()
132
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000133 if self.queue.qsize():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000134 msg = self.queue.get()
135 self.fail(msg)
136
137 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000138 self.server_ready.wait()
139 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000140 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000141 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000142 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000143 try:
144 test_func()
Guido van Rossumb940e112007-01-10 16:19:56 +0000145 except Exception as strerror:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000146 self.queue.put(strerror)
147 self.clientTearDown()
148
149 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000150 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000151
152 def clientTearDown(self):
153 self.done.set()
154 thread.exit()
155
156class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
157
158 def __init__(self, methodName='runTest'):
159 SocketTCPTest.__init__(self, methodName=methodName)
160 ThreadableTest.__init__(self)
161
162 def clientSetUp(self):
163 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
164
165 def clientTearDown(self):
166 self.cli.close()
167 self.cli = None
168 ThreadableTest.clientTearDown(self)
169
170class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
171
172 def __init__(self, methodName='runTest'):
173 SocketUDPTest.__init__(self, methodName=methodName)
174 ThreadableTest.__init__(self)
175
176 def clientSetUp(self):
177 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
178
179class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000180 """Socket tests for client-server connection.
181
182 self.cli_conn is a client socket connected to the server. The
183 setUp() method guarantees that it is connected to the server.
184 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000185
186 def __init__(self, methodName='runTest'):
187 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
188
189 def setUp(self):
190 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000191 # Indicate explicitly we're ready for the client thread to
192 # proceed and then perform the blocking call to accept
193 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000194 conn, addr = self.serv.accept()
195 self.cli_conn = conn
196
197 def tearDown(self):
198 self.cli_conn.close()
199 self.cli_conn = None
200 ThreadedTCPSocketTest.tearDown(self)
201
202 def clientSetUp(self):
203 ThreadedTCPSocketTest.clientSetUp(self)
Christian Heimes5e696852008-04-09 08:37:03 +0000204 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000205 self.serv_conn = self.cli
206
207 def clientTearDown(self):
208 self.serv_conn.close()
209 self.serv_conn = None
210 ThreadedTCPSocketTest.clientTearDown(self)
211
Dave Cole331708b2004-08-09 04:51:41 +0000212class SocketPairTest(unittest.TestCase, ThreadableTest):
213
214 def __init__(self, methodName='runTest'):
215 unittest.TestCase.__init__(self, methodName=methodName)
216 ThreadableTest.__init__(self)
217
218 def setUp(self):
219 self.serv, self.cli = socket.socketpair()
220
221 def tearDown(self):
222 self.serv.close()
223 self.serv = None
224
225 def clientSetUp(self):
226 pass
227
228 def clientTearDown(self):
229 self.cli.close()
230 self.cli = None
231 ThreadableTest.clientTearDown(self)
232
Tim Peters494aaee2004-08-09 18:54:11 +0000233
Guido van Rossum24e4af82002-06-12 19:18:08 +0000234#######################################################################
235## Begin Tests
236
237class GeneralModuleTests(unittest.TestCase):
238
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000239 def test_repr(self):
240 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlab91fde2009-08-13 08:51:18 +0000241 self.assertTrue(repr(s).startswith("<socket.socket object"))
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000242
Raymond Hettinger027bb632004-05-31 03:09:25 +0000243 def test_weakref(self):
244 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
245 p = proxy(s)
246 self.assertEqual(p.fileno(), s.fileno())
247 s.close()
248 s = None
249 try:
250 p.fileno()
251 except ReferenceError:
252 pass
253 else:
254 self.fail('Socket proxy still exists')
255
Guido van Rossum24e4af82002-06-12 19:18:08 +0000256 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000257 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000258 def raise_error(*args, **kwargs):
259 raise socket.error
260 def raise_herror(*args, **kwargs):
261 raise socket.herror
262 def raise_gaierror(*args, **kwargs):
263 raise socket.gaierror
Georg Brandlab91fde2009-08-13 08:51:18 +0000264 self.assertRaises(socket.error, raise_error,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000265 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000266 self.assertRaises(socket.error, raise_herror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000267 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000268 self.assertRaises(socket.error, raise_gaierror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000269 "Error raising socket exception.")
270
271 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000272 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000273 socket.AF_INET
274 socket.SOCK_STREAM
275 socket.SOCK_DGRAM
276 socket.SOCK_RAW
277 socket.SOCK_RDM
278 socket.SOCK_SEQPACKET
279 socket.SOL_SOCKET
280 socket.SO_REUSEADDR
281
Guido van Rossum654c11e2002-06-13 20:24:17 +0000282 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000283 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000284 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000285 try:
286 ip = socket.gethostbyname(hostname)
287 except socket.error:
288 # Probably name lookup wasn't set up right; skip this test
289 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000290 self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000291 try:
292 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
293 except socket.error:
294 # Probably a similar problem as above; skip this test
295 return
Brett Cannon01668a12005-03-11 00:04:17 +0000296 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000297 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000298 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000299 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000300
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000301 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000302 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000303 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000304 try:
305 # On some versions, this loses a reference
306 orig = sys.getrefcount(__name__)
307 socket.getnameinfo(__name__,0)
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +0000308 except TypeError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000309 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000310 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000311
Guido van Rossum24e4af82002-06-12 19:18:08 +0000312 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000313 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000314 try:
315 # On some versions, this crashes the interpreter.
316 socket.getnameinfo(('x', 0, 0, 0), 0)
317 except socket.error:
318 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000319
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000320 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000321 # This just checks that htons etc. are their own inverse,
322 # when looking at the lower 16 or 32 bits.
323 sizes = {socket.htonl: 32, socket.ntohl: 32,
324 socket.htons: 16, socket.ntohs: 16}
325 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000326 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000327 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
328 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000329
Guido van Rossuma2627af2002-09-14 00:58:46 +0000330 swapped = func(mask)
331 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000332 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000333
Guido van Rossum018919a2007-01-15 00:07:32 +0000334 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000335 good_values = [ 1, 2, 3, 1, 2, 3 ]
336 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000337 for k in good_values:
338 socket.ntohl(k)
339 socket.ntohs(k)
340 socket.htonl(k)
341 socket.htons(k)
342 for k in bad_values:
343 self.assertRaises(OverflowError, socket.ntohl, k)
344 self.assertRaises(OverflowError, socket.ntohs, k)
345 self.assertRaises(OverflowError, socket.htonl, k)
346 self.assertRaises(OverflowError, socket.htons, k)
347
Barry Warsaw11b91a02004-06-28 00:50:43 +0000348 def testGetServBy(self):
349 eq = self.assertEqual
350 # Find one service that exists, then check all the related interfaces.
351 # I've ordered this by protocols that have both a tcp and udp
352 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000353 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000354 'freebsd7', 'freebsd8', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000355 # avoid the 'echo' service on this platform, as there is an
356 # assumption breaking non-standard port/protocol entry
357 services = ('daytime', 'qotd', 'domain')
358 else:
359 services = ('echo', 'daytime', 'domain')
360 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000361 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000362 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000363 break
364 except socket.error:
365 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000366 else:
367 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000368 # Try same call with optional protocol omitted
369 port2 = socket.getservbyname(service)
370 eq(port, port2)
371 # Try udp, but don't barf it it doesn't exist
372 try:
373 udpport = socket.getservbyname(service, 'udp')
374 except socket.error:
375 udpport = None
376 else:
377 eq(udpport, port)
378 # Now make sure the lookup by port returns the same service name
379 eq(socket.getservbyport(port2), service)
380 eq(socket.getservbyport(port, 'tcp'), service)
381 if udpport is not None:
382 eq(socket.getservbyport(udpport, 'udp'), service)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000383 # Make sure getservbyport does not accept out of range ports.
384 self.assertRaises(OverflowError, socket.getservbyport, -1)
385 self.assertRaises(OverflowError, socket.getservbyport, 65536)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000386
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000387 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000388 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000389 # The default timeout should initially be None
390 self.assertEqual(socket.getdefaulttimeout(), None)
391 s = socket.socket()
392 self.assertEqual(s.gettimeout(), None)
393 s.close()
394
395 # Set the default timeout to 10, and see if it propagates
396 socket.setdefaulttimeout(10)
397 self.assertEqual(socket.getdefaulttimeout(), 10)
398 s = socket.socket()
399 self.assertEqual(s.gettimeout(), 10)
400 s.close()
401
402 # Reset the default timeout to None, and see if it propagates
403 socket.setdefaulttimeout(None)
404 self.assertEqual(socket.getdefaulttimeout(), None)
405 s = socket.socket()
406 self.assertEqual(s.gettimeout(), None)
407 s.close()
408
409 # Check that setting it to an invalid value raises ValueError
410 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
411
412 # Check that setting it to an invalid type raises TypeError
413 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
414
Benjamin Petersonf91df042009-02-13 02:50:59 +0000415 def testIPv4_inet_aton_fourbytes(self):
416 if not hasattr(socket, 'inet_aton'):
417 return # No inet_aton, nothing to check
418 # Test that issue1008086 and issue767150 are fixed.
419 # It must return 4 bytes.
420 self.assertEquals(b'\x00'*4, socket.inet_aton('0.0.0.0'))
421 self.assertEquals(b'\xff'*4, socket.inet_aton('255.255.255.255'))
422
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000423 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000424 if not hasattr(socket, 'inet_pton'):
425 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000426 from socket import inet_aton as f, inet_pton, AF_INET
427 g = lambda a: inet_pton(AF_INET, a)
428
Guido van Rossumb5b22702007-05-18 18:55:53 +0000429 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
430 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
431 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
432 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
433 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000434
Guido van Rossumb5b22702007-05-18 18:55:53 +0000435 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
436 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
437 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
438 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000439
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000440 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000441 if not hasattr(socket, 'inet_pton'):
442 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000443 try:
444 from socket import inet_pton, AF_INET6, has_ipv6
445 if not has_ipv6:
446 return
447 except ImportError:
448 return
449 f = lambda a: inet_pton(AF_INET6, a)
450
Guido van Rossum540d9872007-08-17 03:51:09 +0000451 self.assertEquals(b'\x00' * 16, f('::'))
452 self.assertEquals(b'\x00' * 16, f('0::0'))
453 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000454 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000455 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 +0000456 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
457 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000458
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000459 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000460 if not hasattr(socket, 'inet_ntop'):
461 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000462 from socket import inet_ntoa as f, inet_ntop, AF_INET
463 g = lambda a: inet_ntop(AF_INET, a)
464
Guido van Rossumb5b22702007-05-18 18:55:53 +0000465 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
466 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
467 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
468 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000469
Guido van Rossumb5b22702007-05-18 18:55:53 +0000470 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
471 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
472 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000473
474 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000475 if not hasattr(socket, 'inet_ntop'):
476 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000477 try:
478 from socket import inet_ntop, AF_INET6, has_ipv6
479 if not has_ipv6:
480 return
481 except ImportError:
482 return
483 f = lambda a: inet_ntop(AF_INET6, a)
484
Guido van Rossum540d9872007-08-17 03:51:09 +0000485 self.assertEquals('::', f(b'\x00' * 16))
486 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000487 self.assertEquals(
488 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000489 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 +0000490 )
491
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000492 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000493
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000494 def _get_unused_port(self, bind_address='0.0.0.0'):
495 """Use a temporary socket to elicit an unused ephemeral port.
Christian Heimes5e696852008-04-09 08:37:03 +0000496
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000497 Args:
498 bind_address: Hostname or IP address to search for a port on.
499
500 Returns: A most likely to be unused port.
501 """
502 tempsock = socket.socket()
503 tempsock.bind((bind_address, 0))
504 host, port = tempsock.getsockname()
505 tempsock.close()
506 return port
507
508 def testSockName(self):
509 # Testing getsockname()
510 port = self._get_unused_port()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000511 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Christian Heimes5e696852008-04-09 08:37:03 +0000512 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000513 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000514 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
515 # it reasonable to get the host's addr in addition to 0.0.0.0.
516 # At least for eCos. This is required for the S/390 to pass.
517 my_ip_addr = socket.gethostbyname(socket.gethostname())
Georg Brandlab91fde2009-08-13 08:51:18 +0000518 self.assertTrue(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +0000519 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000520
521 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000522 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000523 # We know a socket should start without reuse==0
524 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
525 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000526 self.assertFalse(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000527
528 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000529 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000530 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
531 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
532 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000533 self.assertFalse(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000534
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000535 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000536 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000537 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
538 sock.settimeout(1)
539 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000540 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000541
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000542 def testNewAttributes(self):
543 # testing .family, .type and .protocol
544 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
545 self.assertEqual(sock.family, socket.AF_INET)
546 self.assertEqual(sock.type, socket.SOCK_STREAM)
547 self.assertEqual(sock.proto, 0)
548 sock.close()
549
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000550 def test_getsockaddrarg(self):
551 host = '0.0.0.0'
552 port = self._get_unused_port(bind_address=host)
553 big_port = port + 65536
554 neg_port = port - 65536
555 sock = socket.socket()
556 try:
557 self.assertRaises(OverflowError, sock.bind, (host, big_port))
558 self.assertRaises(OverflowError, sock.bind, (host, neg_port))
559 sock.bind((host, port))
560 finally:
561 sock.close()
562
Christian Heimesfaf2f632008-01-06 16:59:19 +0000563 def test_sock_ioctl(self):
564 if os.name != "nt":
565 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000566 self.assertTrue(hasattr(socket.socket, 'ioctl'))
567 self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
568 self.assertTrue(hasattr(socket, 'RCVALL_ON'))
569 self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
Christian Heimesfaf2f632008-01-06 16:59:19 +0000570
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000571 def testGetaddrinfo(self):
572 try:
573 socket.getaddrinfo('localhost', 80)
574 except socket.gaierror as err:
575 if err.errno == socket.EAI_SERVICE:
576 # see http://bugs.python.org/issue1282647
577 self.skipTest("buggy libc version")
578 raise
579 # len of every sequence is supposed to be == 5
580 for info in socket.getaddrinfo(HOST, None):
581 self.assertEqual(len(info), 5)
582 # host can be a domain name, a string representation of an
583 # IPv4/v6 address or None
584 socket.getaddrinfo('localhost', 80)
585 socket.getaddrinfo('127.0.0.1', 80)
586 socket.getaddrinfo(None, 80)
587 if SUPPORTS_IPV6:
588 socket.getaddrinfo('::1', 80)
589 # port can be a string service name such as "http", a numeric
590 # port number or None
591 socket.getaddrinfo(HOST, "http")
592 socket.getaddrinfo(HOST, 80)
593 socket.getaddrinfo(HOST, None)
594 # test family and socktype filters
595 infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
596 for family, _, _, _, _ in infos:
597 self.assertEqual(family, socket.AF_INET)
598 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
599 for _, socktype, _, _, _ in infos:
600 self.assertEqual(socktype, socket.SOCK_STREAM)
601 # test proto and flags arguments
Giampaolo Rodolà5b37ce62010-08-16 05:09:31 +0000602 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000603 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
604 # a server willing to support both IPv4 and IPv6 will
605 # usually do this
606 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
607 socket.AI_PASSIVE)
608
Christian Heimesfaf2f632008-01-06 16:59:19 +0000609
Guido van Rossum24e4af82002-06-12 19:18:08 +0000610class BasicTCPTest(SocketConnectedTest):
611
612 def __init__(self, methodName='runTest'):
613 SocketConnectedTest.__init__(self, methodName=methodName)
614
615 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000616 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000617 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000618 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000619
620 def _testRecv(self):
621 self.serv_conn.send(MSG)
622
623 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000624 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000625 seg1 = self.cli_conn.recv(len(MSG) - 3)
626 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000627 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000628 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000629
630 def _testOverFlowRecv(self):
631 self.serv_conn.send(MSG)
632
633 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000634 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000635 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000636 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000637
638 def _testRecvFrom(self):
639 self.serv_conn.send(MSG)
640
641 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000642 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000643 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
644 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000645 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000646 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000647
648 def _testOverFlowRecvFrom(self):
649 self.serv_conn.send(MSG)
650
651 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000652 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000653 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000654 while 1:
655 read = self.cli_conn.recv(1024)
656 if not read:
657 break
Guido van Rossume531e292002-08-08 20:28:34 +0000658 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000659 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000660
661 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000662 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000663 self.serv_conn.sendall(big_chunk)
664
665 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000666 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000667 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000668 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000669 fd = self.cli_conn.fileno()
670 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
671 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000672 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000673
674 def _testFromFd(self):
675 self.serv_conn.send(MSG)
676
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000677 def testDup(self):
678 # Testing dup()
679 sock = self.cli_conn.dup()
680 msg = sock.recv(1024)
681 self.assertEqual(msg, MSG)
682
683 def _testDup(self):
684 self.serv_conn.send(MSG)
685
Guido van Rossum24e4af82002-06-12 19:18:08 +0000686 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000687 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000688 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000689 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +0000690 # wait for _testShutdown to finish: on OS X, when the server
691 # closes the connection the client also becomes disconnected,
692 # and the client's shutdown call will fail. (Issue #4397.)
693 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000694
695 def _testShutdown(self):
696 self.serv_conn.send(MSG)
697 self.serv_conn.shutdown(2)
698
699class BasicUDPTest(ThreadedUDPSocketTest):
700
701 def __init__(self, methodName='runTest'):
702 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
703
704 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000705 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000706 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000707 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000708
709 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000710 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000711
Guido van Rossum1c938012002-06-12 21:17:20 +0000712 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000713 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000714 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000715 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000716
Guido van Rossum1c938012002-06-12 21:17:20 +0000717 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000718 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000719
Guido van Rossumd8faa362007-04-27 19:54:29 +0000720 def testRecvFromNegative(self):
721 # Negative lengths passed to recvfrom should give ValueError.
722 self.assertRaises(ValueError, self.serv.recvfrom, -1)
723
724 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000725 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000726
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000727class TCPCloserTest(ThreadedTCPSocketTest):
728
729 def testClose(self):
730 conn, addr = self.serv.accept()
731 conn.close()
732
733 sd = self.cli
734 read, write, err = select.select([sd], [], [], 1.0)
735 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000736 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000737
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000738 # Calling close() many times should be safe.
739 conn.close()
740 conn.close()
741
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000742 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000743 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000744 time.sleep(1.0)
745
Dave Cole331708b2004-08-09 04:51:41 +0000746class BasicSocketPairTest(SocketPairTest):
747
748 def __init__(self, methodName='runTest'):
749 SocketPairTest.__init__(self, methodName=methodName)
750
751 def testRecv(self):
752 msg = self.serv.recv(1024)
753 self.assertEqual(msg, MSG)
754
755 def _testRecv(self):
756 self.cli.send(MSG)
757
758 def testSend(self):
759 self.serv.send(MSG)
760
761 def _testSend(self):
762 msg = self.cli.recv(1024)
763 self.assertEqual(msg, MSG)
764
Guido van Rossum24e4af82002-06-12 19:18:08 +0000765class NonBlockingTCPTests(ThreadedTCPSocketTest):
766
767 def __init__(self, methodName='runTest'):
768 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
769
770 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000771 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000772 self.serv.setblocking(0)
773 start = time.time()
774 try:
775 self.serv.accept()
776 except socket.error:
777 pass
778 end = time.time()
Georg Brandlab91fde2009-08-13 08:51:18 +0000779 self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000780
781 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000782 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000783
Guido van Rossum24e4af82002-06-12 19:18:08 +0000784 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000785 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000786 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000787 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000788 conn, addr = self.serv.accept()
789 except socket.error:
790 pass
791 else:
792 self.fail("Error trying to do non-blocking accept.")
793 read, write, err = select.select([self.serv], [], [])
794 if self.serv in read:
795 conn, addr = self.serv.accept()
796 else:
797 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000798
Guido van Rossum24e4af82002-06-12 19:18:08 +0000799 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000800 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +0000801 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000802
803 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000804 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000805 conn, addr = self.serv.accept()
806
807 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000808 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +0000809 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000810
811 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000812 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000813 conn, addr = self.serv.accept()
814 conn.setblocking(0)
815 try:
816 msg = conn.recv(len(MSG))
817 except socket.error:
818 pass
819 else:
820 self.fail("Error trying to do non-blocking recv.")
821 read, write, err = select.select([conn], [], [])
822 if conn in read:
823 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000824 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000825 else:
826 self.fail("Error during select call to non-blocking socket.")
827
828 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000829 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000830 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000831 self.cli.send(MSG)
832
833class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000834 """Unit tests for the object returned by socket.makefile()
835
836 self.serv_file is the io object returned by makefile() on
837 the client connection. You can read from this file to
838 get output from the server.
839
840 self.cli_file is the io object returned by makefile() on the
841 server connection. You can write to this file to send output
842 to the client.
843 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000844
Guido van Rossume9f66142002-08-07 15:46:19 +0000845 bufsize = -1 # Use default buffer size
846
Guido van Rossum24e4af82002-06-12 19:18:08 +0000847 def __init__(self, methodName='runTest'):
848 SocketConnectedTest.__init__(self, methodName=methodName)
849
850 def setUp(self):
851 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000852 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000853
854 def tearDown(self):
855 self.serv_file.close()
Georg Brandlab91fde2009-08-13 08:51:18 +0000856 self.assertTrue(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000857 self.serv_file = None
858 SocketConnectedTest.tearDown(self)
859
860 def clientSetUp(self):
861 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000862 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000863
864 def clientTearDown(self):
865 self.cli_file.close()
Georg Brandlab91fde2009-08-13 08:51:18 +0000866 self.assertTrue(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000867 self.cli_file = None
868 SocketConnectedTest.clientTearDown(self)
869
870 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000871 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000872 first_seg = self.serv_file.read(len(MSG)-3)
873 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000874 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000875 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000876
877 def _testSmallRead(self):
878 self.cli_file.write(MSG)
879 self.cli_file.flush()
880
Guido van Rossum8c943832002-08-08 01:00:28 +0000881 def testFullRead(self):
882 # read until EOF
883 msg = self.serv_file.read()
884 self.assertEqual(msg, MSG)
885
886 def _testFullRead(self):
887 self.cli_file.write(MSG)
888 self.cli_file.close()
889
Guido van Rossum24e4af82002-06-12 19:18:08 +0000890 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000891 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000892 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000893 while 1:
894 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000895 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000896 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000897 buf += char
898 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000899
900 def _testUnbufferedRead(self):
901 self.cli_file.write(MSG)
902 self.cli_file.flush()
903
904 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000905 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000906 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000907 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000908
909 def _testReadline(self):
910 self.cli_file.write(MSG)
911 self.cli_file.flush()
912
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000913 def testCloseAfterMakefile(self):
914 # The file returned by makefile should keep the socket open.
915 self.cli_conn.close()
916 # read until EOF
917 msg = self.serv_file.read()
918 self.assertEqual(msg, MSG)
919
920 def _testCloseAfterMakefile(self):
921 self.cli_file.write(MSG)
922 self.cli_file.flush()
923
924 def testMakefileAfterMakefileClose(self):
925 self.serv_file.close()
926 msg = self.cli_conn.recv(len(MSG))
927 self.assertEqual(msg, MSG)
928
929 def _testMakefileAfterMakefileClose(self):
930 self.cli_file.write(MSG)
931 self.cli_file.flush()
932
Tim Peters116d83c2004-03-28 02:20:45 +0000933 def testClosedAttr(self):
Georg Brandlab91fde2009-08-13 08:51:18 +0000934 self.assertTrue(not self.serv_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +0000935
936 def _testClosedAttr(self):
Georg Brandlab91fde2009-08-13 08:51:18 +0000937 self.assertTrue(not self.cli_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +0000938
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000939 def testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +0000940 self.assertEqual(self.serv_file.mode, 'rb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000941 self.assertEqual(self.serv_file.name, self.cli_conn.fileno())
942
943 def _testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +0000944 self.assertEqual(self.cli_file.mode, 'wb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000945 self.assertEqual(self.cli_file.name, self.serv_conn.fileno())
946
Gregory P. Smithde3369f2009-01-12 04:50:11 +0000947 def testRealClose(self):
948 self.serv_file.close()
949 self.assertRaises(ValueError, self.serv_file.fileno)
950 self.cli_conn.close()
951 self.assertRaises(socket.error, self.cli_conn.getsockname)
952
953 def _testRealClose(self):
954 pass
955
956
Guido van Rossume9f66142002-08-07 15:46:19 +0000957class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
958
959 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000960
Guido van Rossume9f66142002-08-07 15:46:19 +0000961 In this case (and in this case only), it should be possible to
962 create a file object, read a line from it, create another file
963 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +0000964 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +0000965 when reading multiple requests from the same socket."""
966
967 bufsize = 0 # Use unbuffered mode
968
969 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000970 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000971 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000972 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000973 self.serv_file = self.cli_conn.makefile('rb', 0)
974 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000975 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000976
977 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000978 self.cli_file.write(b"A. " + MSG)
979 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000980 self.cli_file.flush()
981
Gregory P. Smithde3369f2009-01-12 04:50:11 +0000982 def testMakefileClose(self):
983 # The file returned by makefile should keep the socket open...
984 self.cli_conn.close()
985 msg = self.cli_conn.recv(1024)
986 self.assertEqual(msg, MSG)
987 # ...until the file is itself closed
988 self.serv_file.close()
989 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
990
991 def _testMakefileClose(self):
992 self.cli_file.write(MSG)
993 self.cli_file.flush()
994
995 def testMakefileCloseSocketDestroy(self):
996 refcount_before = sys.getrefcount(self.cli_conn)
997 self.serv_file.close()
998 refcount_after = sys.getrefcount(self.cli_conn)
999 self.assertEqual(refcount_before - 1, refcount_after)
1000
1001 def _testMakefileCloseSocketDestroy(self):
1002 pass
1003
1004
Guido van Rossum8c943832002-08-08 01:00:28 +00001005class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1006
1007 bufsize = 1 # Default-buffered for reading; line-buffered for writing
1008
1009
1010class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1011
1012 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +00001013
Thomas Woutersb2137042007-02-01 18:02:27 +00001014
Guido van Rossumd8faa362007-04-27 19:54:29 +00001015class NetworkConnectionTest(object):
1016 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001017
Guido van Rossumd8faa362007-04-27 19:54:29 +00001018 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001019 # We're inherited below by BasicTCPTest2, which also inherits
1020 # BasicTCPTest, which defines self.port referenced below.
1021 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001022 self.serv_conn = self.cli
1023
1024class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
1025 """Tests that NetworkConnection does not break existing TCP functionality.
1026 """
1027
1028class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001029
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001030 class MockSocket(socket.socket):
1031 def connect(self, *args):
1032 raise socket.timeout('timed out')
1033
1034 @contextlib.contextmanager
1035 def mocked_socket_module(self):
1036 """Return a socket which times out on connect"""
1037 old_socket = socket.socket
1038 socket.socket = self.MockSocket
1039 try:
1040 yield
1041 finally:
1042 socket.socket = old_socket
1043
1044 def test_connect(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001045 port = support.find_unused_port()
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001046 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1047 try:
1048 cli.connect((HOST, port))
1049 except socket.error as err:
1050 self.assertEqual(err.errno, errno.ECONNREFUSED)
1051 else:
1052 self.fail("socket.error not raised")
1053
1054 def test_create_connection(self):
1055 # Issue #9792: errors raised by create_connection() should have
1056 # a proper errno attribute.
1057 port = support.find_unused_port()
1058 try:
1059 socket.create_connection((HOST, port))
1060 except socket.error as err:
1061 self.assertEqual(err.errno, errno.ECONNREFUSED)
1062 else:
1063 self.fail("socket.error not raised")
1064
1065 def test_create_connection_timeout(self):
1066 # Issue #9792: create_connection() should not recast timeout errors
1067 # as generic socket errors.
1068 with self.mocked_socket_module():
1069 with self.assertRaises(socket.timeout):
1070 socket.create_connection((HOST, 1234))
1071
Guido van Rossumd8faa362007-04-27 19:54:29 +00001072
1073class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
1074
1075 def __init__(self, methodName='runTest'):
1076 SocketTCPTest.__init__(self, methodName=methodName)
1077 ThreadableTest.__init__(self)
1078
1079 def clientSetUp(self):
1080 pass
1081
1082 def clientTearDown(self):
1083 self.cli.close()
1084 self.cli = None
1085 ThreadableTest.clientTearDown(self)
1086
1087 def _justAccept(self):
1088 conn, addr = self.serv.accept()
1089
1090 testFamily = _justAccept
1091 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001092 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001093 self.assertEqual(self.cli.family, 2)
1094
1095 testTimeoutDefault = _justAccept
1096 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001097 # passing no explicit timeout uses socket's global default
Georg Brandlab91fde2009-08-13 08:51:18 +00001098 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001099 socket.setdefaulttimeout(42)
1100 try:
1101 self.cli = socket.create_connection((HOST, self.port))
1102 finally:
1103 socket.setdefaulttimeout(None)
1104 self.assertEquals(self.cli.gettimeout(), 42)
1105
1106 testTimeoutNone = _justAccept
1107 def _testTimeoutNone(self):
1108 # None timeout means the same as sock.settimeout(None)
Georg Brandlab91fde2009-08-13 08:51:18 +00001109 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001110 socket.setdefaulttimeout(30)
1111 try:
1112 self.cli = socket.create_connection((HOST, self.port), timeout=None)
1113 finally:
1114 socket.setdefaulttimeout(None)
1115 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001116
1117 testTimeoutValueNamed = _justAccept
1118 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001119 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001120 self.assertEqual(self.cli.gettimeout(), 30)
1121
1122 testTimeoutValueNonamed = _justAccept
1123 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001124 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001125 self.assertEqual(self.cli.gettimeout(), 30)
1126
Guido van Rossumd8faa362007-04-27 19:54:29 +00001127class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1128
1129 def __init__(self, methodName='runTest'):
1130 SocketTCPTest.__init__(self, methodName=methodName)
1131 ThreadableTest.__init__(self)
1132
1133 def clientSetUp(self):
1134 pass
1135
1136 def clientTearDown(self):
1137 self.cli.close()
1138 self.cli = None
1139 ThreadableTest.clientTearDown(self)
1140
1141 def testInsideTimeout(self):
1142 conn, addr = self.serv.accept()
1143 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001144 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001145 testOutsideTimeout = testInsideTimeout
1146
1147 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001148 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001149 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001150 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001151
1152 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001153 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Georg Brandlab91fde2009-08-13 08:51:18 +00001154 self.assertRaises(socket.timeout, lambda: sock.recv(5))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001155
1156
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001157class TCPTimeoutTest(SocketTCPTest):
1158
1159 def testTCPTimeout(self):
1160 def raise_timeout(*args, **kwargs):
1161 self.serv.settimeout(1.0)
1162 self.serv.accept()
Georg Brandlab91fde2009-08-13 08:51:18 +00001163 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001164 "Error generating a timeout exception (TCP)")
1165
1166 def testTimeoutZero(self):
1167 ok = False
1168 try:
1169 self.serv.settimeout(0.0)
1170 foo = self.serv.accept()
1171 except socket.timeout:
1172 self.fail("caught timeout instead of error (TCP)")
1173 except socket.error:
1174 ok = True
1175 except:
1176 self.fail("caught unexpected exception (TCP)")
1177 if not ok:
1178 self.fail("accept() returned success when we did not expect it")
1179
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001180 def testInterruptedTimeout(self):
1181 # XXX I don't know how to do this test on MSWindows or any other
1182 # plaform that doesn't support signal.alarm() or os.kill(), though
1183 # the bug should have existed on all platforms.
1184 if not hasattr(signal, "alarm"):
1185 return # can only test on *nix
1186 self.serv.settimeout(5.0) # must be longer than alarm
1187 class Alarm(Exception):
1188 pass
1189 def alarm_handler(signal, frame):
1190 raise Alarm
1191 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1192 try:
1193 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1194 try:
1195 foo = self.serv.accept()
1196 except socket.timeout:
1197 self.fail("caught timeout instead of Alarm")
1198 except Alarm:
1199 pass
1200 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001201 self.fail("caught other exception instead of Alarm:"
1202 " %s(%s):\n%s" %
1203 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001204 else:
1205 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001206 finally:
1207 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001208 except Alarm:
1209 self.fail("got Alarm in wrong place")
1210 finally:
1211 # no alarm can be pending. Safe to restore old handler.
1212 signal.signal(signal.SIGALRM, old_alarm)
1213
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001214class UDPTimeoutTest(SocketTCPTest):
1215
1216 def testUDPTimeout(self):
1217 def raise_timeout(*args, **kwargs):
1218 self.serv.settimeout(1.0)
1219 self.serv.recv(1024)
Georg Brandlab91fde2009-08-13 08:51:18 +00001220 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001221 "Error generating a timeout exception (UDP)")
1222
1223 def testTimeoutZero(self):
1224 ok = False
1225 try:
1226 self.serv.settimeout(0.0)
1227 foo = self.serv.recv(1024)
1228 except socket.timeout:
1229 self.fail("caught timeout instead of error (UDP)")
1230 except socket.error:
1231 ok = True
1232 except:
1233 self.fail("caught unexpected exception (UDP)")
1234 if not ok:
1235 self.fail("recv() returned success when we did not expect it")
1236
1237class TestExceptions(unittest.TestCase):
1238
1239 def testExceptionTree(self):
Georg Brandlab91fde2009-08-13 08:51:18 +00001240 self.assertTrue(issubclass(socket.error, Exception))
1241 self.assertTrue(issubclass(socket.herror, socket.error))
1242 self.assertTrue(issubclass(socket.gaierror, socket.error))
1243 self.assertTrue(issubclass(socket.timeout, socket.error))
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001244
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001245class TestLinuxAbstractNamespace(unittest.TestCase):
1246
1247 UNIX_PATH_MAX = 108
1248
1249 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001250 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001251 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1252 s1.bind(address)
1253 s1.listen(1)
1254 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1255 s2.connect(s1.getsockname())
1256 s1.accept()
1257 self.assertEqual(s1.getsockname(), address)
1258 self.assertEqual(s2.getpeername(), address)
1259
1260 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001261 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001262 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1263 s.bind(address)
1264 self.assertEqual(s.getsockname(), address)
1265
1266 def testNameOverflow(self):
1267 address = "\x00" + "h" * self.UNIX_PATH_MAX
1268 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1269 self.assertRaises(socket.error, s.bind, address)
1270
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001271
Thomas Wouters477c8d52006-05-27 19:21:47 +00001272class BufferIOTest(SocketConnectedTest):
1273 """
1274 Test the buffer versions of socket.recv() and socket.send().
1275 """
1276 def __init__(self, methodName='runTest'):
1277 SocketConnectedTest.__init__(self, methodName=methodName)
1278
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001279 def testRecvInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001280 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001281 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001282 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001283 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001284 self.assertEqual(msg, MSG)
1285
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001286 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001287 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001288 self.serv_conn.send(buf)
1289
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001290 def testRecvFromInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001291 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001292 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001293 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001294 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001295 self.assertEqual(msg, MSG)
1296
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001297 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001298 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001299 self.serv_conn.send(buf)
1300
Christian Heimes043d6f62008-01-07 17:19:16 +00001301
1302TIPC_STYPE = 2000
1303TIPC_LOWER = 200
1304TIPC_UPPER = 210
1305
1306def isTipcAvailable():
1307 """Check if the TIPC module is loaded
1308
1309 The TIPC module is not loaded automatically on Ubuntu and probably
1310 other Linux distros.
1311 """
1312 if not hasattr(socket, "AF_TIPC"):
1313 return False
1314 if not os.path.isfile("/proc/modules"):
1315 return False
1316 with open("/proc/modules") as f:
1317 for line in f:
1318 if line.startswith("tipc "):
1319 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001320 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001321 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1322 return False
1323
1324class TIPCTest (unittest.TestCase):
1325 def testRDM(self):
1326 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1327 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1328
1329 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1330 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1331 TIPC_LOWER, TIPC_UPPER)
1332 srv.bind(srvaddr)
1333
1334 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1335 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1336 cli.sendto(MSG, sendaddr)
1337
1338 msg, recvaddr = srv.recvfrom(1024)
1339
1340 self.assertEqual(cli.getsockname(), recvaddr)
1341 self.assertEqual(msg, MSG)
1342
1343
1344class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1345 def __init__(self, methodName = 'runTest'):
1346 unittest.TestCase.__init__(self, methodName = methodName)
1347 ThreadableTest.__init__(self)
1348
1349 def setUp(self):
1350 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1351 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1352 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1353 TIPC_LOWER, TIPC_UPPER)
1354 self.srv.bind(srvaddr)
1355 self.srv.listen(5)
1356 self.serverExplicitReady()
1357 self.conn, self.connaddr = self.srv.accept()
1358
1359 def clientSetUp(self):
1360 # The is a hittable race between serverExplicitReady() and the
1361 # accept() call; sleep a little while to avoid it, otherwise
1362 # we could get an exception
1363 time.sleep(0.1)
1364 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1365 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1366 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1367 self.cli.connect(addr)
1368 self.cliaddr = self.cli.getsockname()
1369
1370 def testStream(self):
1371 msg = self.conn.recv(1024)
1372 self.assertEqual(msg, MSG)
1373 self.assertEqual(self.cliaddr, self.connaddr)
1374
1375 def _testStream(self):
1376 self.cli.send(MSG)
1377 self.cli.close()
1378
1379
Guido van Rossumb995eb72002-07-31 16:08:40 +00001380def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001381 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001382 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001383 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001384 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001385
1386 tests.extend([
1387 NonBlockingTCPTests,
1388 FileObjectClassTestCase,
1389 UnbufferedFileObjectClassTestCase,
1390 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001391 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001392 NetworkConnectionNoServer,
1393 NetworkConnectionAttributesTest,
1394 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001395 ])
Dave Cole331708b2004-08-09 04:51:41 +00001396 if hasattr(socket, "socketpair"):
1397 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001398 if sys.platform == 'linux2':
1399 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001400 if isTipcAvailable():
1401 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001402 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001403
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001404 thread_info = support.threading_setup()
1405 support.run_unittest(*tests)
1406 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001407
1408if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001409 test_main()