blob: 67c541388bfd02b95475081fe158a8cff43f7221 [file] [log] [blame]
Guido van Rossum24e4af82002-06-12 19:18:08 +00001#!/usr/bin/env python
Barry Warsawcf3d4b51997-01-03 20:03:32 +00002
Guido van Rossum24e4af82002-06-12 19:18:08 +00003import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test import support
Barry Warsawcf3d4b51997-01-03 20:03:32 +00005
Christian Heimes5e696852008-04-09 08:37:03 +00006import errno
Barry Warsawcf3d4b51997-01-03 20:03:32 +00007import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00008import select
Georg Brandl2067bfd2008-05-25 13:05:15 +00009import _thread as thread
10import threading
Christian Heimesbbe741d2008-03-28 10:53:29 +000011import time
12import traceback
Alexandre Vassalottif260e442008-05-11 19:59:59 +000013import queue
Jack Jansen522e7692002-09-06 21:57:50 +000014import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000015import os
16import array
Antoine Pitrou4d7979b2010-09-07 21:22:56 +000017import contextlib
Raymond Hettinger027bb632004-05-31 03:09:25 +000018from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019import signal
Antoine Pitrou08ae02f2010-09-27 18:14:43 +000020import math
Barry Warsawcf3d4b51997-01-03 20:03:32 +000021
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +000022def try_address(host, port=0, family=socket.AF_INET):
23 """Try to bind a socket on the given host:port and return True
24 if that has been possible."""
25 try:
26 sock = socket.socket(family, socket.SOCK_STREAM)
27 sock.bind((host, port))
28 except (socket.error, socket.gaierror):
29 return False
30 else:
31 sock.close()
32 return True
33
Benjamin Petersonee8712c2008-05-20 21:35:26 +000034HOST = support.HOST
Antoine Pitrou674f4002010-10-13 16:25:33 +000035MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf8') ## test unicode string and carriage return
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +000036SUPPORTS_IPV6 = socket.has_ipv6 and try_address('::1', family=socket.AF_INET6)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000037
Guido van Rossum24e4af82002-06-12 19:18:08 +000038class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000039
Guido van Rossum24e4af82002-06-12 19:18:08 +000040 def setUp(self):
41 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000042 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000043 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000044
Guido van Rossum24e4af82002-06-12 19:18:08 +000045 def tearDown(self):
46 self.serv.close()
47 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000048
Guido van Rossum24e4af82002-06-12 19:18:08 +000049class SocketUDPTest(unittest.TestCase):
50
51 def setUp(self):
52 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000053 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000054
55 def tearDown(self):
56 self.serv.close()
57 self.serv = None
58
59class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000060 """Threadable Test class
61
62 The ThreadableTest class makes it easy to create a threaded
63 client/server pair from an existing unit test. To create a
64 new threaded class from an existing unit test, use multiple
65 inheritance:
66
67 class NewClass (OldClass, ThreadableTest):
68 pass
69
70 This class defines two new fixture functions with obvious
71 purposes for overriding:
72
73 clientSetUp ()
74 clientTearDown ()
75
76 Any new test functions within the class must then define
77 tests in pairs, where the test name is preceeded with a
78 '_' to indicate the client portion of the test. Ex:
79
80 def testFoo(self):
81 # Server portion
82
83 def _testFoo(self):
84 # Client portion
85
86 Any exceptions raised by the clients during their tests
87 are caught and transferred to the main thread to alert
88 the testing framework.
89
90 Note, the server setup function cannot call any blocking
91 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +000092 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000093 the blocking call (such as in setting up a client/server
94 connection and performing the accept() in setUp().
95 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000096
97 def __init__(self):
98 # Swap the true setup function
99 self.__setUp = self.setUp
100 self.__tearDown = self.tearDown
101 self.setUp = self._setUp
102 self.tearDown = self._tearDown
103
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000104 def serverExplicitReady(self):
105 """This method allows the server to explicitly indicate that
106 it wants the client thread to proceed. This is useful if the
107 server is about to execute a blocking routine that is
108 dependent upon the client thread during its setup routine."""
109 self.server_ready.set()
110
Guido van Rossum24e4af82002-06-12 19:18:08 +0000111 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000112 self.server_ready = threading.Event()
113 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000114 self.done = threading.Event()
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000115 self.queue = queue.Queue(1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000116
117 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000118 methodname = self.id()
119 i = methodname.rfind('.')
120 methodname = methodname[i+1:]
121 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000122 self.client_thread = thread.start_new_thread(
123 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000124
125 self.__setUp()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000126 if not self.server_ready.is_set():
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000127 self.server_ready.set()
128 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000129
130 def _tearDown(self):
131 self.__tearDown()
132 self.done.wait()
133
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000134 if self.queue.qsize():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000135 msg = self.queue.get()
136 self.fail(msg)
137
138 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000139 self.server_ready.wait()
140 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000141 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000142 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000143 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000144 try:
145 test_func()
Guido van Rossumb940e112007-01-10 16:19:56 +0000146 except Exception as strerror:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000147 self.queue.put(strerror)
148 self.clientTearDown()
149
150 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000151 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000152
153 def clientTearDown(self):
154 self.done.set()
155 thread.exit()
156
157class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
158
159 def __init__(self, methodName='runTest'):
160 SocketTCPTest.__init__(self, methodName=methodName)
161 ThreadableTest.__init__(self)
162
163 def clientSetUp(self):
164 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
165
166 def clientTearDown(self):
167 self.cli.close()
168 self.cli = None
169 ThreadableTest.clientTearDown(self)
170
171class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
172
173 def __init__(self, methodName='runTest'):
174 SocketUDPTest.__init__(self, methodName=methodName)
175 ThreadableTest.__init__(self)
176
177 def clientSetUp(self):
178 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
179
Brian Curtin8f8ed942010-11-04 03:49:29 +0000180 def clientTearDown(self):
181 self.cli.close()
182 self.cli = None
183 ThreadableTest.clientTearDown(self)
184
Guido van Rossum24e4af82002-06-12 19:18:08 +0000185class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000186 """Socket tests for client-server connection.
187
188 self.cli_conn is a client socket connected to the server. The
189 setUp() method guarantees that it is connected to the server.
190 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000191
192 def __init__(self, methodName='runTest'):
193 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
194
195 def setUp(self):
196 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000197 # Indicate explicitly we're ready for the client thread to
198 # proceed and then perform the blocking call to accept
199 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000200 conn, addr = self.serv.accept()
201 self.cli_conn = conn
202
203 def tearDown(self):
204 self.cli_conn.close()
205 self.cli_conn = None
206 ThreadedTCPSocketTest.tearDown(self)
207
208 def clientSetUp(self):
209 ThreadedTCPSocketTest.clientSetUp(self)
Christian Heimes5e696852008-04-09 08:37:03 +0000210 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000211 self.serv_conn = self.cli
212
213 def clientTearDown(self):
214 self.serv_conn.close()
215 self.serv_conn = None
216 ThreadedTCPSocketTest.clientTearDown(self)
217
Dave Cole331708b2004-08-09 04:51:41 +0000218class SocketPairTest(unittest.TestCase, ThreadableTest):
219
220 def __init__(self, methodName='runTest'):
221 unittest.TestCase.__init__(self, methodName=methodName)
222 ThreadableTest.__init__(self)
223
224 def setUp(self):
225 self.serv, self.cli = socket.socketpair()
226
227 def tearDown(self):
228 self.serv.close()
229 self.serv = None
230
231 def clientSetUp(self):
232 pass
233
234 def clientTearDown(self):
235 self.cli.close()
236 self.cli = None
237 ThreadableTest.clientTearDown(self)
238
Tim Peters494aaee2004-08-09 18:54:11 +0000239
Guido van Rossum24e4af82002-06-12 19:18:08 +0000240#######################################################################
241## Begin Tests
242
243class GeneralModuleTests(unittest.TestCase):
244
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000245 def test_repr(self):
246 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlab91fde2009-08-13 08:51:18 +0000247 self.assertTrue(repr(s).startswith("<socket.socket object"))
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000248
Raymond Hettinger027bb632004-05-31 03:09:25 +0000249 def test_weakref(self):
250 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
251 p = proxy(s)
252 self.assertEqual(p.fileno(), s.fileno())
253 s.close()
254 s = None
255 try:
256 p.fileno()
257 except ReferenceError:
258 pass
259 else:
260 self.fail('Socket proxy still exists')
261
Guido van Rossum24e4af82002-06-12 19:18:08 +0000262 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000263 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000264 def raise_error(*args, **kwargs):
265 raise socket.error
266 def raise_herror(*args, **kwargs):
267 raise socket.herror
268 def raise_gaierror(*args, **kwargs):
269 raise socket.gaierror
Georg Brandlab91fde2009-08-13 08:51:18 +0000270 self.assertRaises(socket.error, raise_error,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000271 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000272 self.assertRaises(socket.error, raise_herror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000273 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000274 self.assertRaises(socket.error, raise_gaierror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000275 "Error raising socket exception.")
276
277 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000278 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000279 socket.AF_INET
280 socket.SOCK_STREAM
281 socket.SOCK_DGRAM
282 socket.SOCK_RAW
283 socket.SOCK_RDM
284 socket.SOCK_SEQPACKET
285 socket.SOL_SOCKET
286 socket.SO_REUSEADDR
287
Guido van Rossum654c11e2002-06-13 20:24:17 +0000288 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000289 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000290 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000291 try:
292 ip = socket.gethostbyname(hostname)
293 except socket.error:
294 # Probably name lookup wasn't set up right; skip this test
295 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000296 self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000297 try:
298 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
299 except socket.error:
300 # Probably a similar problem as above; skip this test
301 return
Brett Cannon01668a12005-03-11 00:04:17 +0000302 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000303 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000304 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000305 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000306
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000307 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000308 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000309 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000310 try:
311 # On some versions, this loses a reference
312 orig = sys.getrefcount(__name__)
313 socket.getnameinfo(__name__,0)
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +0000314 except TypeError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000315 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000316 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000317
Guido van Rossum24e4af82002-06-12 19:18:08 +0000318 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000319 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000320 try:
321 # On some versions, this crashes the interpreter.
322 socket.getnameinfo(('x', 0, 0, 0), 0)
323 except socket.error:
324 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000325
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000326 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000327 # This just checks that htons etc. are their own inverse,
328 # when looking at the lower 16 or 32 bits.
329 sizes = {socket.htonl: 32, socket.ntohl: 32,
330 socket.htons: 16, socket.ntohs: 16}
331 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000332 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000333 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
334 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000335
Guido van Rossuma2627af2002-09-14 00:58:46 +0000336 swapped = func(mask)
337 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000338 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000339
Guido van Rossum018919a2007-01-15 00:07:32 +0000340 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000341 good_values = [ 1, 2, 3, 1, 2, 3 ]
342 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000343 for k in good_values:
344 socket.ntohl(k)
345 socket.ntohs(k)
346 socket.htonl(k)
347 socket.htons(k)
348 for k in bad_values:
349 self.assertRaises(OverflowError, socket.ntohl, k)
350 self.assertRaises(OverflowError, socket.ntohs, k)
351 self.assertRaises(OverflowError, socket.htonl, k)
352 self.assertRaises(OverflowError, socket.htons, k)
353
Barry Warsaw11b91a02004-06-28 00:50:43 +0000354 def testGetServBy(self):
355 eq = self.assertEqual
356 # Find one service that exists, then check all the related interfaces.
357 # I've ordered this by protocols that have both a tcp and udp
358 # protocol, at least for modern Linuxes.
Gregory P. Smith397cd8a2010-10-17 04:23:21 +0000359 if (sys.platform.startswith('linux') or
360 sys.platform.startswith('freebsd') or
361 sys.platform.startswith('netbsd') or
362 sys.platform == 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000363 # avoid the 'echo' service on this platform, as there is an
364 # assumption breaking non-standard port/protocol entry
365 services = ('daytime', 'qotd', 'domain')
366 else:
367 services = ('echo', 'daytime', 'domain')
368 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000369 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000370 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000371 break
372 except socket.error:
373 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000374 else:
375 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000376 # Try same call with optional protocol omitted
377 port2 = socket.getservbyname(service)
378 eq(port, port2)
379 # Try udp, but don't barf it it doesn't exist
380 try:
381 udpport = socket.getservbyname(service, 'udp')
382 except socket.error:
383 udpport = None
384 else:
385 eq(udpport, port)
386 # Now make sure the lookup by port returns the same service name
387 eq(socket.getservbyport(port2), service)
388 eq(socket.getservbyport(port, 'tcp'), service)
389 if udpport is not None:
390 eq(socket.getservbyport(udpport, 'udp'), service)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000391 # Make sure getservbyport does not accept out of range ports.
392 self.assertRaises(OverflowError, socket.getservbyport, -1)
393 self.assertRaises(OverflowError, socket.getservbyport, 65536)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000394
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000395 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000396 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000397 # The default timeout should initially be None
398 self.assertEqual(socket.getdefaulttimeout(), None)
399 s = socket.socket()
400 self.assertEqual(s.gettimeout(), None)
401 s.close()
402
403 # Set the default timeout to 10, and see if it propagates
404 socket.setdefaulttimeout(10)
405 self.assertEqual(socket.getdefaulttimeout(), 10)
406 s = socket.socket()
407 self.assertEqual(s.gettimeout(), 10)
408 s.close()
409
410 # Reset the default timeout to None, and see if it propagates
411 socket.setdefaulttimeout(None)
412 self.assertEqual(socket.getdefaulttimeout(), None)
413 s = socket.socket()
414 self.assertEqual(s.gettimeout(), None)
415 s.close()
416
417 # Check that setting it to an invalid value raises ValueError
418 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
419
420 # Check that setting it to an invalid type raises TypeError
421 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
422
Benjamin Petersonf91df042009-02-13 02:50:59 +0000423 def testIPv4_inet_aton_fourbytes(self):
424 if not hasattr(socket, 'inet_aton'):
425 return # No inet_aton, nothing to check
426 # Test that issue1008086 and issue767150 are fixed.
427 # It must return 4 bytes.
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000428 self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0'))
429 self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255'))
Benjamin Petersonf91df042009-02-13 02:50:59 +0000430
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000431 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000432 if not hasattr(socket, 'inet_pton'):
433 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000434 from socket import inet_aton as f, inet_pton, AF_INET
435 g = lambda a: inet_pton(AF_INET, a)
436
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000437 self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0'))
438 self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0'))
439 self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
440 self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4'))
441 self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000442
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000443 self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0'))
444 self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0'))
445 self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
446 self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000447
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000448 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000449 if not hasattr(socket, 'inet_pton'):
450 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000451 try:
452 from socket import inet_pton, AF_INET6, has_ipv6
453 if not has_ipv6:
454 return
455 except ImportError:
456 return
457 f = lambda a: inet_pton(AF_INET6, a)
458
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000459 self.assertEqual(b'\x00' * 16, f('::'))
460 self.assertEqual(b'\x00' * 16, f('0::0'))
461 self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::'))
462 self.assertEqual(
Guido van Rossum67180622007-07-10 07:29:12 +0000463 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 +0000464 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
465 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000466
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000467 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000468 if not hasattr(socket, 'inet_ntop'):
469 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000470 from socket import inet_ntoa as f, inet_ntop, AF_INET
471 g = lambda a: inet_ntop(AF_INET, a)
472
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000473 self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00'))
474 self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
475 self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff'))
476 self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000477
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000478 self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00'))
479 self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
480 self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000481
482 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000483 if not hasattr(socket, 'inet_ntop'):
484 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000485 try:
486 from socket import inet_ntop, AF_INET6, has_ipv6
487 if not has_ipv6:
488 return
489 except ImportError:
490 return
491 f = lambda a: inet_ntop(AF_INET6, a)
492
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000493 self.assertEqual('::', f(b'\x00' * 16))
494 self.assertEqual('::1', f(b'\x00' * 15 + b'\x01'))
495 self.assertEqual(
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000496 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000497 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 +0000498 )
499
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000500 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000501
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000502 def _get_unused_port(self, bind_address='0.0.0.0'):
503 """Use a temporary socket to elicit an unused ephemeral port.
Christian Heimes5e696852008-04-09 08:37:03 +0000504
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000505 Args:
506 bind_address: Hostname or IP address to search for a port on.
507
508 Returns: A most likely to be unused port.
509 """
510 tempsock = socket.socket()
511 tempsock.bind((bind_address, 0))
512 host, port = tempsock.getsockname()
513 tempsock.close()
514 return port
515
516 def testSockName(self):
517 # Testing getsockname()
518 port = self._get_unused_port()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000519 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Christian Heimes5e696852008-04-09 08:37:03 +0000520 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000521 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000522 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
523 # it reasonable to get the host's addr in addition to 0.0.0.0.
524 # At least for eCos. This is required for the S/390 to pass.
Georg Brandlf65e25b2010-11-26 09:05:43 +0000525 try:
526 my_ip_addr = socket.gethostbyname(socket.gethostname())
527 except socket.error:
528 # Probably name lookup wasn't set up right; skip this test
529 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000530 self.assertTrue(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +0000531 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000532
533 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000534 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000535 # We know a socket should start without reuse==0
536 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
537 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000538 self.assertFalse(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000539
540 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000541 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000542 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
543 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
544 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000545 self.assertFalse(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000546
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000547 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000548 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000549 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
550 sock.settimeout(1)
551 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000552 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000553
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000554 def testNewAttributes(self):
555 # testing .family, .type and .protocol
556 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
557 self.assertEqual(sock.family, socket.AF_INET)
558 self.assertEqual(sock.type, socket.SOCK_STREAM)
559 self.assertEqual(sock.proto, 0)
560 sock.close()
561
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000562 def test_getsockaddrarg(self):
563 host = '0.0.0.0'
564 port = self._get_unused_port(bind_address=host)
565 big_port = port + 65536
566 neg_port = port - 65536
567 sock = socket.socket()
568 try:
569 self.assertRaises(OverflowError, sock.bind, (host, big_port))
570 self.assertRaises(OverflowError, sock.bind, (host, neg_port))
571 sock.bind((host, port))
572 finally:
573 sock.close()
574
Christian Heimesfaf2f632008-01-06 16:59:19 +0000575 def test_sock_ioctl(self):
576 if os.name != "nt":
577 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000578 self.assertTrue(hasattr(socket.socket, 'ioctl'))
579 self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
580 self.assertTrue(hasattr(socket, 'RCVALL_ON'))
581 self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
Christian Heimesfaf2f632008-01-06 16:59:19 +0000582
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000583 def testGetaddrinfo(self):
584 try:
585 socket.getaddrinfo('localhost', 80)
586 except socket.gaierror as err:
587 if err.errno == socket.EAI_SERVICE:
588 # see http://bugs.python.org/issue1282647
589 self.skipTest("buggy libc version")
590 raise
591 # len of every sequence is supposed to be == 5
592 for info in socket.getaddrinfo(HOST, None):
593 self.assertEqual(len(info), 5)
594 # host can be a domain name, a string representation of an
595 # IPv4/v6 address or None
596 socket.getaddrinfo('localhost', 80)
597 socket.getaddrinfo('127.0.0.1', 80)
598 socket.getaddrinfo(None, 80)
599 if SUPPORTS_IPV6:
600 socket.getaddrinfo('::1', 80)
601 # port can be a string service name such as "http", a numeric
602 # port number or None
603 socket.getaddrinfo(HOST, "http")
604 socket.getaddrinfo(HOST, 80)
605 socket.getaddrinfo(HOST, None)
606 # test family and socktype filters
607 infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
608 for family, _, _, _, _ in infos:
609 self.assertEqual(family, socket.AF_INET)
610 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
611 for _, socktype, _, _, _ in infos:
612 self.assertEqual(socktype, socket.SOCK_STREAM)
613 # test proto and flags arguments
Giampaolo Rodolà5b37ce62010-08-16 05:09:31 +0000614 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000615 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
616 # a server willing to support both IPv4 and IPv6 will
617 # usually do this
618 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
619 socket.AI_PASSIVE)
620
Christian Heimesfaf2f632008-01-06 16:59:19 +0000621
Antoine Pitrou08ae02f2010-09-27 18:14:43 +0000622 def check_sendall_interrupted(self, with_timeout):
623 # socketpair() is not stricly required, but it makes things easier.
624 if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
625 self.skipTest("signal.alarm and socket.socketpair required for this test")
626 # Our signal handlers clobber the C errno by calling a math function
627 # with an invalid domain value.
628 def ok_handler(*args):
629 self.assertRaises(ValueError, math.acosh, 0)
630 def raising_handler(*args):
631 self.assertRaises(ValueError, math.acosh, 0)
632 1 // 0
633 c, s = socket.socketpair()
634 old_alarm = signal.signal(signal.SIGALRM, raising_handler)
635 try:
636 if with_timeout:
637 # Just above the one second minimum for signal.alarm
638 c.settimeout(1.5)
639 with self.assertRaises(ZeroDivisionError):
640 signal.alarm(1)
641 c.sendall(b"x" * (1024**2))
642 if with_timeout:
643 signal.signal(signal.SIGALRM, ok_handler)
644 signal.alarm(1)
645 self.assertRaises(socket.timeout, c.sendall, b"x" * (1024**2))
646 finally:
647 signal.signal(signal.SIGALRM, old_alarm)
648 c.close()
649 s.close()
650
651 def test_sendall_interrupted(self):
652 self.check_sendall_interrupted(False)
653
654 def test_sendall_interrupted_with_timeout(self):
655 self.check_sendall_interrupted(True)
656
657
Guido van Rossum24e4af82002-06-12 19:18:08 +0000658class BasicTCPTest(SocketConnectedTest):
659
660 def __init__(self, methodName='runTest'):
661 SocketConnectedTest.__init__(self, methodName=methodName)
662
663 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000664 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000665 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000666 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000667
668 def _testRecv(self):
669 self.serv_conn.send(MSG)
670
671 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000672 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000673 seg1 = self.cli_conn.recv(len(MSG) - 3)
674 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000675 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000676 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000677
678 def _testOverFlowRecv(self):
679 self.serv_conn.send(MSG)
680
681 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000682 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000683 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000684 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000685
686 def _testRecvFrom(self):
687 self.serv_conn.send(MSG)
688
689 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000690 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000691 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
692 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000693 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000694 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000695
696 def _testOverFlowRecvFrom(self):
697 self.serv_conn.send(MSG)
698
699 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000700 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000701 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000702 while 1:
703 read = self.cli_conn.recv(1024)
704 if not read:
705 break
Guido van Rossume531e292002-08-08 20:28:34 +0000706 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000707 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000708
709 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000710 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000711 self.serv_conn.sendall(big_chunk)
712
713 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000714 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000715 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000716 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000717 fd = self.cli_conn.fileno()
718 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
719 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000720 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000721
722 def _testFromFd(self):
723 self.serv_conn.send(MSG)
724
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000725 def testDup(self):
726 # Testing dup()
727 sock = self.cli_conn.dup()
728 msg = sock.recv(1024)
729 self.assertEqual(msg, MSG)
730
731 def _testDup(self):
732 self.serv_conn.send(MSG)
733
Guido van Rossum24e4af82002-06-12 19:18:08 +0000734 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000735 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000736 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000737 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +0000738 # wait for _testShutdown to finish: on OS X, when the server
739 # closes the connection the client also becomes disconnected,
740 # and the client's shutdown call will fail. (Issue #4397.)
741 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000742
743 def _testShutdown(self):
744 self.serv_conn.send(MSG)
745 self.serv_conn.shutdown(2)
746
747class BasicUDPTest(ThreadedUDPSocketTest):
748
749 def __init__(self, methodName='runTest'):
750 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
751
752 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000753 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000754 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000755 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000756
757 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000758 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000759
Guido van Rossum1c938012002-06-12 21:17:20 +0000760 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000761 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000762 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000763 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000764
Guido van Rossum1c938012002-06-12 21:17:20 +0000765 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000766 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000767
Guido van Rossumd8faa362007-04-27 19:54:29 +0000768 def testRecvFromNegative(self):
769 # Negative lengths passed to recvfrom should give ValueError.
770 self.assertRaises(ValueError, self.serv.recvfrom, -1)
771
772 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000773 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000774
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000775class TCPCloserTest(ThreadedTCPSocketTest):
776
777 def testClose(self):
778 conn, addr = self.serv.accept()
779 conn.close()
780
781 sd = self.cli
782 read, write, err = select.select([sd], [], [], 1.0)
783 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000784 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000785
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000786 # Calling close() many times should be safe.
787 conn.close()
788 conn.close()
789
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000790 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000791 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000792 time.sleep(1.0)
793
Dave Cole331708b2004-08-09 04:51:41 +0000794class BasicSocketPairTest(SocketPairTest):
795
796 def __init__(self, methodName='runTest'):
797 SocketPairTest.__init__(self, methodName=methodName)
798
799 def testRecv(self):
800 msg = self.serv.recv(1024)
801 self.assertEqual(msg, MSG)
802
803 def _testRecv(self):
804 self.cli.send(MSG)
805
806 def testSend(self):
807 self.serv.send(MSG)
808
809 def _testSend(self):
810 msg = self.cli.recv(1024)
811 self.assertEqual(msg, MSG)
812
Guido van Rossum24e4af82002-06-12 19:18:08 +0000813class NonBlockingTCPTests(ThreadedTCPSocketTest):
814
815 def __init__(self, methodName='runTest'):
816 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
817
818 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000819 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000820 self.serv.setblocking(0)
821 start = time.time()
822 try:
823 self.serv.accept()
824 except socket.error:
825 pass
826 end = time.time()
Georg Brandlab91fde2009-08-13 08:51:18 +0000827 self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000828
829 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000830 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000831
Guido van Rossum24e4af82002-06-12 19:18:08 +0000832 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000833 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000834 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000835 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000836 conn, addr = self.serv.accept()
837 except socket.error:
838 pass
839 else:
840 self.fail("Error trying to do non-blocking accept.")
841 read, write, err = select.select([self.serv], [], [])
842 if self.serv in read:
843 conn, addr = self.serv.accept()
844 else:
845 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000846
Guido van Rossum24e4af82002-06-12 19:18:08 +0000847 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000848 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +0000849 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000850
851 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000852 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000853 conn, addr = self.serv.accept()
854
855 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000856 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +0000857 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000858
859 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000860 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000861 conn, addr = self.serv.accept()
862 conn.setblocking(0)
863 try:
864 msg = conn.recv(len(MSG))
865 except socket.error:
866 pass
867 else:
868 self.fail("Error trying to do non-blocking recv.")
869 read, write, err = select.select([conn], [], [])
870 if conn in read:
871 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000872 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000873 else:
874 self.fail("Error during select call to non-blocking socket.")
875
876 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000877 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000878 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000879 self.cli.send(MSG)
880
881class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000882 """Unit tests for the object returned by socket.makefile()
883
Antoine Pitrou674f4002010-10-13 16:25:33 +0000884 self.read_file is the io object returned by makefile() on
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000885 the client connection. You can read from this file to
886 get output from the server.
887
Antoine Pitrou674f4002010-10-13 16:25:33 +0000888 self.write_file is the io object returned by makefile() on the
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000889 server connection. You can write to this file to send output
890 to the client.
891 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000892
Guido van Rossume9f66142002-08-07 15:46:19 +0000893 bufsize = -1 # Use default buffer size
Antoine Pitrou674f4002010-10-13 16:25:33 +0000894 encoding = 'utf8'
895 errors = 'strict'
896 newline = None
897
898 read_mode = 'rb'
899 read_msg = MSG
900 write_mode = 'wb'
901 write_msg = MSG
Guido van Rossume9f66142002-08-07 15:46:19 +0000902
Guido van Rossum24e4af82002-06-12 19:18:08 +0000903 def __init__(self, methodName='runTest'):
904 SocketConnectedTest.__init__(self, methodName=methodName)
905
906 def setUp(self):
907 SocketConnectedTest.setUp(self)
Antoine Pitrou674f4002010-10-13 16:25:33 +0000908 self.read_file = self.cli_conn.makefile(
909 self.read_mode, self.bufsize,
910 encoding = self.encoding,
911 errors = self.errors,
912 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000913
914 def tearDown(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000915 self.read_file.close()
916 self.assertTrue(self.read_file.closed)
917 self.read_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +0000918 SocketConnectedTest.tearDown(self)
919
920 def clientSetUp(self):
921 SocketConnectedTest.clientSetUp(self)
Antoine Pitrou674f4002010-10-13 16:25:33 +0000922 self.write_file = self.serv_conn.makefile(
923 self.write_mode, self.bufsize,
924 encoding = self.encoding,
925 errors = self.errors,
926 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000927
928 def clientTearDown(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000929 self.write_file.close()
930 self.assertTrue(self.write_file.closed)
931 self.write_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +0000932 SocketConnectedTest.clientTearDown(self)
933
934 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000935 # Performing small file read test
Antoine Pitrou674f4002010-10-13 16:25:33 +0000936 first_seg = self.read_file.read(len(self.read_msg)-3)
937 second_seg = self.read_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000938 msg = first_seg + second_seg
Antoine Pitrou674f4002010-10-13 16:25:33 +0000939 self.assertEqual(msg, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000940
941 def _testSmallRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000942 self.write_file.write(self.write_msg)
943 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000944
Guido van Rossum8c943832002-08-08 01:00:28 +0000945 def testFullRead(self):
946 # read until EOF
Antoine Pitrou674f4002010-10-13 16:25:33 +0000947 msg = self.read_file.read()
948 self.assertEqual(msg, self.read_msg)
Guido van Rossum8c943832002-08-08 01:00:28 +0000949
950 def _testFullRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000951 self.write_file.write(self.write_msg)
952 self.write_file.close()
Guido van Rossum8c943832002-08-08 01:00:28 +0000953
Guido van Rossum24e4af82002-06-12 19:18:08 +0000954 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000955 # Performing unbuffered file read test
Antoine Pitrou674f4002010-10-13 16:25:33 +0000956 buf = type(self.read_msg)()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000957 while 1:
Antoine Pitrou674f4002010-10-13 16:25:33 +0000958 char = self.read_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000959 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000960 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000961 buf += char
Antoine Pitrou674f4002010-10-13 16:25:33 +0000962 self.assertEqual(buf, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000963
964 def _testUnbufferedRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000965 self.write_file.write(self.write_msg)
966 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000967
968 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000969 # Performing file readline test
Antoine Pitrou674f4002010-10-13 16:25:33 +0000970 line = self.read_file.readline()
971 self.assertEqual(line, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000972
973 def _testReadline(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000974 self.write_file.write(self.write_msg)
975 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000976
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000977 def testCloseAfterMakefile(self):
978 # The file returned by makefile should keep the socket open.
979 self.cli_conn.close()
980 # read until EOF
Antoine Pitrou674f4002010-10-13 16:25:33 +0000981 msg = self.read_file.read()
982 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000983
984 def _testCloseAfterMakefile(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000985 self.write_file.write(self.write_msg)
986 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000987
988 def testMakefileAfterMakefileClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000989 self.read_file.close()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000990 msg = self.cli_conn.recv(len(MSG))
Antoine Pitrou674f4002010-10-13 16:25:33 +0000991 if isinstance(self.read_msg, str):
992 msg = msg.decode()
993 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000994
995 def _testMakefileAfterMakefileClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000996 self.write_file.write(self.write_msg)
997 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000998
Tim Peters116d83c2004-03-28 02:20:45 +0000999 def testClosedAttr(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001000 self.assertTrue(not self.read_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00001001
1002 def _testClosedAttr(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001003 self.assertTrue(not self.write_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00001004
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001005 def testAttributes(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001006 self.assertEqual(self.read_file.mode, self.read_mode)
1007 self.assertEqual(self.read_file.name, self.cli_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001008
1009 def _testAttributes(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001010 self.assertEqual(self.write_file.mode, self.write_mode)
1011 self.assertEqual(self.write_file.name, self.serv_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001012
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001013 def testRealClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001014 self.read_file.close()
1015 self.assertRaises(ValueError, self.read_file.fileno)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001016 self.cli_conn.close()
1017 self.assertRaises(socket.error, self.cli_conn.getsockname)
1018
1019 def _testRealClose(self):
1020 pass
1021
1022
Guido van Rossume9f66142002-08-07 15:46:19 +00001023class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
1024
1025 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +00001026
Guido van Rossume9f66142002-08-07 15:46:19 +00001027 In this case (and in this case only), it should be possible to
1028 create a file object, read a line from it, create another file
1029 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +00001030 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +00001031 when reading multiple requests from the same socket."""
1032
1033 bufsize = 0 # Use unbuffered mode
1034
1035 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001036 # Read a line, create a new file object, read another line with it
Antoine Pitrou674f4002010-10-13 16:25:33 +00001037 line = self.read_file.readline() # first line
1038 self.assertEqual(line, b"A. " + self.write_msg) # first line
1039 self.read_file = self.cli_conn.makefile('rb', 0)
1040 line = self.read_file.readline() # second line
1041 self.assertEqual(line, b"B. " + self.write_msg) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +00001042
1043 def _testUnbufferedReadline(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001044 self.write_file.write(b"A. " + self.write_msg)
1045 self.write_file.write(b"B. " + self.write_msg)
1046 self.write_file.flush()
Guido van Rossume9f66142002-08-07 15:46:19 +00001047
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001048 def testMakefileClose(self):
1049 # The file returned by makefile should keep the socket open...
1050 self.cli_conn.close()
1051 msg = self.cli_conn.recv(1024)
Antoine Pitrou674f4002010-10-13 16:25:33 +00001052 self.assertEqual(msg, self.read_msg)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001053 # ...until the file is itself closed
Antoine Pitrou674f4002010-10-13 16:25:33 +00001054 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001055 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
1056
1057 def _testMakefileClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001058 self.write_file.write(self.write_msg)
1059 self.write_file.flush()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001060
1061 def testMakefileCloseSocketDestroy(self):
1062 refcount_before = sys.getrefcount(self.cli_conn)
Antoine Pitrou674f4002010-10-13 16:25:33 +00001063 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001064 refcount_after = sys.getrefcount(self.cli_conn)
1065 self.assertEqual(refcount_before - 1, refcount_after)
1066
1067 def _testMakefileCloseSocketDestroy(self):
1068 pass
1069
1070
Guido van Rossum8c943832002-08-08 01:00:28 +00001071class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1072
1073 bufsize = 1 # Default-buffered for reading; line-buffered for writing
1074
1075
1076class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1077
1078 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +00001079
Thomas Woutersb2137042007-02-01 18:02:27 +00001080
Antoine Pitrou674f4002010-10-13 16:25:33 +00001081class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase):
1082 """Tests for socket.makefile() in text mode (rather than binary)"""
1083
1084 read_mode = 'r'
1085 read_msg = MSG.decode('utf8')
1086 write_mode = 'wb'
1087 write_msg = MSG
1088 newline = ''
1089
1090
1091class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase):
1092 """Tests for socket.makefile() in text mode (rather than binary)"""
1093
1094 read_mode = 'rb'
1095 read_msg = MSG
1096 write_mode = 'w'
1097 write_msg = MSG.decode('utf8')
1098 newline = ''
1099
1100
1101class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase):
1102 """Tests for socket.makefile() in text mode (rather than binary)"""
1103
1104 read_mode = 'r'
1105 read_msg = MSG.decode('utf8')
1106 write_mode = 'w'
1107 write_msg = MSG.decode('utf8')
1108 newline = ''
1109
1110
Guido van Rossumd8faa362007-04-27 19:54:29 +00001111class NetworkConnectionTest(object):
1112 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001113
Guido van Rossumd8faa362007-04-27 19:54:29 +00001114 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001115 # We're inherited below by BasicTCPTest2, which also inherits
1116 # BasicTCPTest, which defines self.port referenced below.
1117 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001118 self.serv_conn = self.cli
1119
1120class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
1121 """Tests that NetworkConnection does not break existing TCP functionality.
1122 """
1123
1124class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001125
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001126 class MockSocket(socket.socket):
1127 def connect(self, *args):
1128 raise socket.timeout('timed out')
1129
1130 @contextlib.contextmanager
1131 def mocked_socket_module(self):
1132 """Return a socket which times out on connect"""
1133 old_socket = socket.socket
1134 socket.socket = self.MockSocket
1135 try:
1136 yield
1137 finally:
1138 socket.socket = old_socket
1139
1140 def test_connect(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001141 port = support.find_unused_port()
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001142 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1143 try:
1144 cli.connect((HOST, port))
1145 except socket.error as err:
1146 self.assertEqual(err.errno, errno.ECONNREFUSED)
1147 else:
1148 self.fail("socket.error not raised")
1149
1150 def test_create_connection(self):
1151 # Issue #9792: errors raised by create_connection() should have
1152 # a proper errno attribute.
1153 port = support.find_unused_port()
1154 try:
1155 socket.create_connection((HOST, port))
1156 except socket.error as err:
1157 self.assertEqual(err.errno, errno.ECONNREFUSED)
1158 else:
1159 self.fail("socket.error not raised")
1160
1161 def test_create_connection_timeout(self):
1162 # Issue #9792: create_connection() should not recast timeout errors
1163 # as generic socket errors.
1164 with self.mocked_socket_module():
1165 with self.assertRaises(socket.timeout):
1166 socket.create_connection((HOST, 1234))
1167
Guido van Rossumd8faa362007-04-27 19:54:29 +00001168
1169class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
1170
1171 def __init__(self, methodName='runTest'):
1172 SocketTCPTest.__init__(self, methodName=methodName)
1173 ThreadableTest.__init__(self)
1174
1175 def clientSetUp(self):
1176 pass
1177
1178 def clientTearDown(self):
1179 self.cli.close()
1180 self.cli = None
1181 ThreadableTest.clientTearDown(self)
1182
1183 def _justAccept(self):
1184 conn, addr = self.serv.accept()
1185
1186 testFamily = _justAccept
1187 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001188 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001189 self.assertEqual(self.cli.family, 2)
1190
1191 testTimeoutDefault = _justAccept
1192 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001193 # passing no explicit timeout uses socket's global default
Georg Brandlab91fde2009-08-13 08:51:18 +00001194 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001195 socket.setdefaulttimeout(42)
1196 try:
1197 self.cli = socket.create_connection((HOST, self.port))
1198 finally:
1199 socket.setdefaulttimeout(None)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +00001200 self.assertEqual(self.cli.gettimeout(), 42)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001201
1202 testTimeoutNone = _justAccept
1203 def _testTimeoutNone(self):
1204 # None timeout means the same as sock.settimeout(None)
Georg Brandlab91fde2009-08-13 08:51:18 +00001205 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001206 socket.setdefaulttimeout(30)
1207 try:
1208 self.cli = socket.create_connection((HOST, self.port), timeout=None)
1209 finally:
1210 socket.setdefaulttimeout(None)
1211 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001212
1213 testTimeoutValueNamed = _justAccept
1214 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001215 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001216 self.assertEqual(self.cli.gettimeout(), 30)
1217
1218 testTimeoutValueNonamed = _justAccept
1219 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001220 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001221 self.assertEqual(self.cli.gettimeout(), 30)
1222
Guido van Rossumd8faa362007-04-27 19:54:29 +00001223class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1224
1225 def __init__(self, methodName='runTest'):
1226 SocketTCPTest.__init__(self, methodName=methodName)
1227 ThreadableTest.__init__(self)
1228
1229 def clientSetUp(self):
1230 pass
1231
1232 def clientTearDown(self):
1233 self.cli.close()
1234 self.cli = None
1235 ThreadableTest.clientTearDown(self)
1236
1237 def testInsideTimeout(self):
1238 conn, addr = self.serv.accept()
1239 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001240 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001241 testOutsideTimeout = testInsideTimeout
1242
1243 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001244 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001245 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001246 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001247
1248 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001249 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Georg Brandlab91fde2009-08-13 08:51:18 +00001250 self.assertRaises(socket.timeout, lambda: sock.recv(5))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001251
1252
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001253class TCPTimeoutTest(SocketTCPTest):
1254
1255 def testTCPTimeout(self):
1256 def raise_timeout(*args, **kwargs):
1257 self.serv.settimeout(1.0)
1258 self.serv.accept()
Georg Brandlab91fde2009-08-13 08:51:18 +00001259 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001260 "Error generating a timeout exception (TCP)")
1261
1262 def testTimeoutZero(self):
1263 ok = False
1264 try:
1265 self.serv.settimeout(0.0)
1266 foo = self.serv.accept()
1267 except socket.timeout:
1268 self.fail("caught timeout instead of error (TCP)")
1269 except socket.error:
1270 ok = True
1271 except:
1272 self.fail("caught unexpected exception (TCP)")
1273 if not ok:
1274 self.fail("accept() returned success when we did not expect it")
1275
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001276 def testInterruptedTimeout(self):
1277 # XXX I don't know how to do this test on MSWindows or any other
1278 # plaform that doesn't support signal.alarm() or os.kill(), though
1279 # the bug should have existed on all platforms.
1280 if not hasattr(signal, "alarm"):
1281 return # can only test on *nix
1282 self.serv.settimeout(5.0) # must be longer than alarm
1283 class Alarm(Exception):
1284 pass
1285 def alarm_handler(signal, frame):
1286 raise Alarm
1287 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1288 try:
1289 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1290 try:
1291 foo = self.serv.accept()
1292 except socket.timeout:
1293 self.fail("caught timeout instead of Alarm")
1294 except Alarm:
1295 pass
1296 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001297 self.fail("caught other exception instead of Alarm:"
1298 " %s(%s):\n%s" %
1299 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001300 else:
1301 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001302 finally:
1303 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001304 except Alarm:
1305 self.fail("got Alarm in wrong place")
1306 finally:
1307 # no alarm can be pending. Safe to restore old handler.
1308 signal.signal(signal.SIGALRM, old_alarm)
1309
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001310class UDPTimeoutTest(SocketTCPTest):
1311
1312 def testUDPTimeout(self):
1313 def raise_timeout(*args, **kwargs):
1314 self.serv.settimeout(1.0)
1315 self.serv.recv(1024)
Georg Brandlab91fde2009-08-13 08:51:18 +00001316 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001317 "Error generating a timeout exception (UDP)")
1318
1319 def testTimeoutZero(self):
1320 ok = False
1321 try:
1322 self.serv.settimeout(0.0)
1323 foo = self.serv.recv(1024)
1324 except socket.timeout:
1325 self.fail("caught timeout instead of error (UDP)")
1326 except socket.error:
1327 ok = True
1328 except:
1329 self.fail("caught unexpected exception (UDP)")
1330 if not ok:
1331 self.fail("recv() returned success when we did not expect it")
1332
1333class TestExceptions(unittest.TestCase):
1334
1335 def testExceptionTree(self):
Georg Brandlab91fde2009-08-13 08:51:18 +00001336 self.assertTrue(issubclass(socket.error, Exception))
1337 self.assertTrue(issubclass(socket.herror, socket.error))
1338 self.assertTrue(issubclass(socket.gaierror, socket.error))
1339 self.assertTrue(issubclass(socket.timeout, socket.error))
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001340
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001341class TestLinuxAbstractNamespace(unittest.TestCase):
1342
1343 UNIX_PATH_MAX = 108
1344
1345 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001346 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001347 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1348 s1.bind(address)
1349 s1.listen(1)
1350 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1351 s2.connect(s1.getsockname())
1352 s1.accept()
1353 self.assertEqual(s1.getsockname(), address)
1354 self.assertEqual(s2.getpeername(), address)
1355
1356 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001357 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001358 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1359 s.bind(address)
1360 self.assertEqual(s.getsockname(), address)
1361
1362 def testNameOverflow(self):
1363 address = "\x00" + "h" * self.UNIX_PATH_MAX
1364 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1365 self.assertRaises(socket.error, s.bind, address)
1366
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001367
Thomas Wouters477c8d52006-05-27 19:21:47 +00001368class BufferIOTest(SocketConnectedTest):
1369 """
1370 Test the buffer versions of socket.recv() and socket.send().
1371 """
1372 def __init__(self, methodName='runTest'):
1373 SocketConnectedTest.__init__(self, methodName=methodName)
1374
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001375 def testRecvInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001376 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001377 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001378 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001379 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001380 self.assertEqual(msg, MSG)
1381
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001382 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001383 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001384 self.serv_conn.send(buf)
1385
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001386 def testRecvFromInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001387 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001388 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001389 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001390 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001391 self.assertEqual(msg, MSG)
1392
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001393 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001394 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001395 self.serv_conn.send(buf)
1396
Christian Heimes043d6f62008-01-07 17:19:16 +00001397
1398TIPC_STYPE = 2000
1399TIPC_LOWER = 200
1400TIPC_UPPER = 210
1401
1402def isTipcAvailable():
1403 """Check if the TIPC module is loaded
1404
1405 The TIPC module is not loaded automatically on Ubuntu and probably
1406 other Linux distros.
1407 """
1408 if not hasattr(socket, "AF_TIPC"):
1409 return False
1410 if not os.path.isfile("/proc/modules"):
1411 return False
1412 with open("/proc/modules") as f:
1413 for line in f:
1414 if line.startswith("tipc "):
1415 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001416 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001417 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1418 return False
1419
1420class TIPCTest (unittest.TestCase):
1421 def testRDM(self):
1422 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1423 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1424
1425 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1426 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1427 TIPC_LOWER, TIPC_UPPER)
1428 srv.bind(srvaddr)
1429
1430 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1431 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1432 cli.sendto(MSG, sendaddr)
1433
1434 msg, recvaddr = srv.recvfrom(1024)
1435
1436 self.assertEqual(cli.getsockname(), recvaddr)
1437 self.assertEqual(msg, MSG)
1438
1439
1440class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1441 def __init__(self, methodName = 'runTest'):
1442 unittest.TestCase.__init__(self, methodName = methodName)
1443 ThreadableTest.__init__(self)
1444
1445 def setUp(self):
1446 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1447 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1448 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1449 TIPC_LOWER, TIPC_UPPER)
1450 self.srv.bind(srvaddr)
1451 self.srv.listen(5)
1452 self.serverExplicitReady()
1453 self.conn, self.connaddr = self.srv.accept()
1454
1455 def clientSetUp(self):
1456 # The is a hittable race between serverExplicitReady() and the
1457 # accept() call; sleep a little while to avoid it, otherwise
1458 # we could get an exception
1459 time.sleep(0.1)
1460 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1461 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1462 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1463 self.cli.connect(addr)
1464 self.cliaddr = self.cli.getsockname()
1465
1466 def testStream(self):
1467 msg = self.conn.recv(1024)
1468 self.assertEqual(msg, MSG)
1469 self.assertEqual(self.cliaddr, self.connaddr)
1470
1471 def _testStream(self):
1472 self.cli.send(MSG)
1473 self.cli.close()
1474
1475
Guido van Rossumb995eb72002-07-31 16:08:40 +00001476def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001477 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001478 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001479 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001480 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001481
1482 tests.extend([
1483 NonBlockingTCPTests,
1484 FileObjectClassTestCase,
1485 UnbufferedFileObjectClassTestCase,
1486 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001487 SmallBufferedFileObjectClassTestCase,
Antoine Pitrou674f4002010-10-13 16:25:33 +00001488 UnicodeReadFileObjectClassTestCase,
1489 UnicodeWriteFileObjectClassTestCase,
1490 UnicodeReadWriteFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001491 NetworkConnectionNoServer,
1492 NetworkConnectionAttributesTest,
1493 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001494 ])
Dave Cole331708b2004-08-09 04:51:41 +00001495 if hasattr(socket, "socketpair"):
1496 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001497 if sys.platform == 'linux2':
1498 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001499 if isTipcAvailable():
1500 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001501 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001502
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001503 thread_info = support.threading_setup()
1504 support.run_unittest(*tests)
1505 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001506
1507if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001508 test_main()