blob: a467e0d1bd2c3172737e99e5aa53246702505ad5 [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
180class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000181 """Socket tests for client-server connection.
182
183 self.cli_conn is a client socket connected to the server. The
184 setUp() method guarantees that it is connected to the server.
185 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000186
187 def __init__(self, methodName='runTest'):
188 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
189
190 def setUp(self):
191 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000192 # Indicate explicitly we're ready for the client thread to
193 # proceed and then perform the blocking call to accept
194 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000195 conn, addr = self.serv.accept()
196 self.cli_conn = conn
197
198 def tearDown(self):
199 self.cli_conn.close()
200 self.cli_conn = None
201 ThreadedTCPSocketTest.tearDown(self)
202
203 def clientSetUp(self):
204 ThreadedTCPSocketTest.clientSetUp(self)
Christian Heimes5e696852008-04-09 08:37:03 +0000205 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000206 self.serv_conn = self.cli
207
208 def clientTearDown(self):
209 self.serv_conn.close()
210 self.serv_conn = None
211 ThreadedTCPSocketTest.clientTearDown(self)
212
Dave Cole331708b2004-08-09 04:51:41 +0000213class SocketPairTest(unittest.TestCase, ThreadableTest):
214
215 def __init__(self, methodName='runTest'):
216 unittest.TestCase.__init__(self, methodName=methodName)
217 ThreadableTest.__init__(self)
218
219 def setUp(self):
220 self.serv, self.cli = socket.socketpair()
221
222 def tearDown(self):
223 self.serv.close()
224 self.serv = None
225
226 def clientSetUp(self):
227 pass
228
229 def clientTearDown(self):
230 self.cli.close()
231 self.cli = None
232 ThreadableTest.clientTearDown(self)
233
Tim Peters494aaee2004-08-09 18:54:11 +0000234
Guido van Rossum24e4af82002-06-12 19:18:08 +0000235#######################################################################
236## Begin Tests
237
238class GeneralModuleTests(unittest.TestCase):
239
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000240 def test_repr(self):
241 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlab91fde2009-08-13 08:51:18 +0000242 self.assertTrue(repr(s).startswith("<socket.socket object"))
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000243
Raymond Hettinger027bb632004-05-31 03:09:25 +0000244 def test_weakref(self):
245 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
246 p = proxy(s)
247 self.assertEqual(p.fileno(), s.fileno())
248 s.close()
249 s = None
250 try:
251 p.fileno()
252 except ReferenceError:
253 pass
254 else:
255 self.fail('Socket proxy still exists')
256
Guido van Rossum24e4af82002-06-12 19:18:08 +0000257 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000258 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000259 def raise_error(*args, **kwargs):
260 raise socket.error
261 def raise_herror(*args, **kwargs):
262 raise socket.herror
263 def raise_gaierror(*args, **kwargs):
264 raise socket.gaierror
Georg Brandlab91fde2009-08-13 08:51:18 +0000265 self.assertRaises(socket.error, raise_error,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000266 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000267 self.assertRaises(socket.error, raise_herror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000268 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000269 self.assertRaises(socket.error, raise_gaierror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000270 "Error raising socket exception.")
271
272 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000273 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000274 socket.AF_INET
275 socket.SOCK_STREAM
276 socket.SOCK_DGRAM
277 socket.SOCK_RAW
278 socket.SOCK_RDM
279 socket.SOCK_SEQPACKET
280 socket.SOL_SOCKET
281 socket.SO_REUSEADDR
282
Guido van Rossum654c11e2002-06-13 20:24:17 +0000283 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000284 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000285 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000286 try:
287 ip = socket.gethostbyname(hostname)
288 except socket.error:
289 # Probably name lookup wasn't set up right; skip this test
290 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000291 self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000292 try:
293 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
294 except socket.error:
295 # Probably a similar problem as above; skip this test
296 return
Brett Cannon01668a12005-03-11 00:04:17 +0000297 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000298 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000299 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000300 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000301
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000302 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000303 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000304 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000305 try:
306 # On some versions, this loses a reference
307 orig = sys.getrefcount(__name__)
308 socket.getnameinfo(__name__,0)
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +0000309 except TypeError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000310 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000311 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000312
Guido van Rossum24e4af82002-06-12 19:18:08 +0000313 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000314 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000315 try:
316 # On some versions, this crashes the interpreter.
317 socket.getnameinfo(('x', 0, 0, 0), 0)
318 except socket.error:
319 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000320
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000321 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000322 # This just checks that htons etc. are their own inverse,
323 # when looking at the lower 16 or 32 bits.
324 sizes = {socket.htonl: 32, socket.ntohl: 32,
325 socket.htons: 16, socket.ntohs: 16}
326 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000327 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000328 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
329 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000330
Guido van Rossuma2627af2002-09-14 00:58:46 +0000331 swapped = func(mask)
332 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000333 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000334
Guido van Rossum018919a2007-01-15 00:07:32 +0000335 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000336 good_values = [ 1, 2, 3, 1, 2, 3 ]
337 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000338 for k in good_values:
339 socket.ntohl(k)
340 socket.ntohs(k)
341 socket.htonl(k)
342 socket.htons(k)
343 for k in bad_values:
344 self.assertRaises(OverflowError, socket.ntohl, k)
345 self.assertRaises(OverflowError, socket.ntohs, k)
346 self.assertRaises(OverflowError, socket.htonl, k)
347 self.assertRaises(OverflowError, socket.htons, k)
348
Barry Warsaw11b91a02004-06-28 00:50:43 +0000349 def testGetServBy(self):
350 eq = self.assertEqual
351 # Find one service that exists, then check all the related interfaces.
352 # I've ordered this by protocols that have both a tcp and udp
353 # protocol, at least for modern Linuxes.
Gregory P. Smith397cd8a2010-10-17 04:23:21 +0000354 if (sys.platform.startswith('linux') or
355 sys.platform.startswith('freebsd') or
356 sys.platform.startswith('netbsd') or
357 sys.platform == 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000358 # avoid the 'echo' service on this platform, as there is an
359 # assumption breaking non-standard port/protocol entry
360 services = ('daytime', 'qotd', 'domain')
361 else:
362 services = ('echo', 'daytime', 'domain')
363 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000364 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000365 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000366 break
367 except socket.error:
368 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000369 else:
370 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000371 # Try same call with optional protocol omitted
372 port2 = socket.getservbyname(service)
373 eq(port, port2)
374 # Try udp, but don't barf it it doesn't exist
375 try:
376 udpport = socket.getservbyname(service, 'udp')
377 except socket.error:
378 udpport = None
379 else:
380 eq(udpport, port)
381 # Now make sure the lookup by port returns the same service name
382 eq(socket.getservbyport(port2), service)
383 eq(socket.getservbyport(port, 'tcp'), service)
384 if udpport is not None:
385 eq(socket.getservbyport(udpport, 'udp'), service)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000386 # Make sure getservbyport does not accept out of range ports.
387 self.assertRaises(OverflowError, socket.getservbyport, -1)
388 self.assertRaises(OverflowError, socket.getservbyport, 65536)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000389
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000390 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000391 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000392 # The default timeout should initially be None
393 self.assertEqual(socket.getdefaulttimeout(), None)
394 s = socket.socket()
395 self.assertEqual(s.gettimeout(), None)
396 s.close()
397
398 # Set the default timeout to 10, and see if it propagates
399 socket.setdefaulttimeout(10)
400 self.assertEqual(socket.getdefaulttimeout(), 10)
401 s = socket.socket()
402 self.assertEqual(s.gettimeout(), 10)
403 s.close()
404
405 # Reset the default timeout to None, and see if it propagates
406 socket.setdefaulttimeout(None)
407 self.assertEqual(socket.getdefaulttimeout(), None)
408 s = socket.socket()
409 self.assertEqual(s.gettimeout(), None)
410 s.close()
411
412 # Check that setting it to an invalid value raises ValueError
413 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
414
415 # Check that setting it to an invalid type raises TypeError
416 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
417
Benjamin Petersonf91df042009-02-13 02:50:59 +0000418 def testIPv4_inet_aton_fourbytes(self):
419 if not hasattr(socket, 'inet_aton'):
420 return # No inet_aton, nothing to check
421 # Test that issue1008086 and issue767150 are fixed.
422 # It must return 4 bytes.
423 self.assertEquals(b'\x00'*4, socket.inet_aton('0.0.0.0'))
424 self.assertEquals(b'\xff'*4, socket.inet_aton('255.255.255.255'))
425
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000426 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000427 if not hasattr(socket, 'inet_pton'):
428 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000429 from socket import inet_aton as f, inet_pton, AF_INET
430 g = lambda a: inet_pton(AF_INET, a)
431
Guido van Rossumb5b22702007-05-18 18:55:53 +0000432 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
433 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
434 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
435 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
436 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000437
Guido van Rossumb5b22702007-05-18 18:55:53 +0000438 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
439 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
440 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
441 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000442
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000443 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000444 if not hasattr(socket, 'inet_pton'):
445 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000446 try:
447 from socket import inet_pton, AF_INET6, has_ipv6
448 if not has_ipv6:
449 return
450 except ImportError:
451 return
452 f = lambda a: inet_pton(AF_INET6, a)
453
Guido van Rossum540d9872007-08-17 03:51:09 +0000454 self.assertEquals(b'\x00' * 16, f('::'))
455 self.assertEquals(b'\x00' * 16, f('0::0'))
456 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000457 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000458 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 +0000459 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
460 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000461
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000462 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000463 if not hasattr(socket, 'inet_ntop'):
464 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000465 from socket import inet_ntoa as f, inet_ntop, AF_INET
466 g = lambda a: inet_ntop(AF_INET, a)
467
Guido van Rossumb5b22702007-05-18 18:55:53 +0000468 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
469 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
470 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
471 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000472
Guido van Rossumb5b22702007-05-18 18:55:53 +0000473 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
474 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
475 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000476
477 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000478 if not hasattr(socket, 'inet_ntop'):
479 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000480 try:
481 from socket import inet_ntop, AF_INET6, has_ipv6
482 if not has_ipv6:
483 return
484 except ImportError:
485 return
486 f = lambda a: inet_ntop(AF_INET6, a)
487
Guido van Rossum540d9872007-08-17 03:51:09 +0000488 self.assertEquals('::', f(b'\x00' * 16))
489 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000490 self.assertEquals(
491 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000492 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 +0000493 )
494
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000495 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000496
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000497 def _get_unused_port(self, bind_address='0.0.0.0'):
498 """Use a temporary socket to elicit an unused ephemeral port.
Christian Heimes5e696852008-04-09 08:37:03 +0000499
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000500 Args:
501 bind_address: Hostname or IP address to search for a port on.
502
503 Returns: A most likely to be unused port.
504 """
505 tempsock = socket.socket()
506 tempsock.bind((bind_address, 0))
507 host, port = tempsock.getsockname()
508 tempsock.close()
509 return port
510
511 def testSockName(self):
512 # Testing getsockname()
513 port = self._get_unused_port()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000514 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Christian Heimes5e696852008-04-09 08:37:03 +0000515 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000516 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000517 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
518 # it reasonable to get the host's addr in addition to 0.0.0.0.
519 # At least for eCos. This is required for the S/390 to pass.
520 my_ip_addr = socket.gethostbyname(socket.gethostname())
Georg Brandlab91fde2009-08-13 08:51:18 +0000521 self.assertTrue(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +0000522 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000523
524 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000525 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000526 # We know a socket should start without reuse==0
527 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
528 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000529 self.assertFalse(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000530
531 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000532 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000533 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
534 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
535 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000536 self.assertFalse(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000537
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000538 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000539 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000540 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
541 sock.settimeout(1)
542 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000543 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000544
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000545 def testNewAttributes(self):
546 # testing .family, .type and .protocol
547 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
548 self.assertEqual(sock.family, socket.AF_INET)
549 self.assertEqual(sock.type, socket.SOCK_STREAM)
550 self.assertEqual(sock.proto, 0)
551 sock.close()
552
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000553 def test_getsockaddrarg(self):
554 host = '0.0.0.0'
555 port = self._get_unused_port(bind_address=host)
556 big_port = port + 65536
557 neg_port = port - 65536
558 sock = socket.socket()
559 try:
560 self.assertRaises(OverflowError, sock.bind, (host, big_port))
561 self.assertRaises(OverflowError, sock.bind, (host, neg_port))
562 sock.bind((host, port))
563 finally:
564 sock.close()
565
Christian Heimesfaf2f632008-01-06 16:59:19 +0000566 def test_sock_ioctl(self):
567 if os.name != "nt":
568 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000569 self.assertTrue(hasattr(socket.socket, 'ioctl'))
570 self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
571 self.assertTrue(hasattr(socket, 'RCVALL_ON'))
572 self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
Christian Heimesfaf2f632008-01-06 16:59:19 +0000573
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000574 def testGetaddrinfo(self):
575 try:
576 socket.getaddrinfo('localhost', 80)
577 except socket.gaierror as err:
578 if err.errno == socket.EAI_SERVICE:
579 # see http://bugs.python.org/issue1282647
580 self.skipTest("buggy libc version")
581 raise
582 # len of every sequence is supposed to be == 5
583 for info in socket.getaddrinfo(HOST, None):
584 self.assertEqual(len(info), 5)
585 # host can be a domain name, a string representation of an
586 # IPv4/v6 address or None
587 socket.getaddrinfo('localhost', 80)
588 socket.getaddrinfo('127.0.0.1', 80)
589 socket.getaddrinfo(None, 80)
590 if SUPPORTS_IPV6:
591 socket.getaddrinfo('::1', 80)
592 # port can be a string service name such as "http", a numeric
593 # port number or None
594 socket.getaddrinfo(HOST, "http")
595 socket.getaddrinfo(HOST, 80)
596 socket.getaddrinfo(HOST, None)
597 # test family and socktype filters
598 infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
599 for family, _, _, _, _ in infos:
600 self.assertEqual(family, socket.AF_INET)
601 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
602 for _, socktype, _, _, _ in infos:
603 self.assertEqual(socktype, socket.SOCK_STREAM)
604 # test proto and flags arguments
Giampaolo Rodolà5b37ce62010-08-16 05:09:31 +0000605 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000606 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
607 # a server willing to support both IPv4 and IPv6 will
608 # usually do this
609 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
610 socket.AI_PASSIVE)
611
Christian Heimesfaf2f632008-01-06 16:59:19 +0000612
Antoine Pitrou08ae02f2010-09-27 18:14:43 +0000613 def check_sendall_interrupted(self, with_timeout):
614 # socketpair() is not stricly required, but it makes things easier.
615 if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
616 self.skipTest("signal.alarm and socket.socketpair required for this test")
617 # Our signal handlers clobber the C errno by calling a math function
618 # with an invalid domain value.
619 def ok_handler(*args):
620 self.assertRaises(ValueError, math.acosh, 0)
621 def raising_handler(*args):
622 self.assertRaises(ValueError, math.acosh, 0)
623 1 // 0
624 c, s = socket.socketpair()
625 old_alarm = signal.signal(signal.SIGALRM, raising_handler)
626 try:
627 if with_timeout:
628 # Just above the one second minimum for signal.alarm
629 c.settimeout(1.5)
630 with self.assertRaises(ZeroDivisionError):
631 signal.alarm(1)
632 c.sendall(b"x" * (1024**2))
633 if with_timeout:
634 signal.signal(signal.SIGALRM, ok_handler)
635 signal.alarm(1)
636 self.assertRaises(socket.timeout, c.sendall, b"x" * (1024**2))
637 finally:
638 signal.signal(signal.SIGALRM, old_alarm)
639 c.close()
640 s.close()
641
642 def test_sendall_interrupted(self):
643 self.check_sendall_interrupted(False)
644
645 def test_sendall_interrupted_with_timeout(self):
646 self.check_sendall_interrupted(True)
647
648
Guido van Rossum24e4af82002-06-12 19:18:08 +0000649class BasicTCPTest(SocketConnectedTest):
650
651 def __init__(self, methodName='runTest'):
652 SocketConnectedTest.__init__(self, methodName=methodName)
653
654 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000655 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000656 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000657 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000658
659 def _testRecv(self):
660 self.serv_conn.send(MSG)
661
662 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000663 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000664 seg1 = self.cli_conn.recv(len(MSG) - 3)
665 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000666 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000667 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000668
669 def _testOverFlowRecv(self):
670 self.serv_conn.send(MSG)
671
672 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000673 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000674 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000675 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000676
677 def _testRecvFrom(self):
678 self.serv_conn.send(MSG)
679
680 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000681 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000682 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
683 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000684 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000685 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000686
687 def _testOverFlowRecvFrom(self):
688 self.serv_conn.send(MSG)
689
690 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000691 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000692 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000693 while 1:
694 read = self.cli_conn.recv(1024)
695 if not read:
696 break
Guido van Rossume531e292002-08-08 20:28:34 +0000697 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000698 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000699
700 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000701 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000702 self.serv_conn.sendall(big_chunk)
703
704 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000705 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000706 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000707 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000708 fd = self.cli_conn.fileno()
709 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
710 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000711 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000712
713 def _testFromFd(self):
714 self.serv_conn.send(MSG)
715
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000716 def testDup(self):
717 # Testing dup()
718 sock = self.cli_conn.dup()
719 msg = sock.recv(1024)
720 self.assertEqual(msg, MSG)
721
722 def _testDup(self):
723 self.serv_conn.send(MSG)
724
Guido van Rossum24e4af82002-06-12 19:18:08 +0000725 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000726 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000727 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000728 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +0000729 # wait for _testShutdown to finish: on OS X, when the server
730 # closes the connection the client also becomes disconnected,
731 # and the client's shutdown call will fail. (Issue #4397.)
732 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000733
734 def _testShutdown(self):
735 self.serv_conn.send(MSG)
736 self.serv_conn.shutdown(2)
737
738class BasicUDPTest(ThreadedUDPSocketTest):
739
740 def __init__(self, methodName='runTest'):
741 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
742
743 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000744 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000745 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000746 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000747
748 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000749 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000750
Guido van Rossum1c938012002-06-12 21:17:20 +0000751 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000752 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000753 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000754 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000755
Guido van Rossum1c938012002-06-12 21:17:20 +0000756 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000757 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000758
Guido van Rossumd8faa362007-04-27 19:54:29 +0000759 def testRecvFromNegative(self):
760 # Negative lengths passed to recvfrom should give ValueError.
761 self.assertRaises(ValueError, self.serv.recvfrom, -1)
762
763 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000764 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000765
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000766class TCPCloserTest(ThreadedTCPSocketTest):
767
768 def testClose(self):
769 conn, addr = self.serv.accept()
770 conn.close()
771
772 sd = self.cli
773 read, write, err = select.select([sd], [], [], 1.0)
774 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000775 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000776
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000777 # Calling close() many times should be safe.
778 conn.close()
779 conn.close()
780
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000781 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000782 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000783 time.sleep(1.0)
784
Dave Cole331708b2004-08-09 04:51:41 +0000785class BasicSocketPairTest(SocketPairTest):
786
787 def __init__(self, methodName='runTest'):
788 SocketPairTest.__init__(self, methodName=methodName)
789
790 def testRecv(self):
791 msg = self.serv.recv(1024)
792 self.assertEqual(msg, MSG)
793
794 def _testRecv(self):
795 self.cli.send(MSG)
796
797 def testSend(self):
798 self.serv.send(MSG)
799
800 def _testSend(self):
801 msg = self.cli.recv(1024)
802 self.assertEqual(msg, MSG)
803
Guido van Rossum24e4af82002-06-12 19:18:08 +0000804class NonBlockingTCPTests(ThreadedTCPSocketTest):
805
806 def __init__(self, methodName='runTest'):
807 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
808
809 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000810 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000811 self.serv.setblocking(0)
812 start = time.time()
813 try:
814 self.serv.accept()
815 except socket.error:
816 pass
817 end = time.time()
Georg Brandlab91fde2009-08-13 08:51:18 +0000818 self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000819
820 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000821 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000822
Guido van Rossum24e4af82002-06-12 19:18:08 +0000823 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000824 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000825 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000826 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000827 conn, addr = self.serv.accept()
828 except socket.error:
829 pass
830 else:
831 self.fail("Error trying to do non-blocking accept.")
832 read, write, err = select.select([self.serv], [], [])
833 if self.serv in read:
834 conn, addr = self.serv.accept()
835 else:
836 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000837
Guido van Rossum24e4af82002-06-12 19:18:08 +0000838 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000839 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +0000840 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000841
842 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000843 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000844 conn, addr = self.serv.accept()
845
846 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000847 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +0000848 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000849
850 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000851 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000852 conn, addr = self.serv.accept()
853 conn.setblocking(0)
854 try:
855 msg = conn.recv(len(MSG))
856 except socket.error:
857 pass
858 else:
859 self.fail("Error trying to do non-blocking recv.")
860 read, write, err = select.select([conn], [], [])
861 if conn in read:
862 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000863 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000864 else:
865 self.fail("Error during select call to non-blocking socket.")
866
867 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000868 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000869 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000870 self.cli.send(MSG)
871
872class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000873 """Unit tests for the object returned by socket.makefile()
874
Antoine Pitrou674f4002010-10-13 16:25:33 +0000875 self.read_file is the io object returned by makefile() on
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000876 the client connection. You can read from this file to
877 get output from the server.
878
Antoine Pitrou674f4002010-10-13 16:25:33 +0000879 self.write_file is the io object returned by makefile() on the
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000880 server connection. You can write to this file to send output
881 to the client.
882 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000883
Guido van Rossume9f66142002-08-07 15:46:19 +0000884 bufsize = -1 # Use default buffer size
Antoine Pitrou674f4002010-10-13 16:25:33 +0000885 encoding = 'utf8'
886 errors = 'strict'
887 newline = None
888
889 read_mode = 'rb'
890 read_msg = MSG
891 write_mode = 'wb'
892 write_msg = MSG
Guido van Rossume9f66142002-08-07 15:46:19 +0000893
Guido van Rossum24e4af82002-06-12 19:18:08 +0000894 def __init__(self, methodName='runTest'):
895 SocketConnectedTest.__init__(self, methodName=methodName)
896
897 def setUp(self):
898 SocketConnectedTest.setUp(self)
Antoine Pitrou674f4002010-10-13 16:25:33 +0000899 self.read_file = self.cli_conn.makefile(
900 self.read_mode, self.bufsize,
901 encoding = self.encoding,
902 errors = self.errors,
903 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000904
905 def tearDown(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000906 self.read_file.close()
907 self.assertTrue(self.read_file.closed)
908 self.read_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +0000909 SocketConnectedTest.tearDown(self)
910
911 def clientSetUp(self):
912 SocketConnectedTest.clientSetUp(self)
Antoine Pitrou674f4002010-10-13 16:25:33 +0000913 self.write_file = self.serv_conn.makefile(
914 self.write_mode, self.bufsize,
915 encoding = self.encoding,
916 errors = self.errors,
917 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000918
919 def clientTearDown(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000920 self.write_file.close()
921 self.assertTrue(self.write_file.closed)
922 self.write_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +0000923 SocketConnectedTest.clientTearDown(self)
924
925 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000926 # Performing small file read test
Antoine Pitrou674f4002010-10-13 16:25:33 +0000927 first_seg = self.read_file.read(len(self.read_msg)-3)
928 second_seg = self.read_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000929 msg = first_seg + second_seg
Antoine Pitrou674f4002010-10-13 16:25:33 +0000930 self.assertEqual(msg, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000931
932 def _testSmallRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000933 self.write_file.write(self.write_msg)
934 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000935
Guido van Rossum8c943832002-08-08 01:00:28 +0000936 def testFullRead(self):
937 # read until EOF
Antoine Pitrou674f4002010-10-13 16:25:33 +0000938 msg = self.read_file.read()
939 self.assertEqual(msg, self.read_msg)
Guido van Rossum8c943832002-08-08 01:00:28 +0000940
941 def _testFullRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000942 self.write_file.write(self.write_msg)
943 self.write_file.close()
Guido van Rossum8c943832002-08-08 01:00:28 +0000944
Guido van Rossum24e4af82002-06-12 19:18:08 +0000945 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000946 # Performing unbuffered file read test
Antoine Pitrou674f4002010-10-13 16:25:33 +0000947 buf = type(self.read_msg)()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000948 while 1:
Antoine Pitrou674f4002010-10-13 16:25:33 +0000949 char = self.read_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000950 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000951 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000952 buf += char
Antoine Pitrou674f4002010-10-13 16:25:33 +0000953 self.assertEqual(buf, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000954
955 def _testUnbufferedRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000956 self.write_file.write(self.write_msg)
957 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000958
959 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000960 # Performing file readline test
Antoine Pitrou674f4002010-10-13 16:25:33 +0000961 line = self.read_file.readline()
962 self.assertEqual(line, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000963
964 def _testReadline(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
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000968 def testCloseAfterMakefile(self):
969 # The file returned by makefile should keep the socket open.
970 self.cli_conn.close()
971 # read until EOF
Antoine Pitrou674f4002010-10-13 16:25:33 +0000972 msg = self.read_file.read()
973 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000974
975 def _testCloseAfterMakefile(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000976 self.write_file.write(self.write_msg)
977 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000978
979 def testMakefileAfterMakefileClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000980 self.read_file.close()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000981 msg = self.cli_conn.recv(len(MSG))
Antoine Pitrou674f4002010-10-13 16:25:33 +0000982 if isinstance(self.read_msg, str):
983 msg = msg.decode()
984 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000985
986 def _testMakefileAfterMakefileClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000987 self.write_file.write(self.write_msg)
988 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000989
Tim Peters116d83c2004-03-28 02:20:45 +0000990 def testClosedAttr(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000991 self.assertTrue(not self.read_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +0000992
993 def _testClosedAttr(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000994 self.assertTrue(not self.write_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +0000995
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000996 def testAttributes(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000997 self.assertEqual(self.read_file.mode, self.read_mode)
998 self.assertEqual(self.read_file.name, self.cli_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000999
1000 def _testAttributes(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001001 self.assertEqual(self.write_file.mode, self.write_mode)
1002 self.assertEqual(self.write_file.name, self.serv_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001003
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001004 def testRealClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001005 self.read_file.close()
1006 self.assertRaises(ValueError, self.read_file.fileno)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001007 self.cli_conn.close()
1008 self.assertRaises(socket.error, self.cli_conn.getsockname)
1009
1010 def _testRealClose(self):
1011 pass
1012
1013
Guido van Rossume9f66142002-08-07 15:46:19 +00001014class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
1015
1016 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +00001017
Guido van Rossume9f66142002-08-07 15:46:19 +00001018 In this case (and in this case only), it should be possible to
1019 create a file object, read a line from it, create another file
1020 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +00001021 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +00001022 when reading multiple requests from the same socket."""
1023
1024 bufsize = 0 # Use unbuffered mode
1025
1026 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001027 # Read a line, create a new file object, read another line with it
Antoine Pitrou674f4002010-10-13 16:25:33 +00001028 line = self.read_file.readline() # first line
1029 self.assertEqual(line, b"A. " + self.write_msg) # first line
1030 self.read_file = self.cli_conn.makefile('rb', 0)
1031 line = self.read_file.readline() # second line
1032 self.assertEqual(line, b"B. " + self.write_msg) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +00001033
1034 def _testUnbufferedReadline(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001035 self.write_file.write(b"A. " + self.write_msg)
1036 self.write_file.write(b"B. " + self.write_msg)
1037 self.write_file.flush()
Guido van Rossume9f66142002-08-07 15:46:19 +00001038
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001039 def testMakefileClose(self):
1040 # The file returned by makefile should keep the socket open...
1041 self.cli_conn.close()
1042 msg = self.cli_conn.recv(1024)
Antoine Pitrou674f4002010-10-13 16:25:33 +00001043 self.assertEqual(msg, self.read_msg)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001044 # ...until the file is itself closed
Antoine Pitrou674f4002010-10-13 16:25:33 +00001045 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001046 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
1047
1048 def _testMakefileClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001049 self.write_file.write(self.write_msg)
1050 self.write_file.flush()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001051
1052 def testMakefileCloseSocketDestroy(self):
1053 refcount_before = sys.getrefcount(self.cli_conn)
Antoine Pitrou674f4002010-10-13 16:25:33 +00001054 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001055 refcount_after = sys.getrefcount(self.cli_conn)
1056 self.assertEqual(refcount_before - 1, refcount_after)
1057
1058 def _testMakefileCloseSocketDestroy(self):
1059 pass
1060
1061
Guido van Rossum8c943832002-08-08 01:00:28 +00001062class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1063
1064 bufsize = 1 # Default-buffered for reading; line-buffered for writing
1065
1066
1067class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1068
1069 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +00001070
Thomas Woutersb2137042007-02-01 18:02:27 +00001071
Antoine Pitrou674f4002010-10-13 16:25:33 +00001072class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase):
1073 """Tests for socket.makefile() in text mode (rather than binary)"""
1074
1075 read_mode = 'r'
1076 read_msg = MSG.decode('utf8')
1077 write_mode = 'wb'
1078 write_msg = MSG
1079 newline = ''
1080
1081
1082class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase):
1083 """Tests for socket.makefile() in text mode (rather than binary)"""
1084
1085 read_mode = 'rb'
1086 read_msg = MSG
1087 write_mode = 'w'
1088 write_msg = MSG.decode('utf8')
1089 newline = ''
1090
1091
1092class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase):
1093 """Tests for socket.makefile() in text mode (rather than binary)"""
1094
1095 read_mode = 'r'
1096 read_msg = MSG.decode('utf8')
1097 write_mode = 'w'
1098 write_msg = MSG.decode('utf8')
1099 newline = ''
1100
1101
Guido van Rossumd8faa362007-04-27 19:54:29 +00001102class NetworkConnectionTest(object):
1103 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001104
Guido van Rossumd8faa362007-04-27 19:54:29 +00001105 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001106 # We're inherited below by BasicTCPTest2, which also inherits
1107 # BasicTCPTest, which defines self.port referenced below.
1108 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001109 self.serv_conn = self.cli
1110
1111class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
1112 """Tests that NetworkConnection does not break existing TCP functionality.
1113 """
1114
1115class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001116
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001117 class MockSocket(socket.socket):
1118 def connect(self, *args):
1119 raise socket.timeout('timed out')
1120
1121 @contextlib.contextmanager
1122 def mocked_socket_module(self):
1123 """Return a socket which times out on connect"""
1124 old_socket = socket.socket
1125 socket.socket = self.MockSocket
1126 try:
1127 yield
1128 finally:
1129 socket.socket = old_socket
1130
1131 def test_connect(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001132 port = support.find_unused_port()
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001133 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1134 try:
1135 cli.connect((HOST, port))
1136 except socket.error as err:
1137 self.assertEqual(err.errno, errno.ECONNREFUSED)
1138 else:
1139 self.fail("socket.error not raised")
1140
1141 def test_create_connection(self):
1142 # Issue #9792: errors raised by create_connection() should have
1143 # a proper errno attribute.
1144 port = support.find_unused_port()
1145 try:
1146 socket.create_connection((HOST, port))
1147 except socket.error as err:
1148 self.assertEqual(err.errno, errno.ECONNREFUSED)
1149 else:
1150 self.fail("socket.error not raised")
1151
1152 def test_create_connection_timeout(self):
1153 # Issue #9792: create_connection() should not recast timeout errors
1154 # as generic socket errors.
1155 with self.mocked_socket_module():
1156 with self.assertRaises(socket.timeout):
1157 socket.create_connection((HOST, 1234))
1158
Guido van Rossumd8faa362007-04-27 19:54:29 +00001159
1160class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
1161
1162 def __init__(self, methodName='runTest'):
1163 SocketTCPTest.__init__(self, methodName=methodName)
1164 ThreadableTest.__init__(self)
1165
1166 def clientSetUp(self):
1167 pass
1168
1169 def clientTearDown(self):
1170 self.cli.close()
1171 self.cli = None
1172 ThreadableTest.clientTearDown(self)
1173
1174 def _justAccept(self):
1175 conn, addr = self.serv.accept()
1176
1177 testFamily = _justAccept
1178 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001179 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001180 self.assertEqual(self.cli.family, 2)
1181
1182 testTimeoutDefault = _justAccept
1183 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001184 # passing no explicit timeout uses socket's global default
Georg Brandlab91fde2009-08-13 08:51:18 +00001185 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001186 socket.setdefaulttimeout(42)
1187 try:
1188 self.cli = socket.create_connection((HOST, self.port))
1189 finally:
1190 socket.setdefaulttimeout(None)
1191 self.assertEquals(self.cli.gettimeout(), 42)
1192
1193 testTimeoutNone = _justAccept
1194 def _testTimeoutNone(self):
1195 # None timeout means the same as sock.settimeout(None)
Georg Brandlab91fde2009-08-13 08:51:18 +00001196 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001197 socket.setdefaulttimeout(30)
1198 try:
1199 self.cli = socket.create_connection((HOST, self.port), timeout=None)
1200 finally:
1201 socket.setdefaulttimeout(None)
1202 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001203
1204 testTimeoutValueNamed = _justAccept
1205 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001206 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001207 self.assertEqual(self.cli.gettimeout(), 30)
1208
1209 testTimeoutValueNonamed = _justAccept
1210 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001211 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001212 self.assertEqual(self.cli.gettimeout(), 30)
1213
Guido van Rossumd8faa362007-04-27 19:54:29 +00001214class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1215
1216 def __init__(self, methodName='runTest'):
1217 SocketTCPTest.__init__(self, methodName=methodName)
1218 ThreadableTest.__init__(self)
1219
1220 def clientSetUp(self):
1221 pass
1222
1223 def clientTearDown(self):
1224 self.cli.close()
1225 self.cli = None
1226 ThreadableTest.clientTearDown(self)
1227
1228 def testInsideTimeout(self):
1229 conn, addr = self.serv.accept()
1230 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001231 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001232 testOutsideTimeout = testInsideTimeout
1233
1234 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001235 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001236 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001237 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001238
1239 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001240 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Georg Brandlab91fde2009-08-13 08:51:18 +00001241 self.assertRaises(socket.timeout, lambda: sock.recv(5))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001242
1243
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001244class TCPTimeoutTest(SocketTCPTest):
1245
1246 def testTCPTimeout(self):
1247 def raise_timeout(*args, **kwargs):
1248 self.serv.settimeout(1.0)
1249 self.serv.accept()
Georg Brandlab91fde2009-08-13 08:51:18 +00001250 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001251 "Error generating a timeout exception (TCP)")
1252
1253 def testTimeoutZero(self):
1254 ok = False
1255 try:
1256 self.serv.settimeout(0.0)
1257 foo = self.serv.accept()
1258 except socket.timeout:
1259 self.fail("caught timeout instead of error (TCP)")
1260 except socket.error:
1261 ok = True
1262 except:
1263 self.fail("caught unexpected exception (TCP)")
1264 if not ok:
1265 self.fail("accept() returned success when we did not expect it")
1266
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001267 def testInterruptedTimeout(self):
1268 # XXX I don't know how to do this test on MSWindows or any other
1269 # plaform that doesn't support signal.alarm() or os.kill(), though
1270 # the bug should have existed on all platforms.
1271 if not hasattr(signal, "alarm"):
1272 return # can only test on *nix
1273 self.serv.settimeout(5.0) # must be longer than alarm
1274 class Alarm(Exception):
1275 pass
1276 def alarm_handler(signal, frame):
1277 raise Alarm
1278 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1279 try:
1280 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1281 try:
1282 foo = self.serv.accept()
1283 except socket.timeout:
1284 self.fail("caught timeout instead of Alarm")
1285 except Alarm:
1286 pass
1287 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001288 self.fail("caught other exception instead of Alarm:"
1289 " %s(%s):\n%s" %
1290 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001291 else:
1292 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001293 finally:
1294 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001295 except Alarm:
1296 self.fail("got Alarm in wrong place")
1297 finally:
1298 # no alarm can be pending. Safe to restore old handler.
1299 signal.signal(signal.SIGALRM, old_alarm)
1300
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001301class UDPTimeoutTest(SocketTCPTest):
1302
1303 def testUDPTimeout(self):
1304 def raise_timeout(*args, **kwargs):
1305 self.serv.settimeout(1.0)
1306 self.serv.recv(1024)
Georg Brandlab91fde2009-08-13 08:51:18 +00001307 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001308 "Error generating a timeout exception (UDP)")
1309
1310 def testTimeoutZero(self):
1311 ok = False
1312 try:
1313 self.serv.settimeout(0.0)
1314 foo = self.serv.recv(1024)
1315 except socket.timeout:
1316 self.fail("caught timeout instead of error (UDP)")
1317 except socket.error:
1318 ok = True
1319 except:
1320 self.fail("caught unexpected exception (UDP)")
1321 if not ok:
1322 self.fail("recv() returned success when we did not expect it")
1323
1324class TestExceptions(unittest.TestCase):
1325
1326 def testExceptionTree(self):
Georg Brandlab91fde2009-08-13 08:51:18 +00001327 self.assertTrue(issubclass(socket.error, Exception))
1328 self.assertTrue(issubclass(socket.herror, socket.error))
1329 self.assertTrue(issubclass(socket.gaierror, socket.error))
1330 self.assertTrue(issubclass(socket.timeout, socket.error))
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001331
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001332class TestLinuxAbstractNamespace(unittest.TestCase):
1333
1334 UNIX_PATH_MAX = 108
1335
1336 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001337 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001338 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1339 s1.bind(address)
1340 s1.listen(1)
1341 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1342 s2.connect(s1.getsockname())
1343 s1.accept()
1344 self.assertEqual(s1.getsockname(), address)
1345 self.assertEqual(s2.getpeername(), address)
1346
1347 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001348 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001349 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1350 s.bind(address)
1351 self.assertEqual(s.getsockname(), address)
1352
1353 def testNameOverflow(self):
1354 address = "\x00" + "h" * self.UNIX_PATH_MAX
1355 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1356 self.assertRaises(socket.error, s.bind, address)
1357
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001358
Thomas Wouters477c8d52006-05-27 19:21:47 +00001359class BufferIOTest(SocketConnectedTest):
1360 """
1361 Test the buffer versions of socket.recv() and socket.send().
1362 """
1363 def __init__(self, methodName='runTest'):
1364 SocketConnectedTest.__init__(self, methodName=methodName)
1365
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001366 def testRecvInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001367 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001368 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001369 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001370 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001371 self.assertEqual(msg, MSG)
1372
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001373 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001374 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001375 self.serv_conn.send(buf)
1376
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001377 def testRecvFromInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001378 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001379 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001380 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001381 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001382 self.assertEqual(msg, MSG)
1383
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001384 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001385 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001386 self.serv_conn.send(buf)
1387
Christian Heimes043d6f62008-01-07 17:19:16 +00001388
1389TIPC_STYPE = 2000
1390TIPC_LOWER = 200
1391TIPC_UPPER = 210
1392
1393def isTipcAvailable():
1394 """Check if the TIPC module is loaded
1395
1396 The TIPC module is not loaded automatically on Ubuntu and probably
1397 other Linux distros.
1398 """
1399 if not hasattr(socket, "AF_TIPC"):
1400 return False
1401 if not os.path.isfile("/proc/modules"):
1402 return False
1403 with open("/proc/modules") as f:
1404 for line in f:
1405 if line.startswith("tipc "):
1406 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001407 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001408 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1409 return False
1410
1411class TIPCTest (unittest.TestCase):
1412 def testRDM(self):
1413 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1414 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1415
1416 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1417 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1418 TIPC_LOWER, TIPC_UPPER)
1419 srv.bind(srvaddr)
1420
1421 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1422 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1423 cli.sendto(MSG, sendaddr)
1424
1425 msg, recvaddr = srv.recvfrom(1024)
1426
1427 self.assertEqual(cli.getsockname(), recvaddr)
1428 self.assertEqual(msg, MSG)
1429
1430
1431class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1432 def __init__(self, methodName = 'runTest'):
1433 unittest.TestCase.__init__(self, methodName = methodName)
1434 ThreadableTest.__init__(self)
1435
1436 def setUp(self):
1437 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1438 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1439 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1440 TIPC_LOWER, TIPC_UPPER)
1441 self.srv.bind(srvaddr)
1442 self.srv.listen(5)
1443 self.serverExplicitReady()
1444 self.conn, self.connaddr = self.srv.accept()
1445
1446 def clientSetUp(self):
1447 # The is a hittable race between serverExplicitReady() and the
1448 # accept() call; sleep a little while to avoid it, otherwise
1449 # we could get an exception
1450 time.sleep(0.1)
1451 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1452 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1453 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1454 self.cli.connect(addr)
1455 self.cliaddr = self.cli.getsockname()
1456
1457 def testStream(self):
1458 msg = self.conn.recv(1024)
1459 self.assertEqual(msg, MSG)
1460 self.assertEqual(self.cliaddr, self.connaddr)
1461
1462 def _testStream(self):
1463 self.cli.send(MSG)
1464 self.cli.close()
1465
1466
Guido van Rossumb995eb72002-07-31 16:08:40 +00001467def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001468 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001469 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001470 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001471 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001472
1473 tests.extend([
1474 NonBlockingTCPTests,
1475 FileObjectClassTestCase,
1476 UnbufferedFileObjectClassTestCase,
1477 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001478 SmallBufferedFileObjectClassTestCase,
Antoine Pitrou674f4002010-10-13 16:25:33 +00001479 UnicodeReadFileObjectClassTestCase,
1480 UnicodeWriteFileObjectClassTestCase,
1481 UnicodeReadWriteFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001482 NetworkConnectionNoServer,
1483 NetworkConnectionAttributesTest,
1484 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001485 ])
Dave Cole331708b2004-08-09 04:51:41 +00001486 if hasattr(socket, "socketpair"):
1487 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001488 if sys.platform == 'linux2':
1489 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001490 if isTipcAvailable():
1491 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001492 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001493
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001494 thread_info = support.threading_setup()
1495 support.run_unittest(*tests)
1496 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001497
1498if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001499 test_main()