blob: c33c82317258ca4f38e44c873dc3aeb60ac22a9c [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.
Brett Cannon08febeb2004-11-20 21:10:07 +0000354 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000355 'freebsd7', 'freebsd8', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000356 # avoid the 'echo' service on this platform, as there is an
357 # assumption breaking non-standard port/protocol entry
358 services = ('daytime', 'qotd', 'domain')
359 else:
360 services = ('echo', 'daytime', 'domain')
361 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000362 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000363 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000364 break
365 except socket.error:
366 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000367 else:
368 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000369 # Try same call with optional protocol omitted
370 port2 = socket.getservbyname(service)
371 eq(port, port2)
372 # Try udp, but don't barf it it doesn't exist
373 try:
374 udpport = socket.getservbyname(service, 'udp')
375 except socket.error:
376 udpport = None
377 else:
378 eq(udpport, port)
379 # Now make sure the lookup by port returns the same service name
380 eq(socket.getservbyport(port2), service)
381 eq(socket.getservbyport(port, 'tcp'), service)
382 if udpport is not None:
383 eq(socket.getservbyport(udpport, 'udp'), service)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000384 # Make sure getservbyport does not accept out of range ports.
385 self.assertRaises(OverflowError, socket.getservbyport, -1)
386 self.assertRaises(OverflowError, socket.getservbyport, 65536)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000387
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000388 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000389 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000390 # The default timeout should initially be None
391 self.assertEqual(socket.getdefaulttimeout(), None)
392 s = socket.socket()
393 self.assertEqual(s.gettimeout(), None)
394 s.close()
395
396 # Set the default timeout to 10, and see if it propagates
397 socket.setdefaulttimeout(10)
398 self.assertEqual(socket.getdefaulttimeout(), 10)
399 s = socket.socket()
400 self.assertEqual(s.gettimeout(), 10)
401 s.close()
402
403 # Reset the default timeout to None, and see if it propagates
404 socket.setdefaulttimeout(None)
405 self.assertEqual(socket.getdefaulttimeout(), None)
406 s = socket.socket()
407 self.assertEqual(s.gettimeout(), None)
408 s.close()
409
410 # Check that setting it to an invalid value raises ValueError
411 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
412
413 # Check that setting it to an invalid type raises TypeError
414 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
415
Benjamin Petersonf91df042009-02-13 02:50:59 +0000416 def testIPv4_inet_aton_fourbytes(self):
417 if not hasattr(socket, 'inet_aton'):
418 return # No inet_aton, nothing to check
419 # Test that issue1008086 and issue767150 are fixed.
420 # It must return 4 bytes.
421 self.assertEquals(b'\x00'*4, socket.inet_aton('0.0.0.0'))
422 self.assertEquals(b'\xff'*4, socket.inet_aton('255.255.255.255'))
423
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000424 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000425 if not hasattr(socket, 'inet_pton'):
426 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000427 from socket import inet_aton as f, inet_pton, AF_INET
428 g = lambda a: inet_pton(AF_INET, a)
429
Guido van Rossumb5b22702007-05-18 18:55:53 +0000430 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
431 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
432 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
433 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
434 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000435
Guido van Rossumb5b22702007-05-18 18:55:53 +0000436 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
437 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
438 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
439 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000440
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000441 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000442 if not hasattr(socket, 'inet_pton'):
443 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000444 try:
445 from socket import inet_pton, AF_INET6, has_ipv6
446 if not has_ipv6:
447 return
448 except ImportError:
449 return
450 f = lambda a: inet_pton(AF_INET6, a)
451
Guido van Rossum540d9872007-08-17 03:51:09 +0000452 self.assertEquals(b'\x00' * 16, f('::'))
453 self.assertEquals(b'\x00' * 16, f('0::0'))
454 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000455 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000456 b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000457 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
458 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000459
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000460 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000461 if not hasattr(socket, 'inet_ntop'):
462 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000463 from socket import inet_ntoa as f, inet_ntop, AF_INET
464 g = lambda a: inet_ntop(AF_INET, a)
465
Guido van Rossumb5b22702007-05-18 18:55:53 +0000466 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
467 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
468 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
469 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000470
Guido van Rossumb5b22702007-05-18 18:55:53 +0000471 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
472 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
473 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000474
475 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000476 if not hasattr(socket, 'inet_ntop'):
477 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000478 try:
479 from socket import inet_ntop, AF_INET6, has_ipv6
480 if not has_ipv6:
481 return
482 except ImportError:
483 return
484 f = lambda a: inet_ntop(AF_INET6, a)
485
Guido van Rossum540d9872007-08-17 03:51:09 +0000486 self.assertEquals('::', f(b'\x00' * 16))
487 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000488 self.assertEquals(
489 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000490 f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000491 )
492
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000493 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000494
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000495 def _get_unused_port(self, bind_address='0.0.0.0'):
496 """Use a temporary socket to elicit an unused ephemeral port.
Christian Heimes5e696852008-04-09 08:37:03 +0000497
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000498 Args:
499 bind_address: Hostname or IP address to search for a port on.
500
501 Returns: A most likely to be unused port.
502 """
503 tempsock = socket.socket()
504 tempsock.bind((bind_address, 0))
505 host, port = tempsock.getsockname()
506 tempsock.close()
507 return port
508
509 def testSockName(self):
510 # Testing getsockname()
511 port = self._get_unused_port()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000512 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Christian Heimes5e696852008-04-09 08:37:03 +0000513 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000514 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000515 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
516 # it reasonable to get the host's addr in addition to 0.0.0.0.
517 # At least for eCos. This is required for the S/390 to pass.
518 my_ip_addr = socket.gethostbyname(socket.gethostname())
Georg Brandlab91fde2009-08-13 08:51:18 +0000519 self.assertTrue(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +0000520 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000521
522 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000523 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000524 # We know a socket should start without reuse==0
525 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
526 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000527 self.assertFalse(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000528
529 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000530 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000531 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
532 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
533 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000534 self.assertFalse(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000535
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000536 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000537 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000538 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
539 sock.settimeout(1)
540 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000541 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000542
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000543 def testNewAttributes(self):
544 # testing .family, .type and .protocol
545 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
546 self.assertEqual(sock.family, socket.AF_INET)
547 self.assertEqual(sock.type, socket.SOCK_STREAM)
548 self.assertEqual(sock.proto, 0)
549 sock.close()
550
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000551 def test_getsockaddrarg(self):
552 host = '0.0.0.0'
553 port = self._get_unused_port(bind_address=host)
554 big_port = port + 65536
555 neg_port = port - 65536
556 sock = socket.socket()
557 try:
558 self.assertRaises(OverflowError, sock.bind, (host, big_port))
559 self.assertRaises(OverflowError, sock.bind, (host, neg_port))
560 sock.bind((host, port))
561 finally:
562 sock.close()
563
Christian Heimesfaf2f632008-01-06 16:59:19 +0000564 def test_sock_ioctl(self):
565 if os.name != "nt":
566 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000567 self.assertTrue(hasattr(socket.socket, 'ioctl'))
568 self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
569 self.assertTrue(hasattr(socket, 'RCVALL_ON'))
570 self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
Christian Heimesfaf2f632008-01-06 16:59:19 +0000571
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000572 def testGetaddrinfo(self):
573 try:
574 socket.getaddrinfo('localhost', 80)
575 except socket.gaierror as err:
576 if err.errno == socket.EAI_SERVICE:
577 # see http://bugs.python.org/issue1282647
578 self.skipTest("buggy libc version")
579 raise
580 # len of every sequence is supposed to be == 5
581 for info in socket.getaddrinfo(HOST, None):
582 self.assertEqual(len(info), 5)
583 # host can be a domain name, a string representation of an
584 # IPv4/v6 address or None
585 socket.getaddrinfo('localhost', 80)
586 socket.getaddrinfo('127.0.0.1', 80)
587 socket.getaddrinfo(None, 80)
588 if SUPPORTS_IPV6:
589 socket.getaddrinfo('::1', 80)
590 # port can be a string service name such as "http", a numeric
591 # port number or None
592 socket.getaddrinfo(HOST, "http")
593 socket.getaddrinfo(HOST, 80)
594 socket.getaddrinfo(HOST, None)
595 # test family and socktype filters
596 infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
597 for family, _, _, _, _ in infos:
598 self.assertEqual(family, socket.AF_INET)
599 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
600 for _, socktype, _, _, _ in infos:
601 self.assertEqual(socktype, socket.SOCK_STREAM)
602 # test proto and flags arguments
Giampaolo Rodolà5b37ce62010-08-16 05:09:31 +0000603 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000604 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
605 # a server willing to support both IPv4 and IPv6 will
606 # usually do this
607 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
608 socket.AI_PASSIVE)
609
Christian Heimesfaf2f632008-01-06 16:59:19 +0000610
Antoine Pitrou08ae02f2010-09-27 18:14:43 +0000611 def check_sendall_interrupted(self, with_timeout):
612 # socketpair() is not stricly required, but it makes things easier.
613 if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
614 self.skipTest("signal.alarm and socket.socketpair required for this test")
615 # Our signal handlers clobber the C errno by calling a math function
616 # with an invalid domain value.
617 def ok_handler(*args):
618 self.assertRaises(ValueError, math.acosh, 0)
619 def raising_handler(*args):
620 self.assertRaises(ValueError, math.acosh, 0)
621 1 // 0
622 c, s = socket.socketpair()
623 old_alarm = signal.signal(signal.SIGALRM, raising_handler)
624 try:
625 if with_timeout:
626 # Just above the one second minimum for signal.alarm
627 c.settimeout(1.5)
628 with self.assertRaises(ZeroDivisionError):
629 signal.alarm(1)
630 c.sendall(b"x" * (1024**2))
631 if with_timeout:
632 signal.signal(signal.SIGALRM, ok_handler)
633 signal.alarm(1)
634 self.assertRaises(socket.timeout, c.sendall, b"x" * (1024**2))
635 finally:
636 signal.signal(signal.SIGALRM, old_alarm)
637 c.close()
638 s.close()
639
640 def test_sendall_interrupted(self):
641 self.check_sendall_interrupted(False)
642
643 def test_sendall_interrupted_with_timeout(self):
644 self.check_sendall_interrupted(True)
645
646
Guido van Rossum24e4af82002-06-12 19:18:08 +0000647class BasicTCPTest(SocketConnectedTest):
648
649 def __init__(self, methodName='runTest'):
650 SocketConnectedTest.__init__(self, methodName=methodName)
651
652 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000653 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000654 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000655 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000656
657 def _testRecv(self):
658 self.serv_conn.send(MSG)
659
660 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000661 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000662 seg1 = self.cli_conn.recv(len(MSG) - 3)
663 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000664 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000665 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000666
667 def _testOverFlowRecv(self):
668 self.serv_conn.send(MSG)
669
670 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000671 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000672 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000673 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000674
675 def _testRecvFrom(self):
676 self.serv_conn.send(MSG)
677
678 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000679 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000680 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
681 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000682 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000683 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000684
685 def _testOverFlowRecvFrom(self):
686 self.serv_conn.send(MSG)
687
688 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000689 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000690 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000691 while 1:
692 read = self.cli_conn.recv(1024)
693 if not read:
694 break
Guido van Rossume531e292002-08-08 20:28:34 +0000695 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000696 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000697
698 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000699 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000700 self.serv_conn.sendall(big_chunk)
701
702 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000703 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000704 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000705 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000706 fd = self.cli_conn.fileno()
707 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
708 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000709 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000710
711 def _testFromFd(self):
712 self.serv_conn.send(MSG)
713
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000714 def testDup(self):
715 # Testing dup()
716 sock = self.cli_conn.dup()
717 msg = sock.recv(1024)
718 self.assertEqual(msg, MSG)
719
720 def _testDup(self):
721 self.serv_conn.send(MSG)
722
Guido van Rossum24e4af82002-06-12 19:18:08 +0000723 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000724 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000725 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000726 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +0000727 # wait for _testShutdown to finish: on OS X, when the server
728 # closes the connection the client also becomes disconnected,
729 # and the client's shutdown call will fail. (Issue #4397.)
730 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000731
732 def _testShutdown(self):
733 self.serv_conn.send(MSG)
734 self.serv_conn.shutdown(2)
735
736class BasicUDPTest(ThreadedUDPSocketTest):
737
738 def __init__(self, methodName='runTest'):
739 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
740
741 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000742 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000743 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000744 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000745
746 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000747 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000748
Guido van Rossum1c938012002-06-12 21:17:20 +0000749 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000750 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000751 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000752 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000753
Guido van Rossum1c938012002-06-12 21:17:20 +0000754 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000755 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000756
Guido van Rossumd8faa362007-04-27 19:54:29 +0000757 def testRecvFromNegative(self):
758 # Negative lengths passed to recvfrom should give ValueError.
759 self.assertRaises(ValueError, self.serv.recvfrom, -1)
760
761 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000762 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000764class TCPCloserTest(ThreadedTCPSocketTest):
765
766 def testClose(self):
767 conn, addr = self.serv.accept()
768 conn.close()
769
770 sd = self.cli
771 read, write, err = select.select([sd], [], [], 1.0)
772 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000773 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000774
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000775 # Calling close() many times should be safe.
776 conn.close()
777 conn.close()
778
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000779 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000780 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000781 time.sleep(1.0)
782
Dave Cole331708b2004-08-09 04:51:41 +0000783class BasicSocketPairTest(SocketPairTest):
784
785 def __init__(self, methodName='runTest'):
786 SocketPairTest.__init__(self, methodName=methodName)
787
788 def testRecv(self):
789 msg = self.serv.recv(1024)
790 self.assertEqual(msg, MSG)
791
792 def _testRecv(self):
793 self.cli.send(MSG)
794
795 def testSend(self):
796 self.serv.send(MSG)
797
798 def _testSend(self):
799 msg = self.cli.recv(1024)
800 self.assertEqual(msg, MSG)
801
Guido van Rossum24e4af82002-06-12 19:18:08 +0000802class NonBlockingTCPTests(ThreadedTCPSocketTest):
803
804 def __init__(self, methodName='runTest'):
805 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
806
807 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000808 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000809 self.serv.setblocking(0)
810 start = time.time()
811 try:
812 self.serv.accept()
813 except socket.error:
814 pass
815 end = time.time()
Georg Brandlab91fde2009-08-13 08:51:18 +0000816 self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000817
818 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000819 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000820
Guido van Rossum24e4af82002-06-12 19:18:08 +0000821 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000822 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000823 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000824 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000825 conn, addr = self.serv.accept()
826 except socket.error:
827 pass
828 else:
829 self.fail("Error trying to do non-blocking accept.")
830 read, write, err = select.select([self.serv], [], [])
831 if self.serv in read:
832 conn, addr = self.serv.accept()
833 else:
834 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000835
Guido van Rossum24e4af82002-06-12 19:18:08 +0000836 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000837 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +0000838 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000839
840 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000841 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000842 conn, addr = self.serv.accept()
843
844 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000845 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +0000846 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000847
848 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000849 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000850 conn, addr = self.serv.accept()
851 conn.setblocking(0)
852 try:
853 msg = conn.recv(len(MSG))
854 except socket.error:
855 pass
856 else:
857 self.fail("Error trying to do non-blocking recv.")
858 read, write, err = select.select([conn], [], [])
859 if conn in read:
860 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000861 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000862 else:
863 self.fail("Error during select call to non-blocking socket.")
864
865 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000866 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000867 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000868 self.cli.send(MSG)
869
870class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000871 """Unit tests for the object returned by socket.makefile()
872
Antoine Pitrou674f4002010-10-13 16:25:33 +0000873 self.read_file is the io object returned by makefile() on
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000874 the client connection. You can read from this file to
875 get output from the server.
876
Antoine Pitrou674f4002010-10-13 16:25:33 +0000877 self.write_file is the io object returned by makefile() on the
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000878 server connection. You can write to this file to send output
879 to the client.
880 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000881
Guido van Rossume9f66142002-08-07 15:46:19 +0000882 bufsize = -1 # Use default buffer size
Antoine Pitrou674f4002010-10-13 16:25:33 +0000883 encoding = 'utf8'
884 errors = 'strict'
885 newline = None
886
887 read_mode = 'rb'
888 read_msg = MSG
889 write_mode = 'wb'
890 write_msg = MSG
Guido van Rossume9f66142002-08-07 15:46:19 +0000891
Guido van Rossum24e4af82002-06-12 19:18:08 +0000892 def __init__(self, methodName='runTest'):
893 SocketConnectedTest.__init__(self, methodName=methodName)
894
895 def setUp(self):
896 SocketConnectedTest.setUp(self)
Antoine Pitrou674f4002010-10-13 16:25:33 +0000897 self.read_file = self.cli_conn.makefile(
898 self.read_mode, self.bufsize,
899 encoding = self.encoding,
900 errors = self.errors,
901 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000902
903 def tearDown(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000904 self.read_file.close()
905 self.assertTrue(self.read_file.closed)
906 self.read_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +0000907 SocketConnectedTest.tearDown(self)
908
909 def clientSetUp(self):
910 SocketConnectedTest.clientSetUp(self)
Antoine Pitrou674f4002010-10-13 16:25:33 +0000911 self.write_file = self.serv_conn.makefile(
912 self.write_mode, self.bufsize,
913 encoding = self.encoding,
914 errors = self.errors,
915 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000916
917 def clientTearDown(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000918 self.write_file.close()
919 self.assertTrue(self.write_file.closed)
920 self.write_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +0000921 SocketConnectedTest.clientTearDown(self)
922
923 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000924 # Performing small file read test
Antoine Pitrou674f4002010-10-13 16:25:33 +0000925 first_seg = self.read_file.read(len(self.read_msg)-3)
926 second_seg = self.read_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000927 msg = first_seg + second_seg
Antoine Pitrou674f4002010-10-13 16:25:33 +0000928 self.assertEqual(msg, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000929
930 def _testSmallRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000931 self.write_file.write(self.write_msg)
932 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000933
Guido van Rossum8c943832002-08-08 01:00:28 +0000934 def testFullRead(self):
935 # read until EOF
Antoine Pitrou674f4002010-10-13 16:25:33 +0000936 msg = self.read_file.read()
937 self.assertEqual(msg, self.read_msg)
Guido van Rossum8c943832002-08-08 01:00:28 +0000938
939 def _testFullRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000940 self.write_file.write(self.write_msg)
941 self.write_file.close()
Guido van Rossum8c943832002-08-08 01:00:28 +0000942
Guido van Rossum24e4af82002-06-12 19:18:08 +0000943 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000944 # Performing unbuffered file read test
Antoine Pitrou674f4002010-10-13 16:25:33 +0000945 buf = type(self.read_msg)()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000946 while 1:
Antoine Pitrou674f4002010-10-13 16:25:33 +0000947 char = self.read_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000948 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000949 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000950 buf += char
Antoine Pitrou674f4002010-10-13 16:25:33 +0000951 self.assertEqual(buf, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000952
953 def _testUnbufferedRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000954 self.write_file.write(self.write_msg)
955 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000956
957 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000958 # Performing file readline test
Antoine Pitrou674f4002010-10-13 16:25:33 +0000959 line = self.read_file.readline()
960 self.assertEqual(line, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000961
962 def _testReadline(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000963 self.write_file.write(self.write_msg)
964 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000965
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000966 def testCloseAfterMakefile(self):
967 # The file returned by makefile should keep the socket open.
968 self.cli_conn.close()
969 # read until EOF
Antoine Pitrou674f4002010-10-13 16:25:33 +0000970 msg = self.read_file.read()
971 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000972
973 def _testCloseAfterMakefile(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000974 self.write_file.write(self.write_msg)
975 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000976
977 def testMakefileAfterMakefileClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000978 self.read_file.close()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000979 msg = self.cli_conn.recv(len(MSG))
Antoine Pitrou674f4002010-10-13 16:25:33 +0000980 if isinstance(self.read_msg, str):
981 msg = msg.decode()
982 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000983
984 def _testMakefileAfterMakefileClose(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
Tim Peters116d83c2004-03-28 02:20:45 +0000988 def testClosedAttr(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000989 self.assertTrue(not self.read_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +0000990
991 def _testClosedAttr(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000992 self.assertTrue(not self.write_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +0000993
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000994 def testAttributes(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000995 self.assertEqual(self.read_file.mode, self.read_mode)
996 self.assertEqual(self.read_file.name, self.cli_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000997
998 def _testAttributes(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000999 self.assertEqual(self.write_file.mode, self.write_mode)
1000 self.assertEqual(self.write_file.name, self.serv_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001001
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001002 def testRealClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001003 self.read_file.close()
1004 self.assertRaises(ValueError, self.read_file.fileno)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001005 self.cli_conn.close()
1006 self.assertRaises(socket.error, self.cli_conn.getsockname)
1007
1008 def _testRealClose(self):
1009 pass
1010
1011
Guido van Rossume9f66142002-08-07 15:46:19 +00001012class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
1013
1014 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +00001015
Guido van Rossume9f66142002-08-07 15:46:19 +00001016 In this case (and in this case only), it should be possible to
1017 create a file object, read a line from it, create another file
1018 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +00001019 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +00001020 when reading multiple requests from the same socket."""
1021
1022 bufsize = 0 # Use unbuffered mode
1023
1024 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001025 # Read a line, create a new file object, read another line with it
Antoine Pitrou674f4002010-10-13 16:25:33 +00001026 line = self.read_file.readline() # first line
1027 self.assertEqual(line, b"A. " + self.write_msg) # first line
1028 self.read_file = self.cli_conn.makefile('rb', 0)
1029 line = self.read_file.readline() # second line
1030 self.assertEqual(line, b"B. " + self.write_msg) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +00001031
1032 def _testUnbufferedReadline(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001033 self.write_file.write(b"A. " + self.write_msg)
1034 self.write_file.write(b"B. " + self.write_msg)
1035 self.write_file.flush()
Guido van Rossume9f66142002-08-07 15:46:19 +00001036
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001037 def testMakefileClose(self):
1038 # The file returned by makefile should keep the socket open...
1039 self.cli_conn.close()
1040 msg = self.cli_conn.recv(1024)
Antoine Pitrou674f4002010-10-13 16:25:33 +00001041 self.assertEqual(msg, self.read_msg)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001042 # ...until the file is itself closed
Antoine Pitrou674f4002010-10-13 16:25:33 +00001043 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001044 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
1045
1046 def _testMakefileClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001047 self.write_file.write(self.write_msg)
1048 self.write_file.flush()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001049
1050 def testMakefileCloseSocketDestroy(self):
1051 refcount_before = sys.getrefcount(self.cli_conn)
Antoine Pitrou674f4002010-10-13 16:25:33 +00001052 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001053 refcount_after = sys.getrefcount(self.cli_conn)
1054 self.assertEqual(refcount_before - 1, refcount_after)
1055
1056 def _testMakefileCloseSocketDestroy(self):
1057 pass
1058
1059
Guido van Rossum8c943832002-08-08 01:00:28 +00001060class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1061
1062 bufsize = 1 # Default-buffered for reading; line-buffered for writing
1063
1064
1065class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1066
1067 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +00001068
Thomas Woutersb2137042007-02-01 18:02:27 +00001069
Antoine Pitrou674f4002010-10-13 16:25:33 +00001070class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase):
1071 """Tests for socket.makefile() in text mode (rather than binary)"""
1072
1073 read_mode = 'r'
1074 read_msg = MSG.decode('utf8')
1075 write_mode = 'wb'
1076 write_msg = MSG
1077 newline = ''
1078
1079
1080class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase):
1081 """Tests for socket.makefile() in text mode (rather than binary)"""
1082
1083 read_mode = 'rb'
1084 read_msg = MSG
1085 write_mode = 'w'
1086 write_msg = MSG.decode('utf8')
1087 newline = ''
1088
1089
1090class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase):
1091 """Tests for socket.makefile() in text mode (rather than binary)"""
1092
1093 read_mode = 'r'
1094 read_msg = MSG.decode('utf8')
1095 write_mode = 'w'
1096 write_msg = MSG.decode('utf8')
1097 newline = ''
1098
1099
Guido van Rossumd8faa362007-04-27 19:54:29 +00001100class NetworkConnectionTest(object):
1101 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001102
Guido van Rossumd8faa362007-04-27 19:54:29 +00001103 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001104 # We're inherited below by BasicTCPTest2, which also inherits
1105 # BasicTCPTest, which defines self.port referenced below.
1106 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001107 self.serv_conn = self.cli
1108
1109class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
1110 """Tests that NetworkConnection does not break existing TCP functionality.
1111 """
1112
1113class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001114
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001115 class MockSocket(socket.socket):
1116 def connect(self, *args):
1117 raise socket.timeout('timed out')
1118
1119 @contextlib.contextmanager
1120 def mocked_socket_module(self):
1121 """Return a socket which times out on connect"""
1122 old_socket = socket.socket
1123 socket.socket = self.MockSocket
1124 try:
1125 yield
1126 finally:
1127 socket.socket = old_socket
1128
1129 def test_connect(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001130 port = support.find_unused_port()
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001131 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1132 try:
1133 cli.connect((HOST, port))
1134 except socket.error as err:
1135 self.assertEqual(err.errno, errno.ECONNREFUSED)
1136 else:
1137 self.fail("socket.error not raised")
1138
1139 def test_create_connection(self):
1140 # Issue #9792: errors raised by create_connection() should have
1141 # a proper errno attribute.
1142 port = support.find_unused_port()
1143 try:
1144 socket.create_connection((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_timeout(self):
1151 # Issue #9792: create_connection() should not recast timeout errors
1152 # as generic socket errors.
1153 with self.mocked_socket_module():
1154 with self.assertRaises(socket.timeout):
1155 socket.create_connection((HOST, 1234))
1156
Guido van Rossumd8faa362007-04-27 19:54:29 +00001157
1158class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
1159
1160 def __init__(self, methodName='runTest'):
1161 SocketTCPTest.__init__(self, methodName=methodName)
1162 ThreadableTest.__init__(self)
1163
1164 def clientSetUp(self):
1165 pass
1166
1167 def clientTearDown(self):
1168 self.cli.close()
1169 self.cli = None
1170 ThreadableTest.clientTearDown(self)
1171
1172 def _justAccept(self):
1173 conn, addr = self.serv.accept()
1174
1175 testFamily = _justAccept
1176 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001177 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001178 self.assertEqual(self.cli.family, 2)
1179
1180 testTimeoutDefault = _justAccept
1181 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001182 # passing no explicit timeout uses socket's global default
Georg Brandlab91fde2009-08-13 08:51:18 +00001183 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001184 socket.setdefaulttimeout(42)
1185 try:
1186 self.cli = socket.create_connection((HOST, self.port))
1187 finally:
1188 socket.setdefaulttimeout(None)
1189 self.assertEquals(self.cli.gettimeout(), 42)
1190
1191 testTimeoutNone = _justAccept
1192 def _testTimeoutNone(self):
1193 # None timeout means the same as sock.settimeout(None)
Georg Brandlab91fde2009-08-13 08:51:18 +00001194 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001195 socket.setdefaulttimeout(30)
1196 try:
1197 self.cli = socket.create_connection((HOST, self.port), timeout=None)
1198 finally:
1199 socket.setdefaulttimeout(None)
1200 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001201
1202 testTimeoutValueNamed = _justAccept
1203 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001204 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001205 self.assertEqual(self.cli.gettimeout(), 30)
1206
1207 testTimeoutValueNonamed = _justAccept
1208 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001209 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001210 self.assertEqual(self.cli.gettimeout(), 30)
1211
Guido van Rossumd8faa362007-04-27 19:54:29 +00001212class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1213
1214 def __init__(self, methodName='runTest'):
1215 SocketTCPTest.__init__(self, methodName=methodName)
1216 ThreadableTest.__init__(self)
1217
1218 def clientSetUp(self):
1219 pass
1220
1221 def clientTearDown(self):
1222 self.cli.close()
1223 self.cli = None
1224 ThreadableTest.clientTearDown(self)
1225
1226 def testInsideTimeout(self):
1227 conn, addr = self.serv.accept()
1228 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001229 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001230 testOutsideTimeout = testInsideTimeout
1231
1232 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001233 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001234 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001235 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001236
1237 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001238 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Georg Brandlab91fde2009-08-13 08:51:18 +00001239 self.assertRaises(socket.timeout, lambda: sock.recv(5))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001240
1241
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001242class TCPTimeoutTest(SocketTCPTest):
1243
1244 def testTCPTimeout(self):
1245 def raise_timeout(*args, **kwargs):
1246 self.serv.settimeout(1.0)
1247 self.serv.accept()
Georg Brandlab91fde2009-08-13 08:51:18 +00001248 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001249 "Error generating a timeout exception (TCP)")
1250
1251 def testTimeoutZero(self):
1252 ok = False
1253 try:
1254 self.serv.settimeout(0.0)
1255 foo = self.serv.accept()
1256 except socket.timeout:
1257 self.fail("caught timeout instead of error (TCP)")
1258 except socket.error:
1259 ok = True
1260 except:
1261 self.fail("caught unexpected exception (TCP)")
1262 if not ok:
1263 self.fail("accept() returned success when we did not expect it")
1264
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001265 def testInterruptedTimeout(self):
1266 # XXX I don't know how to do this test on MSWindows or any other
1267 # plaform that doesn't support signal.alarm() or os.kill(), though
1268 # the bug should have existed on all platforms.
1269 if not hasattr(signal, "alarm"):
1270 return # can only test on *nix
1271 self.serv.settimeout(5.0) # must be longer than alarm
1272 class Alarm(Exception):
1273 pass
1274 def alarm_handler(signal, frame):
1275 raise Alarm
1276 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1277 try:
1278 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1279 try:
1280 foo = self.serv.accept()
1281 except socket.timeout:
1282 self.fail("caught timeout instead of Alarm")
1283 except Alarm:
1284 pass
1285 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001286 self.fail("caught other exception instead of Alarm:"
1287 " %s(%s):\n%s" %
1288 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001289 else:
1290 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001291 finally:
1292 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001293 except Alarm:
1294 self.fail("got Alarm in wrong place")
1295 finally:
1296 # no alarm can be pending. Safe to restore old handler.
1297 signal.signal(signal.SIGALRM, old_alarm)
1298
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001299class UDPTimeoutTest(SocketTCPTest):
1300
1301 def testUDPTimeout(self):
1302 def raise_timeout(*args, **kwargs):
1303 self.serv.settimeout(1.0)
1304 self.serv.recv(1024)
Georg Brandlab91fde2009-08-13 08:51:18 +00001305 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001306 "Error generating a timeout exception (UDP)")
1307
1308 def testTimeoutZero(self):
1309 ok = False
1310 try:
1311 self.serv.settimeout(0.0)
1312 foo = self.serv.recv(1024)
1313 except socket.timeout:
1314 self.fail("caught timeout instead of error (UDP)")
1315 except socket.error:
1316 ok = True
1317 except:
1318 self.fail("caught unexpected exception (UDP)")
1319 if not ok:
1320 self.fail("recv() returned success when we did not expect it")
1321
1322class TestExceptions(unittest.TestCase):
1323
1324 def testExceptionTree(self):
Georg Brandlab91fde2009-08-13 08:51:18 +00001325 self.assertTrue(issubclass(socket.error, Exception))
1326 self.assertTrue(issubclass(socket.herror, socket.error))
1327 self.assertTrue(issubclass(socket.gaierror, socket.error))
1328 self.assertTrue(issubclass(socket.timeout, socket.error))
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001329
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001330class TestLinuxAbstractNamespace(unittest.TestCase):
1331
1332 UNIX_PATH_MAX = 108
1333
1334 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001335 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001336 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1337 s1.bind(address)
1338 s1.listen(1)
1339 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1340 s2.connect(s1.getsockname())
1341 s1.accept()
1342 self.assertEqual(s1.getsockname(), address)
1343 self.assertEqual(s2.getpeername(), address)
1344
1345 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001346 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001347 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1348 s.bind(address)
1349 self.assertEqual(s.getsockname(), address)
1350
1351 def testNameOverflow(self):
1352 address = "\x00" + "h" * self.UNIX_PATH_MAX
1353 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1354 self.assertRaises(socket.error, s.bind, address)
1355
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001356
Thomas Wouters477c8d52006-05-27 19:21:47 +00001357class BufferIOTest(SocketConnectedTest):
1358 """
1359 Test the buffer versions of socket.recv() and socket.send().
1360 """
1361 def __init__(self, methodName='runTest'):
1362 SocketConnectedTest.__init__(self, methodName=methodName)
1363
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001364 def testRecvInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001365 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001366 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001367 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001368 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001369 self.assertEqual(msg, MSG)
1370
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001371 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001372 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001373 self.serv_conn.send(buf)
1374
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001375 def testRecvFromInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001376 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001377 nbytes, addr = self.cli_conn.recvfrom_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 _testRecvFromInto(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
Christian Heimes043d6f62008-01-07 17:19:16 +00001386
1387TIPC_STYPE = 2000
1388TIPC_LOWER = 200
1389TIPC_UPPER = 210
1390
1391def isTipcAvailable():
1392 """Check if the TIPC module is loaded
1393
1394 The TIPC module is not loaded automatically on Ubuntu and probably
1395 other Linux distros.
1396 """
1397 if not hasattr(socket, "AF_TIPC"):
1398 return False
1399 if not os.path.isfile("/proc/modules"):
1400 return False
1401 with open("/proc/modules") as f:
1402 for line in f:
1403 if line.startswith("tipc "):
1404 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001405 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001406 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1407 return False
1408
1409class TIPCTest (unittest.TestCase):
1410 def testRDM(self):
1411 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1412 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1413
1414 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1415 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1416 TIPC_LOWER, TIPC_UPPER)
1417 srv.bind(srvaddr)
1418
1419 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1420 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1421 cli.sendto(MSG, sendaddr)
1422
1423 msg, recvaddr = srv.recvfrom(1024)
1424
1425 self.assertEqual(cli.getsockname(), recvaddr)
1426 self.assertEqual(msg, MSG)
1427
1428
1429class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1430 def __init__(self, methodName = 'runTest'):
1431 unittest.TestCase.__init__(self, methodName = methodName)
1432 ThreadableTest.__init__(self)
1433
1434 def setUp(self):
1435 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1436 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1437 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1438 TIPC_LOWER, TIPC_UPPER)
1439 self.srv.bind(srvaddr)
1440 self.srv.listen(5)
1441 self.serverExplicitReady()
1442 self.conn, self.connaddr = self.srv.accept()
1443
1444 def clientSetUp(self):
1445 # The is a hittable race between serverExplicitReady() and the
1446 # accept() call; sleep a little while to avoid it, otherwise
1447 # we could get an exception
1448 time.sleep(0.1)
1449 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1450 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1451 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1452 self.cli.connect(addr)
1453 self.cliaddr = self.cli.getsockname()
1454
1455 def testStream(self):
1456 msg = self.conn.recv(1024)
1457 self.assertEqual(msg, MSG)
1458 self.assertEqual(self.cliaddr, self.connaddr)
1459
1460 def _testStream(self):
1461 self.cli.send(MSG)
1462 self.cli.close()
1463
1464
Guido van Rossumb995eb72002-07-31 16:08:40 +00001465def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001466 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001467 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001468 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001469 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001470
1471 tests.extend([
1472 NonBlockingTCPTests,
1473 FileObjectClassTestCase,
1474 UnbufferedFileObjectClassTestCase,
1475 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001476 SmallBufferedFileObjectClassTestCase,
Antoine Pitrou674f4002010-10-13 16:25:33 +00001477 UnicodeReadFileObjectClassTestCase,
1478 UnicodeWriteFileObjectClassTestCase,
1479 UnicodeReadWriteFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001480 NetworkConnectionNoServer,
1481 NetworkConnectionAttributesTest,
1482 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001483 ])
Dave Cole331708b2004-08-09 04:51:41 +00001484 if hasattr(socket, "socketpair"):
1485 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001486 if sys.platform == 'linux2':
1487 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001488 if isTipcAvailable():
1489 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001490 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001491
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001492 thread_info = support.threading_setup()
1493 support.run_unittest(*tests)
1494 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001495
1496if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001497 test_main()