blob: 5a8aa5a905998c39468f522b2c3d4b48d47791d9 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
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
Gregory P. Smithaafdca82010-01-04 04:50:36 +00007import io
Barry Warsawcf3d4b51997-01-03 20:03:32 +00008import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00009import select
Christian Heimesbbe741d2008-03-28 10:53:29 +000010import time
11import traceback
Alexandre Vassalottif260e442008-05-11 19:59:59 +000012import queue
Jack Jansen522e7692002-09-06 21:57:50 +000013import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000014import os
15import array
Raymond Hettinger027bb632004-05-31 03:09:25 +000016from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000017import signal
Barry Warsawcf3d4b51997-01-03 20:03:32 +000018
Giampaolo Rodolà419f7042010-08-14 16:45:41 +000019def try_address(host, port=0, family=socket.AF_INET):
20 """Try to bind a socket on the given host:port and return True
21 if that has been possible."""
22 try:
23 sock = socket.socket(family, socket.SOCK_STREAM)
24 sock.bind((host, port))
25 except (socket.error, socket.gaierror):
26 return False
27 else:
28 sock.close()
29 return True
30
Benjamin Petersonee8712c2008-05-20 21:35:26 +000031HOST = support.HOST
Guido van Rossum7d0a8262007-05-21 23:13:11 +000032MSG = b'Michael Gilfix was here\n'
Giampaolo Rodolà419f7042010-08-14 16:45:41 +000033SUPPORTS_IPV6 = socket.has_ipv6 and try_address('::1', family=socket.AF_INET6)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000034
Victor Stinner45df8202010-04-28 22:31:17 +000035try:
36 import _thread as thread
37 import threading
38except ImportError:
39 thread = None
40 threading = None
41
Guido van Rossum24e4af82002-06-12 19:18:08 +000042class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000043
Guido van Rossum24e4af82002-06-12 19:18:08 +000044 def setUp(self):
45 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000046 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000047 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000048
Guido van Rossum24e4af82002-06-12 19:18:08 +000049 def tearDown(self):
50 self.serv.close()
51 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000052
Guido van Rossum24e4af82002-06-12 19:18:08 +000053class SocketUDPTest(unittest.TestCase):
54
55 def setUp(self):
56 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000057 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000058
59 def tearDown(self):
60 self.serv.close()
61 self.serv = None
62
63class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000064 """Threadable Test class
65
66 The ThreadableTest class makes it easy to create a threaded
67 client/server pair from an existing unit test. To create a
68 new threaded class from an existing unit test, use multiple
69 inheritance:
70
71 class NewClass (OldClass, ThreadableTest):
72 pass
73
74 This class defines two new fixture functions with obvious
75 purposes for overriding:
76
77 clientSetUp ()
78 clientTearDown ()
79
80 Any new test functions within the class must then define
81 tests in pairs, where the test name is preceeded with a
82 '_' to indicate the client portion of the test. Ex:
83
84 def testFoo(self):
85 # Server portion
86
87 def _testFoo(self):
88 # Client portion
89
90 Any exceptions raised by the clients during their tests
91 are caught and transferred to the main thread to alert
92 the testing framework.
93
94 Note, the server setup function cannot call any blocking
95 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +000096 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000097 the blocking call (such as in setting up a client/server
98 connection and performing the accept() in setUp().
99 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000100
101 def __init__(self):
102 # Swap the true setup function
103 self.__setUp = self.setUp
104 self.__tearDown = self.tearDown
105 self.setUp = self._setUp
106 self.tearDown = self._tearDown
107
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000108 def serverExplicitReady(self):
109 """This method allows the server to explicitly indicate that
110 it wants the client thread to proceed. This is useful if the
111 server is about to execute a blocking routine that is
112 dependent upon the client thread during its setup routine."""
113 self.server_ready.set()
114
Guido van Rossum24e4af82002-06-12 19:18:08 +0000115 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000116 self.server_ready = threading.Event()
117 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000118 self.done = threading.Event()
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000119 self.queue = queue.Queue(1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000120
121 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000122 methodname = self.id()
123 i = methodname.rfind('.')
124 methodname = methodname[i+1:]
125 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000126 self.client_thread = thread.start_new_thread(
127 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000128
129 self.__setUp()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000130 if not self.server_ready.is_set():
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000131 self.server_ready.set()
132 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000133
134 def _tearDown(self):
135 self.__tearDown()
136 self.done.wait()
137
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000138 if self.queue.qsize():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000139 msg = self.queue.get()
140 self.fail(msg)
141
142 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000143 self.server_ready.wait()
144 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000145 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000146 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000147 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000148 try:
149 test_func()
Guido van Rossumb940e112007-01-10 16:19:56 +0000150 except Exception as strerror:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000151 self.queue.put(strerror)
152 self.clientTearDown()
153
154 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000155 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000156
157 def clientTearDown(self):
158 self.done.set()
159 thread.exit()
160
161class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
162
163 def __init__(self, methodName='runTest'):
164 SocketTCPTest.__init__(self, methodName=methodName)
165 ThreadableTest.__init__(self)
166
167 def clientSetUp(self):
168 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
169
170 def clientTearDown(self):
171 self.cli.close()
172 self.cli = None
173 ThreadableTest.clientTearDown(self)
174
175class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
176
177 def __init__(self, methodName='runTest'):
178 SocketUDPTest.__init__(self, methodName=methodName)
179 ThreadableTest.__init__(self)
180
181 def clientSetUp(self):
182 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
183
184class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000185 """Socket tests for client-server connection.
186
187 self.cli_conn is a client socket connected to the server. The
188 setUp() method guarantees that it is connected to the server.
189 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000190
191 def __init__(self, methodName='runTest'):
192 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
193
194 def setUp(self):
195 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000196 # Indicate explicitly we're ready for the client thread to
197 # proceed and then perform the blocking call to accept
198 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000199 conn, addr = self.serv.accept()
200 self.cli_conn = conn
201
202 def tearDown(self):
203 self.cli_conn.close()
204 self.cli_conn = None
205 ThreadedTCPSocketTest.tearDown(self)
206
207 def clientSetUp(self):
208 ThreadedTCPSocketTest.clientSetUp(self)
Christian Heimes5e696852008-04-09 08:37:03 +0000209 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000210 self.serv_conn = self.cli
211
212 def clientTearDown(self):
213 self.serv_conn.close()
214 self.serv_conn = None
215 ThreadedTCPSocketTest.clientTearDown(self)
216
Dave Cole331708b2004-08-09 04:51:41 +0000217class SocketPairTest(unittest.TestCase, ThreadableTest):
218
219 def __init__(self, methodName='runTest'):
220 unittest.TestCase.__init__(self, methodName=methodName)
221 ThreadableTest.__init__(self)
222
223 def setUp(self):
224 self.serv, self.cli = socket.socketpair()
225
226 def tearDown(self):
227 self.serv.close()
228 self.serv = None
229
230 def clientSetUp(self):
231 pass
232
233 def clientTearDown(self):
234 self.cli.close()
235 self.cli = None
236 ThreadableTest.clientTearDown(self)
237
Tim Peters494aaee2004-08-09 18:54:11 +0000238
Guido van Rossum24e4af82002-06-12 19:18:08 +0000239#######################################################################
240## Begin Tests
241
242class GeneralModuleTests(unittest.TestCase):
243
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000244 def test_repr(self):
245 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000246 self.assertTrue(repr(s).startswith("<socket.socket object"))
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000247
Raymond Hettinger027bb632004-05-31 03:09:25 +0000248 def test_weakref(self):
249 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
250 p = proxy(s)
251 self.assertEqual(p.fileno(), s.fileno())
252 s.close()
253 s = None
254 try:
255 p.fileno()
256 except ReferenceError:
257 pass
258 else:
259 self.fail('Socket proxy still exists')
260
Guido van Rossum24e4af82002-06-12 19:18:08 +0000261 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000262 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000263 def raise_error(*args, **kwargs):
264 raise socket.error
265 def raise_herror(*args, **kwargs):
266 raise socket.herror
267 def raise_gaierror(*args, **kwargs):
268 raise socket.gaierror
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000269 self.assertRaises(socket.error, raise_error,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000270 "Error raising socket exception.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000271 self.assertRaises(socket.error, raise_herror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000272 "Error raising socket exception.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000273 self.assertRaises(socket.error, raise_gaierror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000274 "Error raising socket exception.")
275
276 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000277 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000278 socket.AF_INET
279 socket.SOCK_STREAM
280 socket.SOCK_DGRAM
281 socket.SOCK_RAW
282 socket.SOCK_RDM
283 socket.SOCK_SEQPACKET
284 socket.SOL_SOCKET
285 socket.SO_REUSEADDR
286
Guido van Rossum654c11e2002-06-13 20:24:17 +0000287 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000288 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000289 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000290 try:
291 ip = socket.gethostbyname(hostname)
292 except socket.error:
293 # Probably name lookup wasn't set up right; skip this test
294 return
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000295 self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000296 try:
297 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
298 except socket.error:
299 # Probably a similar problem as above; skip this test
300 return
Brett Cannon01668a12005-03-11 00:04:17 +0000301 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000302 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000303 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000304 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000305
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000306 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000307 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000308 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000309 try:
310 # On some versions, this loses a reference
311 orig = sys.getrefcount(__name__)
312 socket.getnameinfo(__name__,0)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000313 except TypeError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000314 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000315 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000316
Guido van Rossum24e4af82002-06-12 19:18:08 +0000317 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000318 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000319 try:
320 # On some versions, this crashes the interpreter.
321 socket.getnameinfo(('x', 0, 0, 0), 0)
322 except socket.error:
323 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000324
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000325 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000326 # This just checks that htons etc. are their own inverse,
327 # when looking at the lower 16 or 32 bits.
328 sizes = {socket.htonl: 32, socket.ntohl: 32,
329 socket.htons: 16, socket.ntohs: 16}
330 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000331 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000332 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
333 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000334
Guido van Rossuma2627af2002-09-14 00:58:46 +0000335 swapped = func(mask)
336 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000337 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000338
Guido van Rossum018919a2007-01-15 00:07:32 +0000339 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000340 good_values = [ 1, 2, 3, 1, 2, 3 ]
341 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000342 for k in good_values:
343 socket.ntohl(k)
344 socket.ntohs(k)
345 socket.htonl(k)
346 socket.htons(k)
347 for k in bad_values:
348 self.assertRaises(OverflowError, socket.ntohl, k)
349 self.assertRaises(OverflowError, socket.ntohs, k)
350 self.assertRaises(OverflowError, socket.htonl, k)
351 self.assertRaises(OverflowError, socket.htons, k)
352
Barry Warsaw11b91a02004-06-28 00:50:43 +0000353 def testGetServBy(self):
354 eq = self.assertEqual
355 # Find one service that exists, then check all the related interfaces.
356 # I've ordered this by protocols that have both a tcp and udp
357 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000358 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000359 'freebsd7', 'freebsd8', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000360 # avoid the 'echo' service on this platform, as there is an
361 # assumption breaking non-standard port/protocol entry
362 services = ('daytime', 'qotd', 'domain')
363 else:
364 services = ('echo', 'daytime', 'domain')
365 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000366 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000367 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000368 break
369 except socket.error:
370 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000371 else:
372 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000373 # Try same call with optional protocol omitted
374 port2 = socket.getservbyname(service)
375 eq(port, port2)
376 # Try udp, but don't barf it it doesn't exist
377 try:
378 udpport = socket.getservbyname(service, 'udp')
379 except socket.error:
380 udpport = None
381 else:
382 eq(udpport, port)
383 # Now make sure the lookup by port returns the same service name
384 eq(socket.getservbyport(port2), service)
385 eq(socket.getservbyport(port, 'tcp'), service)
386 if udpport is not None:
387 eq(socket.getservbyport(udpport, 'udp'), service)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000388 # Make sure getservbyport does not accept out of range ports.
389 self.assertRaises(OverflowError, socket.getservbyport, -1)
390 self.assertRaises(OverflowError, socket.getservbyport, 65536)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000391
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000392 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000393 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000394 # The default timeout should initially be None
395 self.assertEqual(socket.getdefaulttimeout(), None)
396 s = socket.socket()
397 self.assertEqual(s.gettimeout(), None)
398 s.close()
399
400 # Set the default timeout to 10, and see if it propagates
401 socket.setdefaulttimeout(10)
402 self.assertEqual(socket.getdefaulttimeout(), 10)
403 s = socket.socket()
404 self.assertEqual(s.gettimeout(), 10)
405 s.close()
406
407 # Reset the default timeout to None, and see if it propagates
408 socket.setdefaulttimeout(None)
409 self.assertEqual(socket.getdefaulttimeout(), None)
410 s = socket.socket()
411 self.assertEqual(s.gettimeout(), None)
412 s.close()
413
414 # Check that setting it to an invalid value raises ValueError
415 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
416
417 # Check that setting it to an invalid type raises TypeError
418 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
419
Benjamin Petersonf91df042009-02-13 02:50:59 +0000420 def testIPv4_inet_aton_fourbytes(self):
421 if not hasattr(socket, 'inet_aton'):
422 return # No inet_aton, nothing to check
423 # Test that issue1008086 and issue767150 are fixed.
424 # It must return 4 bytes.
425 self.assertEquals(b'\x00'*4, socket.inet_aton('0.0.0.0'))
426 self.assertEquals(b'\xff'*4, socket.inet_aton('255.255.255.255'))
427
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000428 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000429 if not hasattr(socket, 'inet_pton'):
430 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000431 from socket import inet_aton as f, inet_pton, AF_INET
432 g = lambda a: inet_pton(AF_INET, a)
433
Guido van Rossumb5b22702007-05-18 18:55:53 +0000434 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
435 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
436 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
437 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
438 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000439
Guido van Rossumb5b22702007-05-18 18:55:53 +0000440 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
441 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
442 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
443 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000444
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000445 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000446 if not hasattr(socket, 'inet_pton'):
447 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000448 try:
449 from socket import inet_pton, AF_INET6, has_ipv6
450 if not has_ipv6:
451 return
452 except ImportError:
453 return
454 f = lambda a: inet_pton(AF_INET6, a)
455
Guido van Rossum540d9872007-08-17 03:51:09 +0000456 self.assertEquals(b'\x00' * 16, f('::'))
457 self.assertEquals(b'\x00' * 16, f('0::0'))
458 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000459 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000460 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 +0000461 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
462 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000463
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000464 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000465 if not hasattr(socket, 'inet_ntop'):
466 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000467 from socket import inet_ntoa as f, inet_ntop, AF_INET
468 g = lambda a: inet_ntop(AF_INET, a)
469
Guido van Rossumb5b22702007-05-18 18:55:53 +0000470 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
471 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
472 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
473 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000474
Guido van Rossumb5b22702007-05-18 18:55:53 +0000475 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
476 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
477 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000478
479 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000480 if not hasattr(socket, 'inet_ntop'):
481 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000482 try:
483 from socket import inet_ntop, AF_INET6, has_ipv6
484 if not has_ipv6:
485 return
486 except ImportError:
487 return
488 f = lambda a: inet_ntop(AF_INET6, a)
489
Guido van Rossum540d9872007-08-17 03:51:09 +0000490 self.assertEquals('::', f(b'\x00' * 16))
491 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000492 self.assertEquals(
493 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000494 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 +0000495 )
496
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000497 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000498
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000499 def _get_unused_port(self, bind_address='0.0.0.0'):
500 """Use a temporary socket to elicit an unused ephemeral port.
Christian Heimes5e696852008-04-09 08:37:03 +0000501
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000502 Args:
503 bind_address: Hostname or IP address to search for a port on.
504
505 Returns: A most likely to be unused port.
506 """
507 tempsock = socket.socket()
508 tempsock.bind((bind_address, 0))
509 host, port = tempsock.getsockname()
510 tempsock.close()
511 return port
512
513 def testSockName(self):
514 # Testing getsockname()
515 port = self._get_unused_port()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000516 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Christian Heimes5e696852008-04-09 08:37:03 +0000517 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000518 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000519 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
520 # it reasonable to get the host's addr in addition to 0.0.0.0.
521 # At least for eCos. This is required for the S/390 to pass.
522 my_ip_addr = socket.gethostbyname(socket.gethostname())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000523 self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +0000524 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000525
526 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000527 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000528 # We know a socket should start without reuse==0
529 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
530 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000531 self.assertFalse(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000532
533 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000534 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000535 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
536 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
537 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000538 self.assertFalse(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000539
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000540 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000541 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000542 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
543 sock.settimeout(1)
544 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000545 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000546
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000547 def testNewAttributes(self):
548 # testing .family, .type and .protocol
549 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
550 self.assertEqual(sock.family, socket.AF_INET)
551 self.assertEqual(sock.type, socket.SOCK_STREAM)
552 self.assertEqual(sock.proto, 0)
553 sock.close()
554
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000555 def test_getsockaddrarg(self):
556 host = '0.0.0.0'
557 port = self._get_unused_port(bind_address=host)
558 big_port = port + 65536
559 neg_port = port - 65536
560 sock = socket.socket()
561 try:
562 self.assertRaises(OverflowError, sock.bind, (host, big_port))
563 self.assertRaises(OverflowError, sock.bind, (host, neg_port))
564 sock.bind((host, port))
565 finally:
566 sock.close()
567
Christian Heimesfaf2f632008-01-06 16:59:19 +0000568 def test_sock_ioctl(self):
569 if os.name != "nt":
570 return
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000571 self.assertTrue(hasattr(socket.socket, 'ioctl'))
572 self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
573 self.assertTrue(hasattr(socket, 'RCVALL_ON'))
574 self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
Kristján Valur Jónsson847ec752009-09-27 21:10:38 +0000575 self.assertTrue(hasattr(socket, 'SIO_KEEPALIVE_VALS'))
576 s = socket.socket()
577 self.assertRaises(ValueError, s.ioctl, -1, None)
578 s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
Christian Heimesfaf2f632008-01-06 16:59:19 +0000579
Giampaolo Rodolà419f7042010-08-14 16:45:41 +0000580 def testGetaddrinfo(self):
581 try:
582 socket.getaddrinfo('localhost', 80)
583 except socket.gaierror as err:
584 if err.errno == socket.EAI_SERVICE:
585 # see http://bugs.python.org/issue1282647
586 self.skipTest("buggy libc version")
587 raise
588 # len of every sequence is supposed to be == 5
589 for info in socket.getaddrinfo(HOST, None):
590 self.assertEqual(len(info), 5)
591 # host can be a domain name, a string representation of an
592 # IPv4/v6 address or None
593 socket.getaddrinfo('localhost', 80)
594 socket.getaddrinfo('127.0.0.1', 80)
595 socket.getaddrinfo(None, 80)
596 if SUPPORTS_IPV6:
597 socket.getaddrinfo('::1', 80)
598 # port can be a string service name such as "http", a numeric
599 # port number or None
600 socket.getaddrinfo(HOST, "http")
601 socket.getaddrinfo(HOST, 80)
602 socket.getaddrinfo(HOST, None)
603 # test family and socktype filters
604 infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
605 for family, _, _, _, _ in infos:
606 self.assertEqual(family, socket.AF_INET)
607 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
608 for _, socktype, _, _, _ in infos:
609 self.assertEqual(socktype, socket.SOCK_STREAM)
610 # test proto and flags arguments
Giampaolo Rodolà677d95c2010-08-16 05:08:11 +0000611 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
Giampaolo Rodolà419f7042010-08-14 16:45:41 +0000612 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
613 # a server willing to support both IPv4 and IPv6 will
614 # usually do this
615 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
616 socket.AI_PASSIVE)
Giampaolo Rodolàccfb91c2010-08-17 15:30:23 +0000617 # test keyword arguments
618 a = socket.getaddrinfo(HOST, None)
619 b = socket.getaddrinfo(host=HOST, port=None)
620 self.assertEqual(a, b)
621 a = socket.getaddrinfo(HOST, None, socket.AF_INET)
622 b = socket.getaddrinfo(HOST, None, family=socket.AF_INET)
623 self.assertEqual(a, b)
624 a = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
625 b = socket.getaddrinfo(HOST, None, type=socket.SOCK_STREAM)
626 self.assertEqual(a, b)
627 a = socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
628 b = socket.getaddrinfo(HOST, None, proto=socket.SOL_TCP)
629 self.assertEqual(a, b)
630 a = socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
631 b = socket.getaddrinfo(HOST, None, flags=socket.AI_PASSIVE)
632 self.assertEqual(a, b)
633 a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
634 socket.AI_PASSIVE)
635 b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC,
636 type=socket.SOCK_STREAM, proto=0,
637 flags=socket.AI_PASSIVE)
638 self.assertEqual(a, b)
Giampaolo Rodolà419f7042010-08-14 16:45:41 +0000639
Martin v. Löwis112c0f32010-08-25 07:38:15 +0000640 def test_getnameinfo(self):
641 # only IP addresses are allowed
642 self.assertRaises(socket.error, socket.getnameinfo, ('mail.python.org',0), 0)
643
Martin v. Löwisfc0275a2010-08-22 19:33:47 +0000644 def test_idna(self):
645 # these should all be successful
646 socket.gethostbyname('испытание.python.org')
647 socket.gethostbyname_ex('испытание.python.org')
Martin v. Löwis67e91ad2010-08-23 15:27:26 +0000648 socket.getaddrinfo('испытание.python.org',0,socket.AF_UNSPEC,socket.SOCK_STREAM)
649 # this may not work if the forward lookup choses the IPv6 address, as that doesn't
650 # have a reverse entry yet
651 # socket.gethostbyaddr('испытание.python.org')
Christian Heimesfaf2f632008-01-06 16:59:19 +0000652
Victor Stinner45df8202010-04-28 22:31:17 +0000653@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000654class BasicTCPTest(SocketConnectedTest):
655
656 def __init__(self, methodName='runTest'):
657 SocketConnectedTest.__init__(self, methodName=methodName)
658
659 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000660 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000661 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000662 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000663
664 def _testRecv(self):
665 self.serv_conn.send(MSG)
666
667 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000668 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000669 seg1 = self.cli_conn.recv(len(MSG) - 3)
670 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000671 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000672 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000673
674 def _testOverFlowRecv(self):
675 self.serv_conn.send(MSG)
676
677 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000678 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000679 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000680 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000681
682 def _testRecvFrom(self):
683 self.serv_conn.send(MSG)
684
685 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000686 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000687 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
688 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000689 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000690 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000691
692 def _testOverFlowRecvFrom(self):
693 self.serv_conn.send(MSG)
694
695 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000696 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000697 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000698 while 1:
699 read = self.cli_conn.recv(1024)
700 if not read:
701 break
Guido van Rossume531e292002-08-08 20:28:34 +0000702 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000703 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000704
705 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000706 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000707 self.serv_conn.sendall(big_chunk)
708
709 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000710 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000711 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000712 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000713 fd = self.cli_conn.fileno()
714 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
715 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000716 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000717
718 def _testFromFd(self):
719 self.serv_conn.send(MSG)
720
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000721 def testDup(self):
722 # Testing dup()
723 sock = self.cli_conn.dup()
724 msg = sock.recv(1024)
725 self.assertEqual(msg, MSG)
726
727 def _testDup(self):
728 self.serv_conn.send(MSG)
729
Guido van Rossum24e4af82002-06-12 19:18:08 +0000730 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000731 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000732 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000733 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +0000734 # wait for _testShutdown to finish: on OS X, when the server
735 # closes the connection the client also becomes disconnected,
736 # and the client's shutdown call will fail. (Issue #4397.)
737 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000738
739 def _testShutdown(self):
740 self.serv_conn.send(MSG)
741 self.serv_conn.shutdown(2)
742
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000743 def testDetach(self):
744 # Testing detach()
745 fileno = self.cli_conn.fileno()
746 f = self.cli_conn.detach()
747 self.assertEqual(f, fileno)
748 # cli_conn cannot be used anymore...
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000749 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
750 self.cli_conn.close()
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000751 # ...but we can create another socket using the (still open)
752 # file descriptor
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000753 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f)
754 msg = sock.recv(1024)
755 self.assertEqual(msg, MSG)
756
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000757 def _testDetach(self):
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000758 self.serv_conn.send(MSG)
759
Victor Stinner45df8202010-04-28 22:31:17 +0000760@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000761class BasicUDPTest(ThreadedUDPSocketTest):
762
763 def __init__(self, methodName='runTest'):
764 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
765
766 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000767 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000768 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000769 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000770
771 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000772 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000773
Guido van Rossum1c938012002-06-12 21:17:20 +0000774 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000775 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000776 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000777 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000778
Guido van Rossum1c938012002-06-12 21:17:20 +0000779 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000780 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000781
Guido van Rossumd8faa362007-04-27 19:54:29 +0000782 def testRecvFromNegative(self):
783 # Negative lengths passed to recvfrom should give ValueError.
784 self.assertRaises(ValueError, self.serv.recvfrom, -1)
785
786 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000787 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000788
Victor Stinner45df8202010-04-28 22:31:17 +0000789@unittest.skipUnless(thread, 'Threading required for this test.')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000790class TCPCloserTest(ThreadedTCPSocketTest):
791
792 def testClose(self):
793 conn, addr = self.serv.accept()
794 conn.close()
795
796 sd = self.cli
797 read, write, err = select.select([sd], [], [], 1.0)
798 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000799 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000800
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000801 # Calling close() many times should be safe.
802 conn.close()
803 conn.close()
804
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000805 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000806 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000807 time.sleep(1.0)
808
Victor Stinner45df8202010-04-28 22:31:17 +0000809@unittest.skipUnless(thread, 'Threading required for this test.')
Dave Cole331708b2004-08-09 04:51:41 +0000810class BasicSocketPairTest(SocketPairTest):
811
812 def __init__(self, methodName='runTest'):
813 SocketPairTest.__init__(self, methodName=methodName)
814
815 def testRecv(self):
816 msg = self.serv.recv(1024)
817 self.assertEqual(msg, MSG)
818
819 def _testRecv(self):
820 self.cli.send(MSG)
821
822 def testSend(self):
823 self.serv.send(MSG)
824
825 def _testSend(self):
826 msg = self.cli.recv(1024)
827 self.assertEqual(msg, MSG)
828
Victor Stinner45df8202010-04-28 22:31:17 +0000829@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000830class NonBlockingTCPTests(ThreadedTCPSocketTest):
831
832 def __init__(self, methodName='runTest'):
833 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
834
835 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000836 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000837 self.serv.setblocking(0)
838 start = time.time()
839 try:
840 self.serv.accept()
841 except socket.error:
842 pass
843 end = time.time()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000844 self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000845
846 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000847 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000848
Guido van Rossum24e4af82002-06-12 19:18:08 +0000849 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000850 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000851 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000852 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000853 conn, addr = self.serv.accept()
854 except socket.error:
855 pass
856 else:
857 self.fail("Error trying to do non-blocking accept.")
858 read, write, err = select.select([self.serv], [], [])
859 if self.serv in read:
860 conn, addr = self.serv.accept()
861 else:
862 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000863
Guido van Rossum24e4af82002-06-12 19:18:08 +0000864 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000865 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +0000866 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000867
868 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000869 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000870 conn, addr = self.serv.accept()
871
872 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000873 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +0000874 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000875
876 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000877 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000878 conn, addr = self.serv.accept()
879 conn.setblocking(0)
880 try:
881 msg = conn.recv(len(MSG))
882 except socket.error:
883 pass
884 else:
885 self.fail("Error trying to do non-blocking recv.")
886 read, write, err = select.select([conn], [], [])
887 if conn in read:
888 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000889 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000890 else:
891 self.fail("Error during select call to non-blocking socket.")
892
893 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000894 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000895 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000896 self.cli.send(MSG)
897
Victor Stinner45df8202010-04-28 22:31:17 +0000898@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000899class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000900 """Unit tests for the object returned by socket.makefile()
901
902 self.serv_file is the io object returned by makefile() on
903 the client connection. You can read from this file to
904 get output from the server.
905
906 self.cli_file is the io object returned by makefile() on the
907 server connection. You can write to this file to send output
908 to the client.
909 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000910
Guido van Rossume9f66142002-08-07 15:46:19 +0000911 bufsize = -1 # Use default buffer size
912
Guido van Rossum24e4af82002-06-12 19:18:08 +0000913 def __init__(self, methodName='runTest'):
914 SocketConnectedTest.__init__(self, methodName=methodName)
915
916 def setUp(self):
917 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000918 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000919
920 def tearDown(self):
921 self.serv_file.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000922 self.assertTrue(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000923 self.serv_file = None
924 SocketConnectedTest.tearDown(self)
925
926 def clientSetUp(self):
927 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000928 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000929
930 def clientTearDown(self):
931 self.cli_file.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000932 self.assertTrue(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000933 self.cli_file = None
934 SocketConnectedTest.clientTearDown(self)
935
936 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000937 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000938 first_seg = self.serv_file.read(len(MSG)-3)
939 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000940 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000941 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000942
943 def _testSmallRead(self):
944 self.cli_file.write(MSG)
945 self.cli_file.flush()
946
Guido van Rossum8c943832002-08-08 01:00:28 +0000947 def testFullRead(self):
948 # read until EOF
949 msg = self.serv_file.read()
950 self.assertEqual(msg, MSG)
951
952 def _testFullRead(self):
953 self.cli_file.write(MSG)
954 self.cli_file.close()
955
Guido van Rossum24e4af82002-06-12 19:18:08 +0000956 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000957 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000958 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000959 while 1:
960 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000961 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000962 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000963 buf += char
964 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000965
966 def _testUnbufferedRead(self):
967 self.cli_file.write(MSG)
968 self.cli_file.flush()
969
970 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000971 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000972 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000973 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000974
975 def _testReadline(self):
976 self.cli_file.write(MSG)
977 self.cli_file.flush()
978
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000979 def testCloseAfterMakefile(self):
980 # The file returned by makefile should keep the socket open.
981 self.cli_conn.close()
982 # read until EOF
983 msg = self.serv_file.read()
984 self.assertEqual(msg, MSG)
985
986 def _testCloseAfterMakefile(self):
987 self.cli_file.write(MSG)
988 self.cli_file.flush()
989
990 def testMakefileAfterMakefileClose(self):
991 self.serv_file.close()
992 msg = self.cli_conn.recv(len(MSG))
993 self.assertEqual(msg, MSG)
994
995 def _testMakefileAfterMakefileClose(self):
996 self.cli_file.write(MSG)
997 self.cli_file.flush()
998
Tim Peters116d83c2004-03-28 02:20:45 +0000999 def testClosedAttr(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001000 self.assertTrue(not self.serv_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00001001
1002 def _testClosedAttr(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001003 self.assertTrue(not self.cli_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00001004
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001005 def testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +00001006 self.assertEqual(self.serv_file.mode, 'rb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001007 self.assertEqual(self.serv_file.name, self.cli_conn.fileno())
1008
1009 def _testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +00001010 self.assertEqual(self.cli_file.mode, 'wb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001011 self.assertEqual(self.cli_file.name, self.serv_conn.fileno())
1012
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001013 def testRealClose(self):
1014 self.serv_file.close()
1015 self.assertRaises(ValueError, self.serv_file.fileno)
1016 self.cli_conn.close()
1017 self.assertRaises(socket.error, self.cli_conn.getsockname)
1018
1019 def _testRealClose(self):
1020 pass
1021
1022
Gregory P. Smithaafdca82010-01-04 04:50:36 +00001023class FileObjectInterruptedTestCase(unittest.TestCase):
1024 """Test that the file object correctly handles EINTR internally."""
1025
1026 class MockSocket(object):
1027 def __init__(self, recv_funcs=()):
1028 # A generator that returns callables that we'll call for each
1029 # call to recv().
1030 self._recv_step = iter(recv_funcs)
1031
1032 def recv_into(self, buffer):
1033 data = next(self._recv_step)()
1034 assert len(buffer) >= len(data)
1035 buffer[:len(data)] = data
1036 return len(data)
1037
1038 def _decref_socketios(self):
1039 pass
1040
1041 def _textiowrap_for_test(self, buffering=-1):
1042 raw = socket.SocketIO(self, "r")
1043 if buffering < 0:
1044 buffering = io.DEFAULT_BUFFER_SIZE
1045 if buffering == 0:
1046 return raw
1047 buffer = io.BufferedReader(raw, buffering)
1048 text = io.TextIOWrapper(buffer, None, None)
1049 text.mode = "rb"
1050 return text
1051
1052 @staticmethod
1053 def _raise_eintr():
1054 raise socket.error(errno.EINTR)
1055
1056 def _textiowrap_mock_socket(self, mock, buffering=-1):
1057 raw = socket.SocketIO(mock, "r")
1058 if buffering < 0:
1059 buffering = io.DEFAULT_BUFFER_SIZE
1060 if buffering == 0:
1061 return raw
1062 buffer = io.BufferedReader(raw, buffering)
1063 text = io.TextIOWrapper(buffer, None, None)
1064 text.mode = "rb"
1065 return text
1066
1067 def _test_readline(self, size=-1, buffering=-1):
1068 mock_sock = self.MockSocket(recv_funcs=[
1069 lambda : b"This is the first line\nAnd the sec",
1070 self._raise_eintr,
1071 lambda : b"ond line is here\n",
1072 lambda : b"",
1073 lambda : b"", # XXX(gps): io library does an extra EOF read
1074 ])
1075 fo = mock_sock._textiowrap_for_test(buffering=buffering)
1076 self.assertEquals(fo.readline(size), "This is the first line\n")
1077 self.assertEquals(fo.readline(size), "And the second line is here\n")
1078
1079 def _test_read(self, size=-1, buffering=-1):
1080 mock_sock = self.MockSocket(recv_funcs=[
1081 lambda : b"This is the first line\nAnd the sec",
1082 self._raise_eintr,
1083 lambda : b"ond line is here\n",
1084 lambda : b"",
1085 lambda : b"", # XXX(gps): io library does an extra EOF read
1086 ])
1087 expecting = (b"This is the first line\n"
1088 b"And the second line is here\n")
1089 fo = mock_sock._textiowrap_for_test(buffering=buffering)
1090 if buffering == 0:
1091 data = b''
1092 else:
1093 data = ''
1094 expecting = expecting.decode('utf8')
1095 while len(data) != len(expecting):
1096 part = fo.read(size)
1097 if not part:
1098 break
1099 data += part
1100 self.assertEquals(data, expecting)
1101
1102 def test_default(self):
1103 self._test_readline()
1104 self._test_readline(size=100)
1105 self._test_read()
1106 self._test_read(size=100)
1107
1108 def test_with_1k_buffer(self):
1109 self._test_readline(buffering=1024)
1110 self._test_readline(size=100, buffering=1024)
1111 self._test_read(buffering=1024)
1112 self._test_read(size=100, buffering=1024)
1113
1114 def _test_readline_no_buffer(self, size=-1):
1115 mock_sock = self.MockSocket(recv_funcs=[
1116 lambda : b"a",
1117 lambda : b"\n",
1118 lambda : b"B",
1119 self._raise_eintr,
1120 lambda : b"b",
1121 lambda : b"",
1122 ])
1123 fo = mock_sock._textiowrap_for_test(buffering=0)
1124 self.assertEquals(fo.readline(size), b"a\n")
1125 self.assertEquals(fo.readline(size), b"Bb")
1126
1127 def test_no_buffer(self):
1128 self._test_readline_no_buffer()
1129 self._test_readline_no_buffer(size=4)
1130 self._test_read(buffering=0)
1131 self._test_read(size=100, buffering=0)
1132
1133
Guido van Rossume9f66142002-08-07 15:46:19 +00001134class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
1135
1136 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +00001137
Guido van Rossume9f66142002-08-07 15:46:19 +00001138 In this case (and in this case only), it should be possible to
1139 create a file object, read a line from it, create another file
1140 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +00001141 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +00001142 when reading multiple requests from the same socket."""
1143
1144 bufsize = 0 # Use unbuffered mode
1145
1146 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001147 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +00001148 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001149 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +00001150 self.serv_file = self.cli_conn.makefile('rb', 0)
1151 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001152 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +00001153
1154 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001155 self.cli_file.write(b"A. " + MSG)
1156 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +00001157 self.cli_file.flush()
1158
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001159 def testMakefileClose(self):
1160 # The file returned by makefile should keep the socket open...
1161 self.cli_conn.close()
1162 msg = self.cli_conn.recv(1024)
1163 self.assertEqual(msg, MSG)
1164 # ...until the file is itself closed
1165 self.serv_file.close()
1166 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
1167
1168 def _testMakefileClose(self):
1169 self.cli_file.write(MSG)
1170 self.cli_file.flush()
1171
1172 def testMakefileCloseSocketDestroy(self):
1173 refcount_before = sys.getrefcount(self.cli_conn)
1174 self.serv_file.close()
1175 refcount_after = sys.getrefcount(self.cli_conn)
1176 self.assertEqual(refcount_before - 1, refcount_after)
1177
1178 def _testMakefileCloseSocketDestroy(self):
1179 pass
1180
1181
Guido van Rossum8c943832002-08-08 01:00:28 +00001182class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1183
1184 bufsize = 1 # Default-buffered for reading; line-buffered for writing
1185
1186
1187class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1188
1189 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +00001190
Thomas Woutersb2137042007-02-01 18:02:27 +00001191
Guido van Rossumd8faa362007-04-27 19:54:29 +00001192class NetworkConnectionTest(object):
1193 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001194
Guido van Rossumd8faa362007-04-27 19:54:29 +00001195 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001196 # We're inherited below by BasicTCPTest2, which also inherits
1197 # BasicTCPTest, which defines self.port referenced below.
1198 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001199 self.serv_conn = self.cli
1200
1201class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
1202 """Tests that NetworkConnection does not break existing TCP functionality.
1203 """
1204
1205class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001206
Guido van Rossumd8faa362007-04-27 19:54:29 +00001207 def testWithoutServer(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001208 port = support.find_unused_port()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001209 self.assertRaises(
Christian Heimes5e696852008-04-09 08:37:03 +00001210 socket.error,
1211 lambda: socket.create_connection((HOST, port))
1212 )
Guido van Rossumd8faa362007-04-27 19:54:29 +00001213
Victor Stinner45df8202010-04-28 22:31:17 +00001214@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
1216
1217 def __init__(self, methodName='runTest'):
1218 SocketTCPTest.__init__(self, methodName=methodName)
1219 ThreadableTest.__init__(self)
1220
1221 def clientSetUp(self):
Gregory P. Smithb4066372010-01-03 03:28:29 +00001222 self.source_port = support.find_unused_port()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001223
1224 def clientTearDown(self):
1225 self.cli.close()
1226 self.cli = None
1227 ThreadableTest.clientTearDown(self)
1228
1229 def _justAccept(self):
1230 conn, addr = self.serv.accept()
1231
1232 testFamily = _justAccept
1233 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001234 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001235 self.assertEqual(self.cli.family, 2)
1236
Gregory P. Smitha81d8812010-01-03 15:09:32 +00001237 testSourceAddress = _justAccept
1238 def _testSourceAddress(self):
Gregory P. Smithb4066372010-01-03 03:28:29 +00001239 self.cli = socket.create_connection((HOST, self.port), timeout=30,
1240 source_address=('', self.source_port))
1241 self.assertEqual(self.cli.getsockname()[1], self.source_port)
Gregory P. Smitha81d8812010-01-03 15:09:32 +00001242 # The port number being used is sufficient to show that the bind()
1243 # call happened.
Gregory P. Smithb4066372010-01-03 03:28:29 +00001244
Guido van Rossumd8faa362007-04-27 19:54:29 +00001245 testTimeoutDefault = _justAccept
1246 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001247 # passing no explicit timeout uses socket's global default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001248 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001249 socket.setdefaulttimeout(42)
1250 try:
1251 self.cli = socket.create_connection((HOST, self.port))
1252 finally:
1253 socket.setdefaulttimeout(None)
1254 self.assertEquals(self.cli.gettimeout(), 42)
1255
1256 testTimeoutNone = _justAccept
1257 def _testTimeoutNone(self):
1258 # None timeout means the same as sock.settimeout(None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001259 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001260 socket.setdefaulttimeout(30)
1261 try:
1262 self.cli = socket.create_connection((HOST, self.port), timeout=None)
1263 finally:
1264 socket.setdefaulttimeout(None)
1265 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001266
1267 testTimeoutValueNamed = _justAccept
1268 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001269 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001270 self.assertEqual(self.cli.gettimeout(), 30)
1271
1272 testTimeoutValueNonamed = _justAccept
1273 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001274 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001275 self.assertEqual(self.cli.gettimeout(), 30)
1276
Victor Stinner45df8202010-04-28 22:31:17 +00001277@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001278class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1279
1280 def __init__(self, methodName='runTest'):
1281 SocketTCPTest.__init__(self, methodName=methodName)
1282 ThreadableTest.__init__(self)
1283
1284 def clientSetUp(self):
1285 pass
1286
1287 def clientTearDown(self):
1288 self.cli.close()
1289 self.cli = None
1290 ThreadableTest.clientTearDown(self)
1291
1292 def testInsideTimeout(self):
1293 conn, addr = self.serv.accept()
1294 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001295 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001296 testOutsideTimeout = testInsideTimeout
1297
1298 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001299 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001300 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001301 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001302
1303 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001304 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001305 self.assertRaises(socket.timeout, lambda: sock.recv(5))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001306
1307
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001308class TCPTimeoutTest(SocketTCPTest):
1309
1310 def testTCPTimeout(self):
1311 def raise_timeout(*args, **kwargs):
1312 self.serv.settimeout(1.0)
1313 self.serv.accept()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001314 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001315 "Error generating a timeout exception (TCP)")
1316
1317 def testTimeoutZero(self):
1318 ok = False
1319 try:
1320 self.serv.settimeout(0.0)
1321 foo = self.serv.accept()
1322 except socket.timeout:
1323 self.fail("caught timeout instead of error (TCP)")
1324 except socket.error:
1325 ok = True
1326 except:
1327 self.fail("caught unexpected exception (TCP)")
1328 if not ok:
1329 self.fail("accept() returned success when we did not expect it")
1330
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001331 def testInterruptedTimeout(self):
1332 # XXX I don't know how to do this test on MSWindows or any other
1333 # plaform that doesn't support signal.alarm() or os.kill(), though
1334 # the bug should have existed on all platforms.
1335 if not hasattr(signal, "alarm"):
1336 return # can only test on *nix
1337 self.serv.settimeout(5.0) # must be longer than alarm
1338 class Alarm(Exception):
1339 pass
1340 def alarm_handler(signal, frame):
1341 raise Alarm
1342 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1343 try:
1344 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1345 try:
1346 foo = self.serv.accept()
1347 except socket.timeout:
1348 self.fail("caught timeout instead of Alarm")
1349 except Alarm:
1350 pass
1351 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001352 self.fail("caught other exception instead of Alarm:"
1353 " %s(%s):\n%s" %
1354 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001355 else:
1356 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001357 finally:
1358 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001359 except Alarm:
1360 self.fail("got Alarm in wrong place")
1361 finally:
1362 # no alarm can be pending. Safe to restore old handler.
1363 signal.signal(signal.SIGALRM, old_alarm)
1364
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001365class UDPTimeoutTest(SocketTCPTest):
1366
1367 def testUDPTimeout(self):
1368 def raise_timeout(*args, **kwargs):
1369 self.serv.settimeout(1.0)
1370 self.serv.recv(1024)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001371 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001372 "Error generating a timeout exception (UDP)")
1373
1374 def testTimeoutZero(self):
1375 ok = False
1376 try:
1377 self.serv.settimeout(0.0)
1378 foo = self.serv.recv(1024)
1379 except socket.timeout:
1380 self.fail("caught timeout instead of error (UDP)")
1381 except socket.error:
1382 ok = True
1383 except:
1384 self.fail("caught unexpected exception (UDP)")
1385 if not ok:
1386 self.fail("recv() returned success when we did not expect it")
1387
1388class TestExceptions(unittest.TestCase):
1389
1390 def testExceptionTree(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001391 self.assertTrue(issubclass(socket.error, Exception))
1392 self.assertTrue(issubclass(socket.herror, socket.error))
1393 self.assertTrue(issubclass(socket.gaierror, socket.error))
1394 self.assertTrue(issubclass(socket.timeout, socket.error))
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001395
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001396class TestLinuxAbstractNamespace(unittest.TestCase):
1397
1398 UNIX_PATH_MAX = 108
1399
1400 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001401 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001402 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1403 s1.bind(address)
1404 s1.listen(1)
1405 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1406 s2.connect(s1.getsockname())
1407 s1.accept()
1408 self.assertEqual(s1.getsockname(), address)
1409 self.assertEqual(s2.getpeername(), address)
1410
1411 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001412 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001413 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1414 s.bind(address)
1415 self.assertEqual(s.getsockname(), address)
1416
1417 def testNameOverflow(self):
1418 address = "\x00" + "h" * self.UNIX_PATH_MAX
1419 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1420 self.assertRaises(socket.error, s.bind, address)
1421
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001422
Victor Stinner45df8202010-04-28 22:31:17 +00001423@unittest.skipUnless(thread, 'Threading required for this test.')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001424class BufferIOTest(SocketConnectedTest):
1425 """
1426 Test the buffer versions of socket.recv() and socket.send().
1427 """
1428 def __init__(self, methodName='runTest'):
1429 SocketConnectedTest.__init__(self, methodName=methodName)
1430
Antoine Pitrou25480782010-03-17 22:50:28 +00001431 def testRecvIntoArray(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001432 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001433 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001434 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001435 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001436 self.assertEqual(msg, MSG)
1437
Antoine Pitrou25480782010-03-17 22:50:28 +00001438 def _testRecvIntoArray(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001439 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001440 self.serv_conn.send(buf)
1441
Antoine Pitrou25480782010-03-17 22:50:28 +00001442 def testRecvIntoBytearray(self):
1443 buf = bytearray(1024)
1444 nbytes = self.cli_conn.recv_into(buf)
1445 self.assertEqual(nbytes, len(MSG))
1446 msg = buf[:len(MSG)]
1447 self.assertEqual(msg, MSG)
1448
1449 _testRecvIntoBytearray = _testRecvIntoArray
1450
1451 def testRecvIntoMemoryview(self):
1452 buf = bytearray(1024)
1453 nbytes = self.cli_conn.recv_into(memoryview(buf))
1454 self.assertEqual(nbytes, len(MSG))
1455 msg = buf[:len(MSG)]
1456 self.assertEqual(msg, MSG)
1457
1458 _testRecvIntoMemoryview = _testRecvIntoArray
1459
1460 def testRecvFromIntoArray(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001461 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001462 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001463 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001464 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001465 self.assertEqual(msg, MSG)
1466
Antoine Pitrou25480782010-03-17 22:50:28 +00001467 def _testRecvFromIntoArray(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001468 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001469 self.serv_conn.send(buf)
1470
Antoine Pitrou25480782010-03-17 22:50:28 +00001471 def testRecvFromIntoBytearray(self):
1472 buf = bytearray(1024)
1473 nbytes, addr = self.cli_conn.recvfrom_into(buf)
1474 self.assertEqual(nbytes, len(MSG))
1475 msg = buf[:len(MSG)]
1476 self.assertEqual(msg, MSG)
1477
1478 _testRecvFromIntoBytearray = _testRecvFromIntoArray
1479
1480 def testRecvFromIntoMemoryview(self):
1481 buf = bytearray(1024)
1482 nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf))
1483 self.assertEqual(nbytes, len(MSG))
1484 msg = buf[:len(MSG)]
1485 self.assertEqual(msg, MSG)
1486
1487 _testRecvFromIntoMemoryview = _testRecvFromIntoArray
1488
Christian Heimes043d6f62008-01-07 17:19:16 +00001489
1490TIPC_STYPE = 2000
1491TIPC_LOWER = 200
1492TIPC_UPPER = 210
1493
1494def isTipcAvailable():
1495 """Check if the TIPC module is loaded
1496
1497 The TIPC module is not loaded automatically on Ubuntu and probably
1498 other Linux distros.
1499 """
1500 if not hasattr(socket, "AF_TIPC"):
1501 return False
1502 if not os.path.isfile("/proc/modules"):
1503 return False
1504 with open("/proc/modules") as f:
1505 for line in f:
1506 if line.startswith("tipc "):
1507 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001508 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001509 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1510 return False
1511
1512class TIPCTest (unittest.TestCase):
1513 def testRDM(self):
1514 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1515 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1516
1517 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1518 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1519 TIPC_LOWER, TIPC_UPPER)
1520 srv.bind(srvaddr)
1521
1522 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1523 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1524 cli.sendto(MSG, sendaddr)
1525
1526 msg, recvaddr = srv.recvfrom(1024)
1527
1528 self.assertEqual(cli.getsockname(), recvaddr)
1529 self.assertEqual(msg, MSG)
1530
1531
1532class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1533 def __init__(self, methodName = 'runTest'):
1534 unittest.TestCase.__init__(self, methodName = methodName)
1535 ThreadableTest.__init__(self)
1536
1537 def setUp(self):
1538 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1539 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1540 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1541 TIPC_LOWER, TIPC_UPPER)
1542 self.srv.bind(srvaddr)
1543 self.srv.listen(5)
1544 self.serverExplicitReady()
1545 self.conn, self.connaddr = self.srv.accept()
1546
1547 def clientSetUp(self):
1548 # The is a hittable race between serverExplicitReady() and the
1549 # accept() call; sleep a little while to avoid it, otherwise
1550 # we could get an exception
1551 time.sleep(0.1)
1552 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1553 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1554 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1555 self.cli.connect(addr)
1556 self.cliaddr = self.cli.getsockname()
1557
1558 def testStream(self):
1559 msg = self.conn.recv(1024)
1560 self.assertEqual(msg, MSG)
1561 self.assertEqual(self.cliaddr, self.connaddr)
1562
1563 def _testStream(self):
1564 self.cli.send(MSG)
1565 self.cli.close()
1566
1567
Guido van Rossumb995eb72002-07-31 16:08:40 +00001568def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001569 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Ronald Oussoren94f25282010-05-05 19:11:21 +00001570 TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, UDPTimeoutTest ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001571
1572 tests.extend([
1573 NonBlockingTCPTests,
1574 FileObjectClassTestCase,
Gregory P. Smithaafdca82010-01-04 04:50:36 +00001575 FileObjectInterruptedTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001576 UnbufferedFileObjectClassTestCase,
1577 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001578 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001579 NetworkConnectionNoServer,
1580 NetworkConnectionAttributesTest,
1581 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001582 ])
Dave Cole331708b2004-08-09 04:51:41 +00001583 if hasattr(socket, "socketpair"):
1584 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001585 if sys.platform == 'linux2':
1586 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001587 if isTipcAvailable():
1588 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001589 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001590
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001591 thread_info = support.threading_setup()
1592 support.run_unittest(*tests)
1593 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001594
1595if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001596 test_main()