blob: 6a9497bc7d2f0054c71e408b23685dac3a0f1611 [file] [log] [blame]
Guido van Rossum24e4af82002-06-12 19:18:08 +00001#!/usr/bin/env python
Barry Warsawcf3d4b51997-01-03 20:03:32 +00002
Guido van Rossum24e4af82002-06-12 19:18:08 +00003import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test import support
Barry Warsawcf3d4b51997-01-03 20:03:32 +00005
Christian Heimes5e696852008-04-09 08:37:03 +00006import errno
Barry Warsawcf3d4b51997-01-03 20:03:32 +00007import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00008import select
Georg Brandl2067bfd2008-05-25 13:05:15 +00009import _thread as thread
10import threading
Christian Heimesbbe741d2008-03-28 10:53:29 +000011import time
12import traceback
Alexandre Vassalottif260e442008-05-11 19:59:59 +000013import queue
Jack Jansen522e7692002-09-06 21:57:50 +000014import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000015import os
16import array
Antoine Pitrou4d7979b2010-09-07 21:22:56 +000017import contextlib
Raymond Hettinger027bb632004-05-31 03:09:25 +000018from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019import signal
Antoine Pitrou08ae02f2010-09-27 18:14:43 +000020import math
Barry Warsawcf3d4b51997-01-03 20:03:32 +000021
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +000022def try_address(host, port=0, family=socket.AF_INET):
23 """Try to bind a socket on the given host:port and return True
24 if that has been possible."""
25 try:
26 sock = socket.socket(family, socket.SOCK_STREAM)
27 sock.bind((host, port))
28 except (socket.error, socket.gaierror):
29 return False
30 else:
31 sock.close()
32 return True
33
Benjamin Petersonee8712c2008-05-20 21:35:26 +000034HOST = support.HOST
Antoine Pitrou674f4002010-10-13 16:25:33 +000035MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf8') ## test unicode string and carriage return
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +000036SUPPORTS_IPV6 = socket.has_ipv6 and try_address('::1', family=socket.AF_INET6)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000037
Guido van Rossum24e4af82002-06-12 19:18:08 +000038class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000039
Guido van Rossum24e4af82002-06-12 19:18:08 +000040 def setUp(self):
41 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000042 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000043 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000044
Guido van Rossum24e4af82002-06-12 19:18:08 +000045 def tearDown(self):
46 self.serv.close()
47 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000048
Guido van Rossum24e4af82002-06-12 19:18:08 +000049class SocketUDPTest(unittest.TestCase):
50
51 def setUp(self):
52 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000053 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000054
55 def tearDown(self):
56 self.serv.close()
57 self.serv = None
58
59class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000060 """Threadable Test class
61
62 The ThreadableTest class makes it easy to create a threaded
63 client/server pair from an existing unit test. To create a
64 new threaded class from an existing unit test, use multiple
65 inheritance:
66
67 class NewClass (OldClass, ThreadableTest):
68 pass
69
70 This class defines two new fixture functions with obvious
71 purposes for overriding:
72
73 clientSetUp ()
74 clientTearDown ()
75
76 Any new test functions within the class must then define
77 tests in pairs, where the test name is preceeded with a
78 '_' to indicate the client portion of the test. Ex:
79
80 def testFoo(self):
81 # Server portion
82
83 def _testFoo(self):
84 # Client portion
85
86 Any exceptions raised by the clients during their tests
87 are caught and transferred to the main thread to alert
88 the testing framework.
89
90 Note, the server setup function cannot call any blocking
91 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +000092 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000093 the blocking call (such as in setting up a client/server
94 connection and performing the accept() in setUp().
95 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000096
97 def __init__(self):
98 # Swap the true setup function
99 self.__setUp = self.setUp
100 self.__tearDown = self.tearDown
101 self.setUp = self._setUp
102 self.tearDown = self._tearDown
103
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000104 def serverExplicitReady(self):
105 """This method allows the server to explicitly indicate that
106 it wants the client thread to proceed. This is useful if the
107 server is about to execute a blocking routine that is
108 dependent upon the client thread during its setup routine."""
109 self.server_ready.set()
110
Guido van Rossum24e4af82002-06-12 19:18:08 +0000111 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000112 self.server_ready = threading.Event()
113 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000114 self.done = threading.Event()
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000115 self.queue = queue.Queue(1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000116
117 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000118 methodname = self.id()
119 i = methodname.rfind('.')
120 methodname = methodname[i+1:]
121 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000122 self.client_thread = thread.start_new_thread(
123 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000124
125 self.__setUp()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000126 if not self.server_ready.is_set():
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000127 self.server_ready.set()
128 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000129
130 def _tearDown(self):
131 self.__tearDown()
132 self.done.wait()
133
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000134 if self.queue.qsize():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000135 msg = self.queue.get()
136 self.fail(msg)
137
138 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000139 self.server_ready.wait()
140 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000141 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000142 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000143 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000144 try:
145 test_func()
Guido van Rossumb940e112007-01-10 16:19:56 +0000146 except Exception as strerror:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000147 self.queue.put(strerror)
148 self.clientTearDown()
149
150 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000151 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000152
153 def clientTearDown(self):
154 self.done.set()
155 thread.exit()
156
157class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
158
159 def __init__(self, methodName='runTest'):
160 SocketTCPTest.__init__(self, methodName=methodName)
161 ThreadableTest.__init__(self)
162
163 def clientSetUp(self):
164 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
165
166 def clientTearDown(self):
167 self.cli.close()
168 self.cli = None
169 ThreadableTest.clientTearDown(self)
170
171class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
172
173 def __init__(self, methodName='runTest'):
174 SocketUDPTest.__init__(self, methodName=methodName)
175 ThreadableTest.__init__(self)
176
177 def clientSetUp(self):
178 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
179
Brian Curtin8f8ed942010-11-04 03:49:29 +0000180 def clientTearDown(self):
181 self.cli.close()
182 self.cli = None
183 ThreadableTest.clientTearDown(self)
184
Guido van Rossum24e4af82002-06-12 19:18:08 +0000185class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000186 """Socket tests for client-server connection.
187
188 self.cli_conn is a client socket connected to the server. The
189 setUp() method guarantees that it is connected to the server.
190 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000191
192 def __init__(self, methodName='runTest'):
193 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
194
195 def setUp(self):
196 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000197 # Indicate explicitly we're ready for the client thread to
198 # proceed and then perform the blocking call to accept
199 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000200 conn, addr = self.serv.accept()
201 self.cli_conn = conn
202
203 def tearDown(self):
204 self.cli_conn.close()
205 self.cli_conn = None
206 ThreadedTCPSocketTest.tearDown(self)
207
208 def clientSetUp(self):
209 ThreadedTCPSocketTest.clientSetUp(self)
Christian Heimes5e696852008-04-09 08:37:03 +0000210 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000211 self.serv_conn = self.cli
212
213 def clientTearDown(self):
214 self.serv_conn.close()
215 self.serv_conn = None
216 ThreadedTCPSocketTest.clientTearDown(self)
217
Dave Cole331708b2004-08-09 04:51:41 +0000218class SocketPairTest(unittest.TestCase, ThreadableTest):
219
220 def __init__(self, methodName='runTest'):
221 unittest.TestCase.__init__(self, methodName=methodName)
222 ThreadableTest.__init__(self)
223
224 def setUp(self):
225 self.serv, self.cli = socket.socketpair()
226
227 def tearDown(self):
228 self.serv.close()
229 self.serv = None
230
231 def clientSetUp(self):
232 pass
233
234 def clientTearDown(self):
235 self.cli.close()
236 self.cli = None
237 ThreadableTest.clientTearDown(self)
238
Tim Peters494aaee2004-08-09 18:54:11 +0000239
Guido van Rossum24e4af82002-06-12 19:18:08 +0000240#######################################################################
241## Begin Tests
242
243class GeneralModuleTests(unittest.TestCase):
244
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000245 def test_repr(self):
246 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlab91fde2009-08-13 08:51:18 +0000247 self.assertTrue(repr(s).startswith("<socket.socket object"))
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000248
Raymond Hettinger027bb632004-05-31 03:09:25 +0000249 def test_weakref(self):
250 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
251 p = proxy(s)
252 self.assertEqual(p.fileno(), s.fileno())
253 s.close()
254 s = None
255 try:
256 p.fileno()
257 except ReferenceError:
258 pass
259 else:
260 self.fail('Socket proxy still exists')
261
Guido van Rossum24e4af82002-06-12 19:18:08 +0000262 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000263 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000264 def raise_error(*args, **kwargs):
265 raise socket.error
266 def raise_herror(*args, **kwargs):
267 raise socket.herror
268 def raise_gaierror(*args, **kwargs):
269 raise socket.gaierror
Georg Brandlab91fde2009-08-13 08:51:18 +0000270 self.assertRaises(socket.error, raise_error,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000271 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000272 self.assertRaises(socket.error, raise_herror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000273 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000274 self.assertRaises(socket.error, raise_gaierror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000275 "Error raising socket exception.")
276
Ezio Melotti63e42302011-05-07 19:47:48 +0300277 def testSendtoErrors(self):
278 # Testing that sendto doens't masks failures. See #10169.
279 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
280 self.addCleanup(s.close)
281 s.bind(('', 0))
282 sockname = s.getsockname()
283 # 2 args
284 with self.assertRaises(TypeError):
285 s.sendto('\u2620', sockname)
286 with self.assertRaises(TypeError):
287 s.sendto(5j, sockname)
288 with self.assertRaises(TypeError):
289 s.sendto(b'foo', None)
290 # 3 args
291 with self.assertRaises(TypeError):
292 s.sendto('\u2620', 0, sockname)
293 with self.assertRaises(TypeError):
294 s.sendto(5j, 0, sockname)
295 with self.assertRaises(TypeError):
296 s.sendto(b'foo', 0, None)
297 with self.assertRaises(TypeError):
298 s.sendto(b'foo', 'bar', sockname)
299 with self.assertRaises(TypeError):
300 s.sendto(b'foo', None, None)
301 # wrong number of args
302 with self.assertRaises(TypeError):
303 s.sendto(b'foo')
304 with self.assertRaises(TypeError):
305 s.sendto(b'foo', 0, sockname, 4)
306
Guido van Rossum24e4af82002-06-12 19:18:08 +0000307 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000308 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000309 socket.AF_INET
310 socket.SOCK_STREAM
311 socket.SOCK_DGRAM
312 socket.SOCK_RAW
313 socket.SOCK_RDM
314 socket.SOCK_SEQPACKET
315 socket.SOL_SOCKET
316 socket.SO_REUSEADDR
317
Guido van Rossum654c11e2002-06-13 20:24:17 +0000318 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000319 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000320 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000321 try:
322 ip = socket.gethostbyname(hostname)
323 except socket.error:
324 # Probably name lookup wasn't set up right; skip this test
325 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000326 self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000327 try:
328 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
329 except socket.error:
330 # Probably a similar problem as above; skip this test
331 return
Brett Cannon01668a12005-03-11 00:04:17 +0000332 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000333 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000334 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000335 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000336
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000337 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000338 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000339 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000340 try:
341 # On some versions, this loses a reference
342 orig = sys.getrefcount(__name__)
343 socket.getnameinfo(__name__,0)
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +0000344 except TypeError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000345 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000346 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000347
Guido van Rossum24e4af82002-06-12 19:18:08 +0000348 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000349 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000350 try:
351 # On some versions, this crashes the interpreter.
352 socket.getnameinfo(('x', 0, 0, 0), 0)
353 except socket.error:
354 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000355
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000356 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000357 # This just checks that htons etc. are their own inverse,
358 # when looking at the lower 16 or 32 bits.
359 sizes = {socket.htonl: 32, socket.ntohl: 32,
360 socket.htons: 16, socket.ntohs: 16}
361 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000362 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000363 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
364 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000365
Guido van Rossuma2627af2002-09-14 00:58:46 +0000366 swapped = func(mask)
367 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000368 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000369
Guido van Rossum018919a2007-01-15 00:07:32 +0000370 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000371 good_values = [ 1, 2, 3, 1, 2, 3 ]
372 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000373 for k in good_values:
374 socket.ntohl(k)
375 socket.ntohs(k)
376 socket.htonl(k)
377 socket.htons(k)
378 for k in bad_values:
379 self.assertRaises(OverflowError, socket.ntohl, k)
380 self.assertRaises(OverflowError, socket.ntohs, k)
381 self.assertRaises(OverflowError, socket.htonl, k)
382 self.assertRaises(OverflowError, socket.htons, k)
383
Barry Warsaw11b91a02004-06-28 00:50:43 +0000384 def testGetServBy(self):
385 eq = self.assertEqual
386 # Find one service that exists, then check all the related interfaces.
387 # I've ordered this by protocols that have both a tcp and udp
388 # protocol, at least for modern Linuxes.
Gregory P. Smith397cd8a2010-10-17 04:23:21 +0000389 if (sys.platform.startswith('linux') or
390 sys.platform.startswith('freebsd') or
391 sys.platform.startswith('netbsd') or
392 sys.platform == 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000393 # avoid the 'echo' service on this platform, as there is an
394 # assumption breaking non-standard port/protocol entry
395 services = ('daytime', 'qotd', 'domain')
396 else:
397 services = ('echo', 'daytime', 'domain')
398 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000399 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000400 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000401 break
402 except socket.error:
403 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000404 else:
405 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000406 # Try same call with optional protocol omitted
407 port2 = socket.getservbyname(service)
408 eq(port, port2)
409 # Try udp, but don't barf it it doesn't exist
410 try:
411 udpport = socket.getservbyname(service, 'udp')
412 except socket.error:
413 udpport = None
414 else:
415 eq(udpport, port)
416 # Now make sure the lookup by port returns the same service name
417 eq(socket.getservbyport(port2), service)
418 eq(socket.getservbyport(port, 'tcp'), service)
419 if udpport is not None:
420 eq(socket.getservbyport(udpport, 'udp'), service)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000421 # Make sure getservbyport does not accept out of range ports.
422 self.assertRaises(OverflowError, socket.getservbyport, -1)
423 self.assertRaises(OverflowError, socket.getservbyport, 65536)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000424
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000425 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000426 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000427 # The default timeout should initially be None
428 self.assertEqual(socket.getdefaulttimeout(), None)
429 s = socket.socket()
430 self.assertEqual(s.gettimeout(), None)
431 s.close()
432
433 # Set the default timeout to 10, and see if it propagates
434 socket.setdefaulttimeout(10)
435 self.assertEqual(socket.getdefaulttimeout(), 10)
436 s = socket.socket()
437 self.assertEqual(s.gettimeout(), 10)
438 s.close()
439
440 # Reset the default timeout to None, and see if it propagates
441 socket.setdefaulttimeout(None)
442 self.assertEqual(socket.getdefaulttimeout(), None)
443 s = socket.socket()
444 self.assertEqual(s.gettimeout(), None)
445 s.close()
446
447 # Check that setting it to an invalid value raises ValueError
448 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
449
450 # Check that setting it to an invalid type raises TypeError
451 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
452
Benjamin Petersonf91df042009-02-13 02:50:59 +0000453 def testIPv4_inet_aton_fourbytes(self):
454 if not hasattr(socket, 'inet_aton'):
455 return # No inet_aton, nothing to check
456 # Test that issue1008086 and issue767150 are fixed.
457 # It must return 4 bytes.
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000458 self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0'))
459 self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255'))
Benjamin Petersonf91df042009-02-13 02:50:59 +0000460
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000461 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000462 if not hasattr(socket, 'inet_pton'):
463 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000464 from socket import inet_aton as f, inet_pton, AF_INET
465 g = lambda a: inet_pton(AF_INET, a)
466
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000467 self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0'))
468 self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0'))
469 self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
470 self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4'))
471 self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000472
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000473 self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0'))
474 self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0'))
475 self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
476 self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000477
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000478 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000479 if not hasattr(socket, 'inet_pton'):
480 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000481 try:
482 from socket import inet_pton, AF_INET6, has_ipv6
483 if not has_ipv6:
484 return
485 except ImportError:
486 return
487 f = lambda a: inet_pton(AF_INET6, a)
488
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000489 self.assertEqual(b'\x00' * 16, f('::'))
490 self.assertEqual(b'\x00' * 16, f('0::0'))
491 self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::'))
492 self.assertEqual(
Guido van Rossum67180622007-07-10 07:29:12 +0000493 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 +0000494 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
495 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000496
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000497 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000498 if not hasattr(socket, 'inet_ntop'):
499 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000500 from socket import inet_ntoa as f, inet_ntop, AF_INET
501 g = lambda a: inet_ntop(AF_INET, a)
502
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000503 self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00'))
504 self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
505 self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff'))
506 self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000507
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000508 self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00'))
509 self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
510 self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000511
512 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000513 if not hasattr(socket, 'inet_ntop'):
514 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000515 try:
516 from socket import inet_ntop, AF_INET6, has_ipv6
517 if not has_ipv6:
518 return
519 except ImportError:
520 return
521 f = lambda a: inet_ntop(AF_INET6, a)
522
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000523 self.assertEqual('::', f(b'\x00' * 16))
524 self.assertEqual('::1', f(b'\x00' * 15 + b'\x01'))
525 self.assertEqual(
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000526 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000527 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 +0000528 )
529
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000530 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000531
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000532 def _get_unused_port(self, bind_address='0.0.0.0'):
533 """Use a temporary socket to elicit an unused ephemeral port.
Christian Heimes5e696852008-04-09 08:37:03 +0000534
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000535 Args:
536 bind_address: Hostname or IP address to search for a port on.
537
538 Returns: A most likely to be unused port.
539 """
540 tempsock = socket.socket()
541 tempsock.bind((bind_address, 0))
542 host, port = tempsock.getsockname()
543 tempsock.close()
544 return port
545
546 def testSockName(self):
547 # Testing getsockname()
548 port = self._get_unused_port()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000549 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Christian Heimes5e696852008-04-09 08:37:03 +0000550 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000551 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000552 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
553 # it reasonable to get the host's addr in addition to 0.0.0.0.
554 # At least for eCos. This is required for the S/390 to pass.
Georg Brandlf65e25b2010-11-26 09:05:43 +0000555 try:
556 my_ip_addr = socket.gethostbyname(socket.gethostname())
557 except socket.error:
558 # Probably name lookup wasn't set up right; skip this test
559 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000560 self.assertTrue(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +0000561 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000562
563 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000564 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000565 # We know a socket should start without reuse==0
566 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
567 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000568 self.assertFalse(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000569
570 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000571 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000572 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
573 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
574 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000575 self.assertFalse(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000576
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000577 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000578 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000579 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
580 sock.settimeout(1)
581 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000582 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000583
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000584 def testNewAttributes(self):
585 # testing .family, .type and .protocol
586 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
587 self.assertEqual(sock.family, socket.AF_INET)
588 self.assertEqual(sock.type, socket.SOCK_STREAM)
589 self.assertEqual(sock.proto, 0)
590 sock.close()
591
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000592 def test_getsockaddrarg(self):
593 host = '0.0.0.0'
594 port = self._get_unused_port(bind_address=host)
595 big_port = port + 65536
596 neg_port = port - 65536
597 sock = socket.socket()
598 try:
599 self.assertRaises(OverflowError, sock.bind, (host, big_port))
600 self.assertRaises(OverflowError, sock.bind, (host, neg_port))
601 sock.bind((host, port))
602 finally:
603 sock.close()
604
Christian Heimesfaf2f632008-01-06 16:59:19 +0000605 def test_sock_ioctl(self):
606 if os.name != "nt":
607 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000608 self.assertTrue(hasattr(socket.socket, 'ioctl'))
609 self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
610 self.assertTrue(hasattr(socket, 'RCVALL_ON'))
611 self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
Christian Heimesfaf2f632008-01-06 16:59:19 +0000612
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000613 def testGetaddrinfo(self):
614 try:
615 socket.getaddrinfo('localhost', 80)
616 except socket.gaierror as err:
617 if err.errno == socket.EAI_SERVICE:
618 # see http://bugs.python.org/issue1282647
619 self.skipTest("buggy libc version")
620 raise
621 # len of every sequence is supposed to be == 5
622 for info in socket.getaddrinfo(HOST, None):
623 self.assertEqual(len(info), 5)
624 # host can be a domain name, a string representation of an
625 # IPv4/v6 address or None
626 socket.getaddrinfo('localhost', 80)
627 socket.getaddrinfo('127.0.0.1', 80)
628 socket.getaddrinfo(None, 80)
629 if SUPPORTS_IPV6:
630 socket.getaddrinfo('::1', 80)
631 # port can be a string service name such as "http", a numeric
632 # port number or None
633 socket.getaddrinfo(HOST, "http")
634 socket.getaddrinfo(HOST, 80)
635 socket.getaddrinfo(HOST, None)
636 # test family and socktype filters
637 infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
638 for family, _, _, _, _ in infos:
639 self.assertEqual(family, socket.AF_INET)
640 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
641 for _, socktype, _, _, _ in infos:
642 self.assertEqual(socktype, socket.SOCK_STREAM)
643 # test proto and flags arguments
Giampaolo Rodolà5b37ce62010-08-16 05:09:31 +0000644 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
Giampaolo Rodolàb384e6c2010-08-14 17:00:05 +0000645 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
646 # a server willing to support both IPv4 and IPv6 will
647 # usually do this
648 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
649 socket.AI_PASSIVE)
650
Christian Heimesfaf2f632008-01-06 16:59:19 +0000651
Antoine Pitrou08ae02f2010-09-27 18:14:43 +0000652 def check_sendall_interrupted(self, with_timeout):
653 # socketpair() is not stricly required, but it makes things easier.
654 if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
655 self.skipTest("signal.alarm and socket.socketpair required for this test")
656 # Our signal handlers clobber the C errno by calling a math function
657 # with an invalid domain value.
658 def ok_handler(*args):
659 self.assertRaises(ValueError, math.acosh, 0)
660 def raising_handler(*args):
661 self.assertRaises(ValueError, math.acosh, 0)
662 1 // 0
663 c, s = socket.socketpair()
664 old_alarm = signal.signal(signal.SIGALRM, raising_handler)
665 try:
666 if with_timeout:
667 # Just above the one second minimum for signal.alarm
668 c.settimeout(1.5)
669 with self.assertRaises(ZeroDivisionError):
670 signal.alarm(1)
671 c.sendall(b"x" * (1024**2))
672 if with_timeout:
673 signal.signal(signal.SIGALRM, ok_handler)
674 signal.alarm(1)
675 self.assertRaises(socket.timeout, c.sendall, b"x" * (1024**2))
676 finally:
677 signal.signal(signal.SIGALRM, old_alarm)
678 c.close()
679 s.close()
680
681 def test_sendall_interrupted(self):
682 self.check_sendall_interrupted(False)
683
684 def test_sendall_interrupted_with_timeout(self):
685 self.check_sendall_interrupted(True)
686
687
Guido van Rossum24e4af82002-06-12 19:18:08 +0000688class BasicTCPTest(SocketConnectedTest):
689
690 def __init__(self, methodName='runTest'):
691 SocketConnectedTest.__init__(self, methodName=methodName)
692
693 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000694 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000695 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000696 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000697
698 def _testRecv(self):
699 self.serv_conn.send(MSG)
700
701 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000702 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000703 seg1 = self.cli_conn.recv(len(MSG) - 3)
704 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000705 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000706 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000707
708 def _testOverFlowRecv(self):
709 self.serv_conn.send(MSG)
710
711 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000712 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000713 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000714 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000715
716 def _testRecvFrom(self):
717 self.serv_conn.send(MSG)
718
719 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000720 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000721 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
722 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000723 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000724 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000725
726 def _testOverFlowRecvFrom(self):
727 self.serv_conn.send(MSG)
728
729 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000730 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000731 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000732 while 1:
733 read = self.cli_conn.recv(1024)
734 if not read:
735 break
Guido van Rossume531e292002-08-08 20:28:34 +0000736 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000737 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000738
739 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000740 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000741 self.serv_conn.sendall(big_chunk)
742
743 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000744 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000745 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000746 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000747 fd = self.cli_conn.fileno()
748 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
749 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000750 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000751
752 def _testFromFd(self):
753 self.serv_conn.send(MSG)
754
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000755 def testDup(self):
756 # Testing dup()
757 sock = self.cli_conn.dup()
758 msg = sock.recv(1024)
759 self.assertEqual(msg, MSG)
760
761 def _testDup(self):
762 self.serv_conn.send(MSG)
763
Guido van Rossum24e4af82002-06-12 19:18:08 +0000764 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000765 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000766 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000767 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +0000768 # wait for _testShutdown to finish: on OS X, when the server
769 # closes the connection the client also becomes disconnected,
770 # and the client's shutdown call will fail. (Issue #4397.)
771 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000772
773 def _testShutdown(self):
774 self.serv_conn.send(MSG)
775 self.serv_conn.shutdown(2)
776
777class BasicUDPTest(ThreadedUDPSocketTest):
778
779 def __init__(self, methodName='runTest'):
780 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
781
782 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000783 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000784 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000785 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000786
787 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000788 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000789
Guido van Rossum1c938012002-06-12 21:17:20 +0000790 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000791 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000792 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000793 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000794
Guido van Rossum1c938012002-06-12 21:17:20 +0000795 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000796 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000797
Guido van Rossumd8faa362007-04-27 19:54:29 +0000798 def testRecvFromNegative(self):
799 # Negative lengths passed to recvfrom should give ValueError.
800 self.assertRaises(ValueError, self.serv.recvfrom, -1)
801
802 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000803 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000804
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000805class TCPCloserTest(ThreadedTCPSocketTest):
806
807 def testClose(self):
808 conn, addr = self.serv.accept()
809 conn.close()
810
811 sd = self.cli
812 read, write, err = select.select([sd], [], [], 1.0)
813 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000814 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000815
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000816 # Calling close() many times should be safe.
817 conn.close()
818 conn.close()
819
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000820 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000821 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000822 time.sleep(1.0)
823
Dave Cole331708b2004-08-09 04:51:41 +0000824class BasicSocketPairTest(SocketPairTest):
825
826 def __init__(self, methodName='runTest'):
827 SocketPairTest.__init__(self, methodName=methodName)
828
829 def testRecv(self):
830 msg = self.serv.recv(1024)
831 self.assertEqual(msg, MSG)
832
833 def _testRecv(self):
834 self.cli.send(MSG)
835
836 def testSend(self):
837 self.serv.send(MSG)
838
839 def _testSend(self):
840 msg = self.cli.recv(1024)
841 self.assertEqual(msg, MSG)
842
Guido van Rossum24e4af82002-06-12 19:18:08 +0000843class NonBlockingTCPTests(ThreadedTCPSocketTest):
844
845 def __init__(self, methodName='runTest'):
846 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
847
848 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000849 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000850 self.serv.setblocking(0)
851 start = time.time()
852 try:
853 self.serv.accept()
854 except socket.error:
855 pass
856 end = time.time()
Georg Brandlab91fde2009-08-13 08:51:18 +0000857 self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000858
859 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000860 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000861
Guido van Rossum24e4af82002-06-12 19:18:08 +0000862 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000863 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000864 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000865 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000866 conn, addr = self.serv.accept()
867 except socket.error:
868 pass
869 else:
870 self.fail("Error trying to do non-blocking accept.")
871 read, write, err = select.select([self.serv], [], [])
872 if self.serv in read:
873 conn, addr = self.serv.accept()
874 else:
875 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000876
Guido van Rossum24e4af82002-06-12 19:18:08 +0000877 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000878 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +0000879 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000880
881 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000882 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000883 conn, addr = self.serv.accept()
884
885 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000886 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +0000887 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000888
889 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000890 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000891 conn, addr = self.serv.accept()
892 conn.setblocking(0)
893 try:
894 msg = conn.recv(len(MSG))
895 except socket.error:
896 pass
897 else:
898 self.fail("Error trying to do non-blocking recv.")
899 read, write, err = select.select([conn], [], [])
900 if conn in read:
901 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000902 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000903 else:
904 self.fail("Error during select call to non-blocking socket.")
905
906 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000907 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000908 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000909 self.cli.send(MSG)
910
911class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000912 """Unit tests for the object returned by socket.makefile()
913
Antoine Pitrou674f4002010-10-13 16:25:33 +0000914 self.read_file is the io object returned by makefile() on
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000915 the client connection. You can read from this file to
916 get output from the server.
917
Antoine Pitrou674f4002010-10-13 16:25:33 +0000918 self.write_file is the io object returned by makefile() on the
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000919 server connection. You can write to this file to send output
920 to the client.
921 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000922
Guido van Rossume9f66142002-08-07 15:46:19 +0000923 bufsize = -1 # Use default buffer size
Antoine Pitrou674f4002010-10-13 16:25:33 +0000924 encoding = 'utf8'
925 errors = 'strict'
926 newline = None
927
928 read_mode = 'rb'
929 read_msg = MSG
930 write_mode = 'wb'
931 write_msg = MSG
Guido van Rossume9f66142002-08-07 15:46:19 +0000932
Guido van Rossum24e4af82002-06-12 19:18:08 +0000933 def __init__(self, methodName='runTest'):
934 SocketConnectedTest.__init__(self, methodName=methodName)
935
936 def setUp(self):
937 SocketConnectedTest.setUp(self)
Antoine Pitrou674f4002010-10-13 16:25:33 +0000938 self.read_file = self.cli_conn.makefile(
939 self.read_mode, self.bufsize,
940 encoding = self.encoding,
941 errors = self.errors,
942 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000943
944 def tearDown(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000945 self.read_file.close()
946 self.assertTrue(self.read_file.closed)
947 self.read_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +0000948 SocketConnectedTest.tearDown(self)
949
950 def clientSetUp(self):
951 SocketConnectedTest.clientSetUp(self)
Antoine Pitrou674f4002010-10-13 16:25:33 +0000952 self.write_file = self.serv_conn.makefile(
953 self.write_mode, self.bufsize,
954 encoding = self.encoding,
955 errors = self.errors,
956 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000957
958 def clientTearDown(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000959 self.write_file.close()
960 self.assertTrue(self.write_file.closed)
961 self.write_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +0000962 SocketConnectedTest.clientTearDown(self)
963
964 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000965 # Performing small file read test
Antoine Pitrou674f4002010-10-13 16:25:33 +0000966 first_seg = self.read_file.read(len(self.read_msg)-3)
967 second_seg = self.read_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000968 msg = first_seg + second_seg
Antoine Pitrou674f4002010-10-13 16:25:33 +0000969 self.assertEqual(msg, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000970
971 def _testSmallRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000972 self.write_file.write(self.write_msg)
973 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000974
Guido van Rossum8c943832002-08-08 01:00:28 +0000975 def testFullRead(self):
976 # read until EOF
Antoine Pitrou674f4002010-10-13 16:25:33 +0000977 msg = self.read_file.read()
978 self.assertEqual(msg, self.read_msg)
Guido van Rossum8c943832002-08-08 01:00:28 +0000979
980 def _testFullRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000981 self.write_file.write(self.write_msg)
982 self.write_file.close()
Guido van Rossum8c943832002-08-08 01:00:28 +0000983
Guido van Rossum24e4af82002-06-12 19:18:08 +0000984 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000985 # Performing unbuffered file read test
Antoine Pitrou674f4002010-10-13 16:25:33 +0000986 buf = type(self.read_msg)()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000987 while 1:
Antoine Pitrou674f4002010-10-13 16:25:33 +0000988 char = self.read_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000989 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000990 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000991 buf += char
Antoine Pitrou674f4002010-10-13 16:25:33 +0000992 self.assertEqual(buf, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000993
994 def _testUnbufferedRead(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +0000995 self.write_file.write(self.write_msg)
996 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000997
998 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000999 # Performing file readline test
Antoine Pitrou674f4002010-10-13 16:25:33 +00001000 line = self.read_file.readline()
1001 self.assertEqual(line, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001002
1003 def _testReadline(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001004 self.write_file.write(self.write_msg)
1005 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001006
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001007 def testCloseAfterMakefile(self):
1008 # The file returned by makefile should keep the socket open.
1009 self.cli_conn.close()
1010 # read until EOF
Antoine Pitrou674f4002010-10-13 16:25:33 +00001011 msg = self.read_file.read()
1012 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001013
1014 def _testCloseAfterMakefile(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001015 self.write_file.write(self.write_msg)
1016 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001017
1018 def testMakefileAfterMakefileClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001019 self.read_file.close()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001020 msg = self.cli_conn.recv(len(MSG))
Antoine Pitrou674f4002010-10-13 16:25:33 +00001021 if isinstance(self.read_msg, str):
1022 msg = msg.decode()
1023 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001024
1025 def _testMakefileAfterMakefileClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001026 self.write_file.write(self.write_msg)
1027 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001028
Tim Peters116d83c2004-03-28 02:20:45 +00001029 def testClosedAttr(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001030 self.assertTrue(not self.read_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00001031
1032 def _testClosedAttr(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001033 self.assertTrue(not self.write_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00001034
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001035 def testAttributes(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001036 self.assertEqual(self.read_file.mode, self.read_mode)
1037 self.assertEqual(self.read_file.name, self.cli_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001038
1039 def _testAttributes(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001040 self.assertEqual(self.write_file.mode, self.write_mode)
1041 self.assertEqual(self.write_file.name, self.serv_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001042
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001043 def testRealClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001044 self.read_file.close()
1045 self.assertRaises(ValueError, self.read_file.fileno)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001046 self.cli_conn.close()
1047 self.assertRaises(socket.error, self.cli_conn.getsockname)
1048
1049 def _testRealClose(self):
1050 pass
1051
1052
Guido van Rossume9f66142002-08-07 15:46:19 +00001053class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
1054
1055 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +00001056
Guido van Rossume9f66142002-08-07 15:46:19 +00001057 In this case (and in this case only), it should be possible to
1058 create a file object, read a line from it, create another file
1059 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +00001060 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +00001061 when reading multiple requests from the same socket."""
1062
1063 bufsize = 0 # Use unbuffered mode
1064
1065 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001066 # Read a line, create a new file object, read another line with it
Antoine Pitrou674f4002010-10-13 16:25:33 +00001067 line = self.read_file.readline() # first line
1068 self.assertEqual(line, b"A. " + self.write_msg) # first line
1069 self.read_file = self.cli_conn.makefile('rb', 0)
1070 line = self.read_file.readline() # second line
1071 self.assertEqual(line, b"B. " + self.write_msg) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +00001072
1073 def _testUnbufferedReadline(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001074 self.write_file.write(b"A. " + self.write_msg)
1075 self.write_file.write(b"B. " + self.write_msg)
1076 self.write_file.flush()
Guido van Rossume9f66142002-08-07 15:46:19 +00001077
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001078 def testMakefileClose(self):
1079 # The file returned by makefile should keep the socket open...
1080 self.cli_conn.close()
1081 msg = self.cli_conn.recv(1024)
Antoine Pitrou674f4002010-10-13 16:25:33 +00001082 self.assertEqual(msg, self.read_msg)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001083 # ...until the file is itself closed
Antoine Pitrou674f4002010-10-13 16:25:33 +00001084 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001085 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
1086
1087 def _testMakefileClose(self):
Antoine Pitrou674f4002010-10-13 16:25:33 +00001088 self.write_file.write(self.write_msg)
1089 self.write_file.flush()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001090
1091 def testMakefileCloseSocketDestroy(self):
1092 refcount_before = sys.getrefcount(self.cli_conn)
Antoine Pitrou674f4002010-10-13 16:25:33 +00001093 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001094 refcount_after = sys.getrefcount(self.cli_conn)
1095 self.assertEqual(refcount_before - 1, refcount_after)
1096
1097 def _testMakefileCloseSocketDestroy(self):
1098 pass
1099
1100
Guido van Rossum8c943832002-08-08 01:00:28 +00001101class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1102
1103 bufsize = 1 # Default-buffered for reading; line-buffered for writing
1104
1105
1106class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1107
1108 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +00001109
Thomas Woutersb2137042007-02-01 18:02:27 +00001110
Antoine Pitrou674f4002010-10-13 16:25:33 +00001111class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase):
1112 """Tests for socket.makefile() in text mode (rather than binary)"""
1113
1114 read_mode = 'r'
1115 read_msg = MSG.decode('utf8')
1116 write_mode = 'wb'
1117 write_msg = MSG
1118 newline = ''
1119
1120
1121class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase):
1122 """Tests for socket.makefile() in text mode (rather than binary)"""
1123
1124 read_mode = 'rb'
1125 read_msg = MSG
1126 write_mode = 'w'
1127 write_msg = MSG.decode('utf8')
1128 newline = ''
1129
1130
1131class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase):
1132 """Tests for socket.makefile() in text mode (rather than binary)"""
1133
1134 read_mode = 'r'
1135 read_msg = MSG.decode('utf8')
1136 write_mode = 'w'
1137 write_msg = MSG.decode('utf8')
1138 newline = ''
1139
1140
Guido van Rossumd8faa362007-04-27 19:54:29 +00001141class NetworkConnectionTest(object):
1142 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001143
Guido van Rossumd8faa362007-04-27 19:54:29 +00001144 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001145 # We're inherited below by BasicTCPTest2, which also inherits
1146 # BasicTCPTest, which defines self.port referenced below.
1147 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001148 self.serv_conn = self.cli
1149
1150class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
1151 """Tests that NetworkConnection does not break existing TCP functionality.
1152 """
1153
1154class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001155
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001156 class MockSocket(socket.socket):
1157 def connect(self, *args):
1158 raise socket.timeout('timed out')
1159
1160 @contextlib.contextmanager
1161 def mocked_socket_module(self):
1162 """Return a socket which times out on connect"""
1163 old_socket = socket.socket
1164 socket.socket = self.MockSocket
1165 try:
1166 yield
1167 finally:
1168 socket.socket = old_socket
1169
1170 def test_connect(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001171 port = support.find_unused_port()
Antoine Pitrou4d7979b2010-09-07 21:22:56 +00001172 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1173 try:
1174 cli.connect((HOST, port))
1175 except socket.error as err:
1176 self.assertEqual(err.errno, errno.ECONNREFUSED)
1177 else:
1178 self.fail("socket.error not raised")
1179
1180 def test_create_connection(self):
1181 # Issue #9792: errors raised by create_connection() should have
1182 # a proper errno attribute.
1183 port = support.find_unused_port()
1184 try:
1185 socket.create_connection((HOST, port))
1186 except socket.error as err:
1187 self.assertEqual(err.errno, errno.ECONNREFUSED)
1188 else:
1189 self.fail("socket.error not raised")
1190
1191 def test_create_connection_timeout(self):
1192 # Issue #9792: create_connection() should not recast timeout errors
1193 # as generic socket errors.
1194 with self.mocked_socket_module():
1195 with self.assertRaises(socket.timeout):
1196 socket.create_connection((HOST, 1234))
1197
Guido van Rossumd8faa362007-04-27 19:54:29 +00001198
1199class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
1200
1201 def __init__(self, methodName='runTest'):
1202 SocketTCPTest.__init__(self, methodName=methodName)
1203 ThreadableTest.__init__(self)
1204
1205 def clientSetUp(self):
1206 pass
1207
1208 def clientTearDown(self):
1209 self.cli.close()
1210 self.cli = None
1211 ThreadableTest.clientTearDown(self)
1212
1213 def _justAccept(self):
1214 conn, addr = self.serv.accept()
1215
1216 testFamily = _justAccept
1217 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001218 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001219 self.assertEqual(self.cli.family, 2)
1220
1221 testTimeoutDefault = _justAccept
1222 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001223 # passing no explicit timeout uses socket's global default
Georg Brandlab91fde2009-08-13 08:51:18 +00001224 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001225 socket.setdefaulttimeout(42)
1226 try:
1227 self.cli = socket.create_connection((HOST, self.port))
1228 finally:
1229 socket.setdefaulttimeout(None)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +00001230 self.assertEqual(self.cli.gettimeout(), 42)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001231
1232 testTimeoutNone = _justAccept
1233 def _testTimeoutNone(self):
1234 # None timeout means the same as sock.settimeout(None)
Georg Brandlab91fde2009-08-13 08:51:18 +00001235 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001236 socket.setdefaulttimeout(30)
1237 try:
1238 self.cli = socket.create_connection((HOST, self.port), timeout=None)
1239 finally:
1240 socket.setdefaulttimeout(None)
1241 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001242
1243 testTimeoutValueNamed = _justAccept
1244 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001245 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001246 self.assertEqual(self.cli.gettimeout(), 30)
1247
1248 testTimeoutValueNonamed = _justAccept
1249 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001250 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001251 self.assertEqual(self.cli.gettimeout(), 30)
1252
Guido van Rossumd8faa362007-04-27 19:54:29 +00001253class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1254
1255 def __init__(self, methodName='runTest'):
1256 SocketTCPTest.__init__(self, methodName=methodName)
1257 ThreadableTest.__init__(self)
1258
1259 def clientSetUp(self):
1260 pass
1261
1262 def clientTearDown(self):
1263 self.cli.close()
1264 self.cli = None
1265 ThreadableTest.clientTearDown(self)
1266
1267 def testInsideTimeout(self):
1268 conn, addr = self.serv.accept()
1269 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001270 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001271 testOutsideTimeout = testInsideTimeout
1272
1273 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001274 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001275 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001276 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001277
1278 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001279 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Georg Brandlab91fde2009-08-13 08:51:18 +00001280 self.assertRaises(socket.timeout, lambda: sock.recv(5))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001281
1282
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001283class TCPTimeoutTest(SocketTCPTest):
1284
1285 def testTCPTimeout(self):
1286 def raise_timeout(*args, **kwargs):
1287 self.serv.settimeout(1.0)
1288 self.serv.accept()
Georg Brandlab91fde2009-08-13 08:51:18 +00001289 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001290 "Error generating a timeout exception (TCP)")
1291
1292 def testTimeoutZero(self):
1293 ok = False
1294 try:
1295 self.serv.settimeout(0.0)
1296 foo = self.serv.accept()
1297 except socket.timeout:
1298 self.fail("caught timeout instead of error (TCP)")
1299 except socket.error:
1300 ok = True
1301 except:
1302 self.fail("caught unexpected exception (TCP)")
1303 if not ok:
1304 self.fail("accept() returned success when we did not expect it")
1305
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001306 def testInterruptedTimeout(self):
1307 # XXX I don't know how to do this test on MSWindows or any other
1308 # plaform that doesn't support signal.alarm() or os.kill(), though
1309 # the bug should have existed on all platforms.
1310 if not hasattr(signal, "alarm"):
1311 return # can only test on *nix
1312 self.serv.settimeout(5.0) # must be longer than alarm
1313 class Alarm(Exception):
1314 pass
1315 def alarm_handler(signal, frame):
1316 raise Alarm
1317 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1318 try:
1319 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1320 try:
1321 foo = self.serv.accept()
1322 except socket.timeout:
1323 self.fail("caught timeout instead of Alarm")
1324 except Alarm:
1325 pass
1326 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001327 self.fail("caught other exception instead of Alarm:"
1328 " %s(%s):\n%s" %
1329 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001330 else:
1331 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001332 finally:
1333 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001334 except Alarm:
1335 self.fail("got Alarm in wrong place")
1336 finally:
1337 # no alarm can be pending. Safe to restore old handler.
1338 signal.signal(signal.SIGALRM, old_alarm)
1339
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001340class UDPTimeoutTest(SocketTCPTest):
1341
1342 def testUDPTimeout(self):
1343 def raise_timeout(*args, **kwargs):
1344 self.serv.settimeout(1.0)
1345 self.serv.recv(1024)
Georg Brandlab91fde2009-08-13 08:51:18 +00001346 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001347 "Error generating a timeout exception (UDP)")
1348
1349 def testTimeoutZero(self):
1350 ok = False
1351 try:
1352 self.serv.settimeout(0.0)
1353 foo = self.serv.recv(1024)
1354 except socket.timeout:
1355 self.fail("caught timeout instead of error (UDP)")
1356 except socket.error:
1357 ok = True
1358 except:
1359 self.fail("caught unexpected exception (UDP)")
1360 if not ok:
1361 self.fail("recv() returned success when we did not expect it")
1362
1363class TestExceptions(unittest.TestCase):
1364
1365 def testExceptionTree(self):
Georg Brandlab91fde2009-08-13 08:51:18 +00001366 self.assertTrue(issubclass(socket.error, Exception))
1367 self.assertTrue(issubclass(socket.herror, socket.error))
1368 self.assertTrue(issubclass(socket.gaierror, socket.error))
1369 self.assertTrue(issubclass(socket.timeout, socket.error))
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001370
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001371class TestLinuxAbstractNamespace(unittest.TestCase):
1372
1373 UNIX_PATH_MAX = 108
1374
1375 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001376 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001377 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1378 s1.bind(address)
1379 s1.listen(1)
1380 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1381 s2.connect(s1.getsockname())
1382 s1.accept()
1383 self.assertEqual(s1.getsockname(), address)
1384 self.assertEqual(s2.getpeername(), address)
1385
1386 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001387 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001388 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1389 s.bind(address)
1390 self.assertEqual(s.getsockname(), address)
1391
1392 def testNameOverflow(self):
1393 address = "\x00" + "h" * self.UNIX_PATH_MAX
1394 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1395 self.assertRaises(socket.error, s.bind, address)
1396
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001397
Thomas Wouters477c8d52006-05-27 19:21:47 +00001398class BufferIOTest(SocketConnectedTest):
1399 """
1400 Test the buffer versions of socket.recv() and socket.send().
1401 """
1402 def __init__(self, methodName='runTest'):
1403 SocketConnectedTest.__init__(self, methodName=methodName)
1404
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001405 def testRecvInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001406 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001407 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001408 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001409 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001410 self.assertEqual(msg, MSG)
1411
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001412 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001413 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001414 self.serv_conn.send(buf)
1415
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001416 def testRecvFromInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001417 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001418 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001419 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001420 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001421 self.assertEqual(msg, MSG)
1422
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001423 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001424 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001425 self.serv_conn.send(buf)
1426
Christian Heimes043d6f62008-01-07 17:19:16 +00001427
1428TIPC_STYPE = 2000
1429TIPC_LOWER = 200
1430TIPC_UPPER = 210
1431
1432def isTipcAvailable():
1433 """Check if the TIPC module is loaded
1434
1435 The TIPC module is not loaded automatically on Ubuntu and probably
1436 other Linux distros.
1437 """
1438 if not hasattr(socket, "AF_TIPC"):
1439 return False
1440 if not os.path.isfile("/proc/modules"):
1441 return False
1442 with open("/proc/modules") as f:
1443 for line in f:
1444 if line.startswith("tipc "):
1445 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001446 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001447 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1448 return False
1449
1450class TIPCTest (unittest.TestCase):
1451 def testRDM(self):
1452 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1453 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1454
1455 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1456 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1457 TIPC_LOWER, TIPC_UPPER)
1458 srv.bind(srvaddr)
1459
1460 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1461 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1462 cli.sendto(MSG, sendaddr)
1463
1464 msg, recvaddr = srv.recvfrom(1024)
1465
1466 self.assertEqual(cli.getsockname(), recvaddr)
1467 self.assertEqual(msg, MSG)
1468
1469
1470class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1471 def __init__(self, methodName = 'runTest'):
1472 unittest.TestCase.__init__(self, methodName = methodName)
1473 ThreadableTest.__init__(self)
1474
1475 def setUp(self):
1476 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1477 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1478 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1479 TIPC_LOWER, TIPC_UPPER)
1480 self.srv.bind(srvaddr)
1481 self.srv.listen(5)
1482 self.serverExplicitReady()
1483 self.conn, self.connaddr = self.srv.accept()
1484
1485 def clientSetUp(self):
1486 # The is a hittable race between serverExplicitReady() and the
1487 # accept() call; sleep a little while to avoid it, otherwise
1488 # we could get an exception
1489 time.sleep(0.1)
1490 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1491 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1492 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1493 self.cli.connect(addr)
1494 self.cliaddr = self.cli.getsockname()
1495
1496 def testStream(self):
1497 msg = self.conn.recv(1024)
1498 self.assertEqual(msg, MSG)
1499 self.assertEqual(self.cliaddr, self.connaddr)
1500
1501 def _testStream(self):
1502 self.cli.send(MSG)
1503 self.cli.close()
1504
1505
Guido van Rossumb995eb72002-07-31 16:08:40 +00001506def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001507 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001508 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001509 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001510 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001511
1512 tests.extend([
1513 NonBlockingTCPTests,
1514 FileObjectClassTestCase,
1515 UnbufferedFileObjectClassTestCase,
1516 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001517 SmallBufferedFileObjectClassTestCase,
Antoine Pitrou674f4002010-10-13 16:25:33 +00001518 UnicodeReadFileObjectClassTestCase,
1519 UnicodeWriteFileObjectClassTestCase,
1520 UnicodeReadWriteFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001521 NetworkConnectionNoServer,
1522 NetworkConnectionAttributesTest,
1523 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001524 ])
Dave Cole331708b2004-08-09 04:51:41 +00001525 if hasattr(socket, "socketpair"):
1526 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001527 if sys.platform == 'linux2':
1528 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001529 if isTipcAvailable():
1530 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001531 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001532
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001533 thread_info = support.threading_setup()
1534 support.run_unittest(*tests)
1535 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001536
1537if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001538 test_main()